Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubCredentials.ts

247 lines8.6 KB

1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Crypto from "effect/Crypto";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Hex from "effect/encoding/Hex";
7import * as Exit from "effect/Exit";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as PlatformError from "effect/PlatformError";
11import * as Redacted from "effect/Redacted";
12import * as Schema from "effect/Schema";
13​
14import * as HostProcess from "@t3tools/shared/HostProcess";
15​
16import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
17import { readSourceControlHostSettings } from "@t3tools/source-control-core/client/definition";
18import type { ServerSettings } from "@t3tools/contracts";
19​
20import * as GitHubClient from "../client/definition.ts";
21​
22const TOKEN_TTL = Duration.minutes(5);
23const MISSING_TTL = Duration.seconds(10);
24​
25export const GitHubCredentialSource = Schema.Literals(["settings", "env", "gh"]);
26export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
27​
28export interface GitHubCredential {
29 readonly host: string;
30 readonly token: Redacted.Redacted<string>;
31 readonly source: GitHubCredentialSource;
32 readonly fingerprint: string;
34​
35export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
36 "GitHubCliMissingError",
37 { host: Schema.String },
38) {
39 override get message(): string {
40 return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
41 }
43​
44export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
45 "GitHubNotSignedInError",
46 { host: Schema.String, account: Schema.optional(Schema.String) },
47) {
48 override get message(): string {
49 return this.account === undefined
50 ? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`
51 : `No GitHub credential for ${this.account} on ${this.host}: run \`gh auth login --hostname ${this.host}\` for that account or pick another in Settings → Source Control.`;
52 }
54​
55export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(
56 "GitHubHostDisabledError",
57 { host: Schema.String },
58) {
59 override get message(): string {
60 return `GitHub host ${this.host} is turned off in Settings → Source Control.`;
61 }
63​
64export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
65 "GitHubCliFailedError",
66 { host: Schema.String, cause: Schema.Defect() },
67) {
68 override get message(): string {
69 return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
70 }
72​
73export type GitHubCredentialUnavailableError =
74 | GitHubCliMissingError
75 | GitHubNotSignedInError
76 | GitHubHostDisabledError
77 | GitHubCliFailedError;
78​
79export class GitHubCredentials extends Context.Service<
80 GitHubCredentials,
81 {
82 readonly get: (
83 host: string,
84 ) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
85 readonly invalidate: (host: string) => Effect.Effect<void>;
86 }
87>()("@t3tools/source-control-github/server/GitHubCredentials") {}
88​
89function normalizeHost(host: string): string {
90 return host.trim().toLowerCase();
92​
93/** Hosts gh treats as GitHub.com-like for `GH_TOKEN`: github.com and GHE.com data residency. */
94function isGitHubDotCom(host: string): boolean {
95 return host === "github.com" || host.endsWith(".ghe.com");
97​
98/**
99 * The environment token for a host, in gh's precedence order. gh hands `GH_ENTERPRISE_TOKEN` to
100 * any non-github.com host; here it only goes to the host `GH_HOST` names, because a remote URL
101 * picks the host and a hostile one must not receive an enterprise token.
102 */
103export function environmentToken(
104 host: string,
105 env: Readonly<Record<string, string | undefined>>,
106): string | null {
107 const names = isGitHubDotCom(host)
108 ? ["GH_TOKEN", "GITHUB_TOKEN"]
109 : env.GH_HOST?.trim().toLowerCase() === host
110 ? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
111 : [];
112 for (const name of names) {
113 const value = env[name]?.trim();
114 if (value) return value;
115 }
116 return null;
118​
119/** @public Service construction is part of the canonical Effect module API. */
120export const make = Effect.gen(function* () {
121 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
122 const process = sourceControlHost.process;
123 const crypto = yield* Crypto.Crypto;
124 const environment = yield* HostProcess.Environment;
125 const workingDirectory = yield* HostProcess.WorkingDirectory;
126​
127 const fingerprintOf = (host: string, token: string) =>
128 crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
129 Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
130 Effect.orDie,
131 );
132​
133 const fromGh = (host: string, account: string | undefined) =>
134 process
135 .run({
136 operation: "GitHubCredentials.get",
137 command: "gh",
138 args: [
139 "auth",
140 "token",
141 "--hostname",
142 host,
143 ...(account === undefined ? [] : ["--user", account]),
144 ],
145 cwd: workingDirectory,
146 // Never let gh print the token into a debug log.
147 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
148 timeoutMs: 10_000,
149 })
150 .pipe(
151 Effect.mapError((error) =>
152 error._tag === "VcsProcessSpawnError" &&
153 error.cause instanceof PlatformError.PlatformError &&
154 error.cause.reason._tag === "NotFound"
155 ? new GitHubCliMissingError({ host })
156 : // gh exits non-zero with "no oauth token" when it has no login for the host.
157 error._tag === "VcsProcessExitError"
158 ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
159 : new GitHubCliFailedError({ host, cause: error }),
160 ),
161 Effect.map((output) => output.stdout.trim()),
162 Effect.filterOrFail(
163 (token) => token !== "",
164 () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
165 ),
166 );
167​
168 const readSettings = (settings: ServerSettings) =>
169 readSourceControlHostSettings(
170 GitHubClient.settings,
171 settings.sourceControlHosts[GitHubClient.definition.kind],
172 );
173​
174 const hostChoice = (host: string) =>
175 sourceControlHost.settings.get.pipe(
176 Effect.map((settings) => readSettings(settings).hosts[host]),
177 Effect.orElseSucceed(() => undefined),
178 );
179​
180 const savedToken = (host: string) =>
181 sourceControlHost.settings.get.pipe(
182 Effect.map((settings) => readSettings(settings).tokens[host]?.trim() || null),
183 Effect.orElseSucceed(() => null),
184 );
185​
186 const cacheKey = (host: string, account: string | undefined) =>
187 account === undefined ? host : `${host}\u0000${account}`;
188​
189 const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
190 const [host = key, choice] = key.split("\u0000");
191 const fromEnv = environmentToken(host, environment);
192 const token =
193 fromEnv ??
194 (yield* fromGh(host, choice).pipe(
195 Effect.catchTags({
196 GitHubNotSignedInError: (error) =>
197 choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
198 }),
199 ));
200 return {
201 host,
202 token: Redacted.make(token),
203 source: fromEnv !== null ? "env" : "gh",
204 fingerprint: yield* fingerprintOf(host, token),
205 } satisfies GitHubCredential;
206 });
207​
208 const cache = yield* Cache.makeWith(lookup, {
209 capacity: 32,
210 timeToLive: (exit) =>
211 Exit.isSuccess(exit)
212 ? TOKEN_TTL
213 : Exit.findErrorOption(exit).pipe(
214 Option.exists((error) => error._tag === "GitHubCliFailedError"),
215 )
216 ? Duration.zero
217 : MISSING_TTL,
218 });
219​
220 return GitHubCredentials.of({
221 get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
222 const host = normalizeHost(rawHost);
223 const choice = yield* hostChoice(host);
224 if (choice?.enabled === false) {
225 return yield* new GitHubHostDisabledError({ host });
226 }
227 const saved = yield* savedToken(host);
228 if (saved !== null) {
229 return {
230 host,
231 token: Redacted.make(saved),
232 source: "settings",
233 fingerprint: yield* fingerprintOf(host, saved),
234 } satisfies GitHubCredential;
235 }
236 return yield* Cache.get(cache, cacheKey(host, choice?.account));
237 }),
238 invalidate: (rawHost) => {
239 const host = normalizeHost(rawHost);
240 return hostChoice(host).pipe(
241 Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
242 );
243 },
244 });
245});
246​
247export const layer = Layer.effect(GitHubCredentials, make);