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

GitHubAppSignIn.ts

467 lines17.6 KB

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