Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9
10import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
11import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
12import * as GitHubRest from "./GitHubRest.ts";
13
14const Installations = Schema.fromJsonString(
15 Schema.Struct({
16 installations: Schema.Array(
17 Schema.Struct({
18 id: Schema.Number,
19 repository_selection: Schema.String,
20 account: Schema.NullOr(Schema.Struct({ login: Schema.String })),
21 }),
22 ),
23 }),
24);
25
26const InstallationRepositories = Schema.fromJsonString(
27 Schema.Struct({ repositories: Schema.Array(Schema.Struct({ full_name: Schema.String })) }),
28);
29
30const Viewer = Schema.fromJsonString(Schema.Struct({ login: Schema.String }));
31
32const PAGE_SIZE = 100;
33const MAX_PAGES = 10;
34// Installing the app on another account should show up soon after the user comes back.
35const COVERAGE_TTL = Duration.minutes(2);
36// A failed read answers `covered`; keep that briefly so an outage is not re-asked per request.
37const COVERAGE_FAILURE_TTL = Duration.seconds(30);
38
39/** Whether the app sign-in reaches a repository; `signed-out` when the server is not signed in. */
40export type GitHubAppReach = "covered" | "not-covered" | "signed-out";
41
42/** Accounts that installed the app for all repositories, and repositories listed one by one. */
43interface AppCoverage {
44 readonly accounts: ReadonlySet<string>;
45 readonly repositories: ReadonlySet<string>;
46}
47
48export class GitHubAppAccess extends Context.Service<
49 GitHubAppAccess,
50 {
51 /**
52 * Whether an installation covers `owner/name`. A check that fails answers `covered`, so a
53 * GitHub hiccup does not nag the user.
54 */
55 readonly reach: (host: string, repository: string) => Effect.Effect<GitHubAppReach>;
56 /** The login the app sign-in acts as. */
57 readonly viewer: (host: string) => Effect.Effect<string, GitHubRequestPolicy.GitHubApiError>;
58 /**
59 * The credential for work pinned to one repository: the app's only where an installation is
60 * confirmed to cover it, the user's own otherwise when there is one.
61 */
62 readonly credentialFor: (
63 host: string,
64 repository: string,
65 cwd?: string,
66 ) => Effect.Effect<
67 GitHubRequestPolicy.GitHubHeldCredential,
68 GitHubRequestPolicy.GitHubApiError
69 >;
70 }
71>()("@t3tools/source-control-github/server/GitHubAppAccess") {}
72
73/** Callers may name a repository as a URL, `host/owner/name` or `owner/name.git`. */
74function ownerAndName(repository: string): string {
75 return repository
76 .trim()
77 .toLowerCase()
78 .replace(/\.git\/?$/, "")
79 .split(/[/:]/)
80 .filter((segment) => segment.length > 0)
81 .slice(-2)
82 .join("/");
83}
84
85/** @public */
86export const make = Effect.gen(function* () {
87 const api = yield* GitHubRest.GitHubRest;
88 const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
89
90 /** Reads `path` as the app sign-in, whatever credential outranks it elsewhere. */
91 const readAsApp = Effect.fn("GitHubAppAccess.readAsApp")(function* <A>(
92 host: string,
93 operation: string,
94 path: string,
95 schema: Schema.Codec<A, string>,
96 ) {
97 const app = yield* api.appCredential(host);
98 if (Option.isNone(app)) return Option.none<A>();
99 const response = yield* api.rest({ host, operation, path, allowReserve: true }).pipe(
100 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
101 host,
102 token: app.value.token,
103 credentialFingerprint: app.value.fingerprint,
104 }),
105 );
106 return Option.some(yield* Schema.decodeEffect(schema)(response.body));
107 });
108
109 const coverageOf = Effect.fn("GitHubAppAccess.coverageOf")(function* (host: string) {
110 const installations: Array<{
111 readonly id: number;
112 readonly repository_selection: string;
113 readonly account: { readonly login: string } | null;
114 }> = [];
115 for (let page = 1; page <= MAX_PAGES; page++) {
116 const listed = yield* readAsApp(
117 host,
118 "appInstallations",
119 `user/installations?per_page=${PAGE_SIZE}&page=${page}`,
120 Installations,
121 );
122 if (Option.isNone(listed)) return null;
123 installations.push(...listed.value.installations);
124 if (listed.value.installations.length < PAGE_SIZE) break;
125 }
126 const accounts = new Set<string>();
127 const repositories = new Set<string>();
128 for (const installation of installations) {
129 const login = installation.account?.login.toLowerCase();
130 if (login === undefined) continue;
131 if (installation.repository_selection === "all") {
132 accounts.add(login);
133 continue;
134 }
135 for (let page = 1; ; page++) {
136 // Past the cap the list is cut short; count the whole account as reached rather than nag.
137 if (page > MAX_PAGES) {
138 accounts.add(login);
139 break;
140 }
141 const listed = yield* readAsApp(
142 host,
143 "appInstallationRepositories",
144 `user/installations/${installation.id}/repositories?per_page=${PAGE_SIZE}&page=${page}`,
145 InstallationRepositories,
146 );
147 if (Option.isNone(listed)) return null;
148 for (const repository of listed.value.repositories) {
149 repositories.add(repository.full_name.toLowerCase());
150 }
151 if (listed.value.repositories.length < PAGE_SIZE) break;
152 }
153 }
154 return { accounts, repositories } satisfies AppCoverage;
155 });
156
157 const coverage = yield* Cache.makeWith(coverageOf, {
158 capacity: 8,
159 timeToLive: (exit) => (Exit.isSuccess(exit) ? COVERAGE_TTL : COVERAGE_FAILURE_TTL),
160 });
161
162 /** `unknown` when GitHub could not list the installations just now. */
163 const coverageFor = Effect.fn("GitHubAppAccess.coverageFor")(function* (
164 rawHost: string,
165 rawRepository: string,
166 ) {
167 const host = rawHost.trim().toLowerCase();
168 if (!appSignIn.enabled) return "signed-out" as const;
169 const known = yield* Cache.get(coverage, host).pipe(Effect.option);
170 if (Option.isNone(known)) return "unknown" as const;
171 if (known.value === null) return "signed-out" as const;
172 const repository = ownerAndName(rawRepository);
173 const owner = repository.split("/")[0] ?? "";
174 return known.value.accounts.has(owner) || known.value.repositories.has(repository)
175 ? ("covered" as const)
176 : ("not-covered" as const);
177 });
178
179 const reach: GitHubAppAccess["Service"]["reach"] = (host, repository) =>
180 coverageFor(host, repository).pipe(
181 Effect.map((answer) => (answer === "unknown" ? "covered" : answer)),
182 );
183
184 const viewer: GitHubAppAccess["Service"]["viewer"] = Effect.fn("GitHubAppAccess.viewer")(
185 function* (rawHost) {
186 const host = rawHost.trim().toLowerCase();
187 // A new sign-in can reach different installations than the cached answer.
188 yield* Cache.invalidate(coverage, host);
189 const login = yield* readAsApp(host, "appViewer", "user", Viewer).pipe(
190 Effect.catchTags({
191 SchemaError: () => Effect.succeed(Option.none<{ readonly login: string }>()),
192 }),
193 );
194 if (Option.isNone(login)) {
195 return yield* new GitHubRequestPolicy.GitHubApiAuthenticationError({
196 host,
197 operation: "appViewer",
198 });
199 }
200 return login.value.login;
201 },
202 );
203
204 const credentialFor: GitHubAppAccess["Service"]["credentialFor"] = Effect.fn(
205 "GitHubAppAccess.credentialFor",
206 )(function* (host, repository, cwd) {
207 // Pinned work cannot be handed on, so only confirmed app access keeps the app credential.
208 if ((yield* coverageFor(host, repository)) === "covered") {
209 return yield* api.credential(host, { cwd });
210 }
211 return yield* api
212 .credential(host, { personal: true, cwd })
213 .pipe(Effect.catch(() => api.credential(host, { cwd })));
214 });
215
216 return GitHubAppAccess.of({ reach, viewer, credentialFor });
217});
218
219export const layer = Layer.effect(GitHubAppAccess, make);