Open History to see the last commit
1import {
2 SourceControlProviderKind,
3 SourceControlSignInError,
4 type SourceControlSignInFailure,
5 type SourceControlSignInPrompt,
6} from "@t3tools/contracts";
7import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
8import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
9import * as Clock from "effect/Clock";
10import * as Context from "effect/Context";
11import * as Deferred from "effect/Deferred";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Ref from "effect/Ref";
18import * as Schema from "effect/Schema";
19import * as Schedule from "effect/Schedule";
20import * as Semaphore from "effect/Semaphore";
21import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
22import * as FeatureFlags from "@t3tools/shared/FeatureFlags";
23
24import * as GitHubClient from "../shared/definition.ts";
25
26const KIND = SourceControlProviderKind.make("github");
27const REQUEST_TIMEOUT = Duration.seconds(15);
28// Refresh ahead of expiry so a token never lapses between the check and a long request.
29const REFRESH_MARGIN_MS = Duration.toMillis(Duration.minutes(5));
30
31const GitHubAppSession = Schema.Struct({
32 accessToken: Schema.String,
33 /** Null when the app hands out tokens that do not expire. */
34 accessTokenExpiresAt: Schema.NullOr(Schema.Number),
35 refreshToken: Schema.NullOr(Schema.String),
36 refreshTokenExpiresAt: Schema.NullOr(Schema.Number),
37});
38type GitHubAppSession = typeof GitHubAppSession.Type;
39
40const GitHubAppSessionJson = Schema.fromJsonString(GitHubAppSession);
41const decodeSession = Schema.decodeUnknownOption(GitHubAppSessionJson);
42const encodeSession = Schema.encodeSync(GitHubAppSessionJson);
43
44// GitHub answers both token grants with HTTP 200 and puts refusals in `error`.
45const TokenResponse = Schema.Struct({
46 access_token: Schema.optional(Schema.String),
47 expires_in: Schema.optional(Schema.Number),
48 refresh_token: Schema.optional(Schema.String),
49 refresh_token_expires_in: Schema.optional(Schema.Number),
50 interval: Schema.optional(Schema.Number),
51 error: Schema.optional(Schema.String),
52 error_description: Schema.optional(Schema.String),
53});
54
55const DeviceCodeResponse = Schema.Struct({
56 device_code: Schema.optional(Schema.String),
57 user_code: Schema.optional(Schema.String),
58 verification_uri: Schema.optional(Schema.String),
59 expires_in: Schema.optional(Schema.Number),
60 interval: Schema.optional(Schema.Number),
61 error: Schema.optional(Schema.String),
62 error_description: Schema.optional(Schema.String),
63});
64
65export class GitHubAppSessionError extends Schema.TaggedError<GitHubAppSessionError>()(
66 "GitHubAppSessionError",
67 { host: Schema.String, cause: Schema.Defect() },
68) {
69 override get message(): string {
70 return `Could not refresh the ${GitHubClient.APP_SIGN_IN.appName} sign-in for ${this.host}. Check the server's connection to GitHub, or sign in again in Settings → Source control & issues.`;
71 }
72}
73
74export class GitHubAppSignIn extends Context.Service<
75 GitHubAppSignIn,
76 {
77 /** Whether the server is configured with the app's client ID. */
78 readonly enabled: boolean;
79 /** The signed-in access token for `host`, refreshed when due; none when not signed in. */
80 readonly token: (host: string) => Effect.Effect<Option.Option<string>, GitHubAppSessionError>;
81 /** Refreshes on the next `token` when `rejected` is the token GitHub just refused. */
82 readonly invalidate: (host: string, rejected: string) => Effect.Effect<void>;
83 readonly start: (
84 host: string,
85 ) => Effect.Effect<SourceControlSignInPrompt, SourceControlSignInError>;
86 /** Resolves once the sign-in `start` began has saved a session. */
87 readonly wait: (host: string) => Effect.Effect<void, SourceControlSignInError>;
88 readonly cancel: (host: string) => Effect.Effect<void>;
89 }
90>()("@t3tools/source-control-github/server/GitHubAppSignIn") {}
91
92interface PendingSignIn {
93 readonly deferred: Deferred.Deferred<void, SourceControlSignInError>;
94 readonly fiber: Fiber.Fiber<boolean>;
95}
96
97const signInError = (host: string, reason: SourceControlSignInFailure, detail: string) =>
98 new SourceControlSignInError({ provider: KIND, host, reason, detail });
99
100/** @public */
101export const make = Effect.gen(function* () {
102 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
103 const httpClient = yield* HttpClient.HttpClient;
104 // Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show.
105 const clientId = Option.getOrElse((yield* FeatureFlags.FeatureFlags).githubAppClientId, () => "");
106 const enabled = clientId !== "";
107 const scope = yield* Effect.scope;
108 const refreshLock = yield* Semaphore.make(1);
109 const refused = yield* Ref.make<ReadonlySet<string>>(new Set());
110 const pending = yield* Ref.make<ReadonlyMap<string, PendingSignIn>>(new Map());
111
112 const isAppHost = (host: string) =>
113 enabled && GitHubClient.APP_SIGN_IN.hosts.includes(host.trim().toLowerCase());
114
115 const readSignIns = sourceControlHost.settings.get.pipe(
116 Effect.map(
117 (settings) =>
118 readSourceControlHostSettings(
119 GitHubClient.settings,
120 settings.sourceControlHosts[GitHubClient.definition.kind],
121 ).signIns,
122 ),
123 Effect.orElseSucceed((): Readonly<Record<string, string>> => ({})),
124 );
125
126 const readSession = (host: string) =>
127 readSignIns.pipe(Effect.map((signIns) => decodeSession(signIns[host] ?? "")));
128
129 const writeSession = Effect.fn("GitHubAppSignIn.writeSession")(function* (
130 host: string,
131 session: GitHubAppSession | null,
132 ) {
133 const signIns = { ...(yield* readSignIns) };
134 if (session === null) delete signIns[host];
135 else signIns[host] = encodeSession(session);
136 yield* sourceControlHost.settings.update({
137 sourceControlHosts: { [GitHubClient.definition.kind]: { signIns } },
138 });
139 });
140
141 /**
142 * Writes `next` only while the stored session is still the one a refresh started from, so a
143 * sign-out or a newer sign-in during the request is not undone.
144 */
145 const replaceSession = Effect.fn("GitHubAppSignIn.replaceSession")(function* (
146 host: string,
147 from: GitHubAppSession,
148 next: GitHubAppSession | null,
149 ) {
150 const current = yield* readSession(host);
151 if (Option.isNone(current) || current.value.accessToken !== from.accessToken) return false;
152 yield* writeSession(host, next);
153 return true;
154 });
155
156 const postForm = <S extends Schema.Top>(
157 host: string,
158 path: string,
159 body: Record<string, string>,
160 schema: S,
161 ) =>
162 httpClient
163 .execute(
164 HttpClientRequest.post(`https://${host}${path}`).pipe(
165 HttpClientRequest.setHeaders({ accept: "application/json", "user-agent": "t3code" }),
166 HttpClientRequest.bodyUrlParams(body),
167 ),
168 )
169 .pipe(
170 Effect.flatMap(HttpClientResponse.filterStatusOk),
171 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
172 Effect.timeout(REQUEST_TIMEOUT),
173 );
174
175 const sessionFrom = (
176 now: number,
177 response: typeof TokenResponse.Type & { readonly access_token: string },
178 ): GitHubAppSession => ({
179 accessToken: response.access_token,
180 accessTokenExpiresAt:
181 response.expires_in === undefined ? null : now + response.expires_in * 1_000,
182 refreshToken: response.refresh_token ?? null,
183 refreshTokenExpiresAt:
184 response.refresh_token_expires_in === undefined
185 ? null
186 : now + response.refresh_token_expires_in * 1_000,
187 });
188
189 const refresh = Effect.fn("GitHubAppSignIn.refresh")(function* (
190 host: string,
191 session: GitHubAppSession,
192 ) {
193 const now = yield* Clock.currentTimeMillis;
194 if (
195 session.refreshToken === null ||
196 (session.refreshTokenExpiresAt !== null && session.refreshTokenExpiresAt <= now)
197 ) {
198 yield* replaceSession(host, session, null).pipe(Effect.ignore);
199 return Option.none<string>();
200 }
201 const response = yield* postForm(
202 host,
203 "/login/oauth/access_token",
204 {
205 client_id: clientId,
206 grant_type: "refresh_token",
207 refresh_token: session.refreshToken,
208 },
209 TokenResponse,
210 ).pipe(Effect.mapError((cause) => new GitHubAppSessionError({ host, cause })));
211 if (
212 response.error === "bad_refresh_token" ||
213 response.error === "incorrect_client_credentials"
214 ) {
215 // Final: the user revoked the app, the session lapsed, or this server's client cannot refresh it.
216 yield* Effect.logWarning("GitHub refused the app sign-in refresh; signing out.", {
217 host,
218 error: response.error,
219 });
220 yield* replaceSession(host, session, null).pipe(Effect.ignore);
221 return Option.none<string>();
222 }
223 if (response.access_token === undefined) {
224 return yield* new GitHubAppSessionError({
225 host,
226 cause: new Error(`GitHub did not refresh the sign-in (${response.error ?? "no token"}).`),
227 });
228 }
229 const next = sessionFrom(now, {
230 ...response,
231 access_token: response.access_token,
232 });
233 // GitHub has retired the old pair, so an unsaved new one is still the only usable token.
234 const saved = yield* replaceSession(host, session, next).pipe(
235 Effect.retry({ times: 2, schedule: Schedule.spaced(Duration.millis(250)) }),
236 Effect.catch((cause) =>
237 Effect.logError("Could not save the refreshed app sign-in; using it unsaved.", {
238 host,
239 cause,
240 }).pipe(Effect.as(true)),
241 ),
242 );
243 if (saved) return Option.some(next.accessToken);
244 // Signed out or signed in again meanwhile: serve whatever is stored now.
245 return Option.map(yield* readSession(host), (current) => current.accessToken);
246 });
247
248 const isFresh = (session: GitHubAppSession, now: number) =>
249 session.accessTokenExpiresAt === null || now < session.accessTokenExpiresAt - REFRESH_MARGIN_MS;
250
251 const token: GitHubAppSignIn["Service"]["token"] = Effect.fn("GitHubAppSignIn.token")(
252 function* (rawHost) {
253 const host = rawHost.trim().toLowerCase();
254 if (!isAppHost(host)) return Option.none();
255 const session = yield* readSession(host);
256 if (Option.isNone(session)) return Option.none();
257 const now = yield* Clock.currentTimeMillis;
258 if (
259 isFresh(session.value, now) &&
260 !(yield* Ref.get(refused)).has(session.value.accessToken)
261 ) {
262 return Option.some(session.value.accessToken);
263 }
264 return yield* refreshLock.withPermits(1)(
265 Effect.gen(function* () {
266 // Another request may have refreshed while this one queued.
267 const current = yield* readSession(host);
268 if (Option.isNone(current)) return Option.none<string>();
269 const refusedTokens = yield* Ref.get(refused);
270 const now = yield* Clock.currentTimeMillis;
271 if (isFresh(current.value, now) && !refusedTokens.has(current.value.accessToken)) {
272 return Option.some(current.value.accessToken);
273 }
274 const usable = Option.some(current.value.accessToken).pipe(
275 Option.filter(
276 (accessToken) =>
277 !refusedTokens.has(accessToken) &&
278 (current.value.accessTokenExpiresAt === null ||
279 now < current.value.accessTokenExpiresAt),
280 ),
281 );
282 // A refresh ahead of expiry that fails leaves the still-valid token in use.
283 return yield* refresh(host, current.value).pipe(
284 Effect.catchTags({
285 GitHubAppSessionError: (error) =>
286 Option.isSome(usable) ? Effect.succeed(usable) : Effect.fail(error),
287 }),
288 );
289 }),
290 );
291 },
292 );
293
294 const invalidate: GitHubAppSignIn["Service"]["invalidate"] = Effect.fn(
295 "GitHubAppSignIn.invalidate",
296 )(function* (rawHost, rejected) {
297 const session = yield* readSession(rawHost.trim().toLowerCase());
298 // A refused fallback token says nothing about the app session.
299 if (Option.isNone(session) || session.value.accessToken !== rejected) return;
300 yield* Ref.update(refused, (current) => new Set([...current, rejected]));
301 });
302
303 const poll = Effect.fn("GitHubAppSignIn.poll")(function* (
304 host: string,
305 deviceCode: string,
306 expiresAt: number,
307 initialInterval: number,
308 ) {
309 let interval = initialInterval;
310 while (true) {
311 yield* Effect.sleep(Duration.seconds(interval));
312 const now = yield* Clock.currentTimeMillis;
313 if (now >= expiresAt) {
314 return yield* signInError(host, "expired", "The sign-in code expired. Start again.");
315 }
316 const answer = yield* postForm(
317 host,
318 "/login/oauth/access_token",
319 {
320 client_id: clientId,
321 device_code: deviceCode,
322 grant_type: "urn:ietf:params:oauth:grant-type:device_code",
323 },
324 TokenResponse,
325 ).pipe(Effect.option);
326 // A dropped poll is retried on the next tick; the code stays valid until it expires.
327 if (Option.isNone(answer)) continue;
328 const response = answer.value;
329 if (response.access_token !== undefined) {
330 const accessToken = response.access_token;
331 return yield* writeSession(
332 host,
333 sessionFrom(yield* Clock.currentTimeMillis, { ...response, access_token: accessToken }),
334 ).pipe(
335 Effect.mapError(
336 (cause) =>
337 new SourceControlSignInError({
338 provider: KIND,
339 host,
340 reason: "failed",
341 detail: "The server could not save the sign-in.",
342 cause,
343 }),
344 ),
345 );
346 }
347 switch (response.error) {
348 case "authorization_pending":
349 continue;
350 case "slow_down":
351 interval = response.interval ?? interval + 5;
352 continue;
353 case "expired_token":
354 return yield* signInError(host, "expired", "The sign-in code expired. Start again.");
355 case "access_denied":
356 return yield* signInError(host, "denied", "The sign-in was cancelled on GitHub.");
357 default:
358 return yield* signInError(
359 host,
360 "failed",
361 response.error_description ??
362 `GitHub refused the sign-in (${response.error ?? "no reason given"}).`,
363 );
364 }
365 }
366 });
367
368 const start: GitHubAppSignIn["Service"]["start"] = Effect.fn("GitHubAppSignIn.start")(
369 function* (rawHost) {
370 const host = rawHost.trim().toLowerCase();
371 if (!enabled) {
372 return yield* signInError(
373 host,
374 "unsupported",
375 `This server is not set up to sign in with ${GitHubClient.APP_SIGN_IN.appName}.`,
376 );
377 }
378 if (!isAppHost(host)) {
379 return yield* signInError(
380 host,
381 "unsupported",
382 `${GitHubClient.APP_SIGN_IN.appName} only signs in to ${GitHubClient.APP_SIGN_IN.hosts.join(", ")}. Use a token or the GitHub CLI for ${host}.`,
383 );
384 }
385 const code = yield* postForm(
386 host,
387 "/login/device/code",
388 { client_id: clientId },
389 DeviceCodeResponse,
390 ).pipe(
391 Effect.mapError(
392 (cause) =>
393 new SourceControlSignInError({
394 provider: KIND,
395 host,
396 reason: "failed",
397 detail: "The server could not reach GitHub to start the sign-in.",
398 cause,
399 }),
400 ),
401 );
402 if (
403 code.device_code === undefined ||
404 code.user_code === undefined ||
405 code.verification_uri === undefined ||
406 code.expires_in === undefined
407 ) {
408 return yield* signInError(
409 host,
410 "failed",
411 code.error_description ??
412 `GitHub would not start the sign-in (${code.error ?? "no reason given"}).`,
413 );
414 }
415 const expiresAt = (yield* Clock.currentTimeMillis) + code.expires_in * 1_000;
416 const deferred = yield* Deferred.make<void, SourceControlSignInError>();
417 const fiber = yield* poll(host, code.device_code, expiresAt, code.interval ?? 5).pipe(
418 Effect.tap(() => Ref.set(refused, new Set())),
419 Deferred.into(deferred),
420 Effect.forkIn(scope),
421 );
422 const previous = yield* Ref.modify(pending, (current) => [
423 current.get(host),
424 new Map(current).set(host, { deferred, fiber }),
425 ]);
426 if (previous !== undefined) {
427 yield* Deferred.fail(
428 previous.deferred,
429 signInError(host, "failed", "A newer sign-in replaced this one."),
430 );
431 yield* Fiber.interrupt(previous.fiber);
432 }
433 return {
434 userCode: code.user_code,
435 verificationUri: code.verification_uri,
436 expiresAt,
437 } satisfies SourceControlSignInPrompt;
438 },
439 );
440
441 const wait: GitHubAppSignIn["Service"]["wait"] = Effect.fn("GitHubAppSignIn.wait")(
442 function* (rawHost) {
443 const host = rawHost.trim().toLowerCase();
444 const current = (yield* Ref.get(pending)).get(host);
445 if (current === undefined) {
446 return yield* signInError(host, "not-started", "No sign-in is in progress. Start again.");
447 }
448 return yield* Deferred.await(current.deferred);
449 },
450 );
451
452 const cancel: GitHubAppSignIn["Service"]["cancel"] = Effect.fn("GitHubAppSignIn.cancel")(
453 function* (rawHost) {
454 const host = rawHost.trim().toLowerCase();
455 const current = (yield* Ref.get(pending)).get(host);
456 if (current === undefined) return;
457 yield* Deferred.fail(
458 current.deferred,
459 signInError(host, "cancelled", "The sign-in was cancelled."),
460 );
461 yield* Fiber.interrupt(current.fiber);
462 },
463 );
464
465 return GitHubAppSignIn.of({ enabled, token, invalidate, start, wait, cancel });
466});
467
468export const layer = Layer.effect(GitHubAppSignIn, make);