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 ) => Effect.Effect<
66 GitHubRequestPolicy.GitHubHeldCredential,
67 GitHubRequestPolicy.GitHubApiError
68 >;
69 }
70>()("@t3tools/source-control-github/server/GitHubAppAccess") {}
71
72/** Callers may name a repository as a URL, `host/owner/name` or `owner/name.git`. */
73function ownerAndName(repository: string): string {
74 return repository
75 .trim()
76 .toLowerCase()
77 .replace(/\.git\/?$/, "")
78 .split(/[/:]/)
79 .filter((segment) => segment.length > 0)
80 .slice(-2)
81 .join("/");
82}
83
84/** @public */
85export const make = Effect.gen(function* () {
86 const api = yield* GitHubRest.GitHubRest;
87 const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
88
89 /** Reads `path` as the app sign-in, whatever credential outranks it elsewhere. */
90 const readAsApp = Effect.fn("GitHubAppAccess.readAsApp")(function* <A>(
91 host: string,
92 operation: string,
93 path: string,
94 schema: Schema.Codec<A, string>,
95 ) {
96 const app = yield* api.appCredential(host);
97 if (Option.isNone(app)) return Option.none<A>();
98 const response = yield* api.rest({ host, operation, path, allowReserve: true }).pipe(
99 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
100 host,
101 token: app.value.token,
102 credentialFingerprint: app.value.fingerprint,
103 }),
104 );
105 return Option.some(yield* Schema.decodeEffect(schema)(response.body));
106 });
107
108 const coverageOf = Effect.fn("GitHubAppAccess.coverageOf")(function* (host: string) {
109 const installations: Array<{
110 readonly id: number;
111 readonly repository_selection: string;
112 readonly account: { readonly login: string } | null;
113 }> = [];
114 for (let page = 1; page <= MAX_PAGES; page++) {
115 const listed = yield* readAsApp(
116 host,
117 "appInstallations",
118 `user/installations?per_page=${PAGE_SIZE}&page=${page}`,
119 Installations,
120 );
121 if (Option.isNone(listed)) return null;
122 installations.push(...listed.value.installations);
123 if (listed.value.installations.length < PAGE_SIZE) break;
124 }
125 const accounts = new Set<string>();
126 const repositories = new Set<string>();
127 for (const installation of installations) {
128 const login = installation.account?.login.toLowerCase();
129 if (login === undefined) continue;
130 if (installation.repository_selection === "all") {
131 accounts.add(login);
132 continue;
133 }
134 for (let page = 1; ; page++) {
135 // Past the cap the list is cut short; count the whole account as reached rather than nag.
136 if (page > MAX_PAGES) {
137 accounts.add(login);
138 break;
139 }
140 const listed = yield* readAsApp(
141 host,
142 "appInstallationRepositories",
143 `user/installations/${installation.id}/repositories?per_page=${PAGE_SIZE}&page=${page}`,
144 InstallationRepositories,
145 );
146 if (Option.isNone(listed)) return null;
147 for (const repository of listed.value.repositories) {
148 repositories.add(repository.full_name.toLowerCase());
149 }
150 if (listed.value.repositories.length < PAGE_SIZE) break;
151 }
152 }
153 return { accounts, repositories } satisfies AppCoverage;
154 });
155
156 const coverage = yield* Cache.makeWith(coverageOf, {
157 capacity: 8,
158 timeToLive: (exit) => (Exit.isSuccess(exit) ? COVERAGE_TTL : COVERAGE_FAILURE_TTL),
159 });
160
161 /** `unknown` when GitHub could not list the installations just now. */
162 const coverageFor = Effect.fn("GitHubAppAccess.coverageFor")(function* (
163 rawHost: string,
164 rawRepository: string,
165 ) {
166 const host = rawHost.trim().toLowerCase();
167 if (!appSignIn.enabled) return "signed-out" as const;
168 const known = yield* Cache.get(coverage, host).pipe(Effect.option);
169 if (Option.isNone(known)) return "unknown" as const;
170 if (known.value === null) return "signed-out" as const;
171 const repository = ownerAndName(rawRepository);
172 const owner = repository.split("/")[0] ?? "";
173 return known.value.accounts.has(owner) || known.value.repositories.has(repository)
174 ? ("covered" as const)
175 : ("not-covered" as const);
176 });
177
178 const reach: GitHubAppAccess["Service"]["reach"] = (host, repository) =>
179 coverageFor(host, repository).pipe(
180 Effect.map((answer) => (answer === "unknown" ? "covered" : answer)),
181 );
182
183 const viewer: GitHubAppAccess["Service"]["viewer"] = Effect.fn("GitHubAppAccess.viewer")(
184 function* (rawHost) {
185 const host = rawHost.trim().toLowerCase();
186 // A new sign-in can reach different installations than the cached answer.
187 yield* Cache.invalidate(coverage, host);
188 const login = yield* readAsApp(host, "appViewer", "user", Viewer).pipe(
189 Effect.catchTags({
190 SchemaError: () => Effect.succeed(Option.none<{ readonly login: string }>()),
191 }),
192 );
193 if (Option.isNone(login)) {
194 return yield* new GitHubRequestPolicy.GitHubApiAuthenticationError({
195 host,
196 operation: "appViewer",
197 });
198 }
199 return login.value.login;
200 },
201 );
202
203 const credentialFor: GitHubAppAccess["Service"]["credentialFor"] = Effect.fn(
204 "GitHubAppAccess.credentialFor",
205 )(function* (host, repository) {
206 // Pinned work cannot be handed on, so only confirmed app access keeps the app credential.
207 if ((yield* coverageFor(host, repository)) === "covered") return yield* api.credential(host);
208 return yield* api
209 .credential(host, { personal: true })
210 .pipe(Effect.catch(() => api.credential(host)));
211 });
212
213 return GitHubAppAccess.of({ reach, viewer, credentialFor });
214});
215
216export const layer = Layer.effect(GitHubAppAccess, make);