@bevel-software/platform-core-backend 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/create-core-server.d.ts.map +1 -1
- package/dist/core/create-core-server.js +32 -2
- package/dist/core/create-core-server.js.map +1 -1
- package/dist/core/create-core-services.d.ts +13 -1
- package/dist/core/create-core-services.d.ts.map +1 -1
- package/dist/core/create-core-services.js +51 -5
- package/dist/core/create-core-services.js.map +1 -1
- package/dist/modules/access/access-requests.contract.d.ts +75 -0
- package/dist/modules/access/access-requests.contract.d.ts.map +1 -0
- package/dist/modules/access/access-requests.contract.js +20 -0
- package/dist/modules/access/access-requests.contract.js.map +1 -0
- package/dist/modules/access/access-requests.routes.d.ts +35 -0
- package/dist/modules/access/access-requests.routes.d.ts.map +1 -0
- package/dist/modules/access/access-requests.routes.js +237 -0
- package/dist/modules/access/access-requests.routes.js.map +1 -0
- package/dist/modules/access/access-requests.service.d.ts +123 -0
- package/dist/modules/access/access-requests.service.d.ts.map +1 -0
- package/dist/modules/access/access-requests.service.js +337 -0
- package/dist/modules/access/access-requests.service.js.map +1 -0
- package/dist/modules/access-model/access-grammar.d.ts +12 -0
- package/dist/modules/access-model/access-grammar.d.ts.map +1 -1
- package/dist/modules/access-model/access-grammar.js +24 -0
- package/dist/modules/access-model/access-grammar.js.map +1 -1
- package/dist/modules/auth/auth.service.d.ts +26 -1
- package/dist/modules/auth/auth.service.d.ts.map +1 -1
- package/dist/modules/auth/auth.service.js +11 -2
- package/dist/modules/auth/auth.service.js.map +1 -1
- package/dist/modules/github-app/github-app.client.d.ts +101 -0
- package/dist/modules/github-app/github-app.client.d.ts.map +1 -0
- package/dist/modules/github-app/github-app.client.js +222 -0
- package/dist/modules/github-app/github-app.client.js.map +1 -0
- package/dist/modules/github-app/github-app.connection.d.ts +102 -0
- package/dist/modules/github-app/github-app.connection.d.ts.map +1 -0
- package/dist/modules/github-app/github-app.connection.js +185 -0
- package/dist/modules/github-app/github-app.connection.js.map +1 -0
- package/dist/modules/github-app/github-app.routes.d.ts +59 -0
- package/dist/modules/github-app/github-app.routes.d.ts.map +1 -0
- package/dist/modules/github-app/github-app.routes.js +323 -0
- package/dist/modules/github-app/github-app.routes.js.map +1 -0
- package/dist/modules/github-app/index.d.ts +4 -0
- package/dist/modules/github-app/index.d.ts.map +1 -0
- package/dist/modules/github-app/index.js +4 -0
- package/dist/modules/github-app/index.js.map +1 -0
- package/dist/modules/kb-fs/remote-url.d.ts +22 -0
- package/dist/modules/kb-fs/remote-url.d.ts.map +1 -0
- package/dist/modules/kb-fs/remote-url.js +35 -0
- package/dist/modules/kb-fs/remote-url.js.map +1 -0
- package/dist/modules/plugins/join-proposals.d.ts +17 -5
- package/dist/modules/plugins/join-proposals.d.ts.map +1 -1
- package/dist/modules/plugins/join-proposals.js +76 -22
- package/dist/modules/plugins/join-proposals.js.map +1 -1
- package/dist/modules/plugins/join-requests.service.d.ts +111 -18
- package/dist/modules/plugins/join-requests.service.d.ts.map +1 -1
- package/dist/modules/plugins/join-requests.service.js +173 -29
- package/dist/modules/plugins/join-requests.service.js.map +1 -1
- package/dist/modules/plugins/plugins.routes.d.ts.map +1 -1
- package/dist/modules/plugins/plugins.routes.js +3 -2
- package/dist/modules/plugins/plugins.routes.js.map +1 -1
- package/dist/modules/settings/deployment-settings.service.d.ts +22 -1
- package/dist/modules/settings/deployment-settings.service.d.ts.map +1 -1
- package/dist/modules/settings/deployment-settings.service.js +93 -4
- package/dist/modules/settings/deployment-settings.service.js.map +1 -1
- package/dist/modules/settings/managed-repository.d.ts +43 -0
- package/dist/modules/settings/managed-repository.d.ts.map +1 -0
- package/dist/modules/settings/managed-repository.js +60 -0
- package/dist/modules/settings/managed-repository.js.map +1 -0
- package/dist/modules/settings/repository-source.d.ts +128 -0
- package/dist/modules/settings/repository-source.d.ts.map +1 -0
- package/dist/modules/settings/repository-source.js +150 -0
- package/dist/modules/settings/repository-source.js.map +1 -0
- package/dist/modules/settings/setup.routes.d.ts +27 -4
- package/dist/modules/settings/setup.routes.d.ts.map +1 -1
- package/dist/modules/settings/setup.routes.js +187 -13
- package/dist/modules/settings/setup.routes.js.map +1 -1
- package/dist/modules/skills/skill-access-requests.routes.d.ts +6 -8
- package/dist/modules/skills/skill-access-requests.routes.d.ts.map +1 -1
- package/dist/modules/skills/skill-access-requests.routes.js +24 -63
- package/dist/modules/skills/skill-access-requests.routes.js.map +1 -1
- package/dist/modules/tool-helpers/tool-context.d.ts.map +1 -1
- package/dist/modules/tool-helpers/tool-context.js +15 -0
- package/dist/modules/tool-helpers/tool-context.js.map +1 -1
- package/dist/modules/workflow/agent-tools/workflow.tools.d.ts.map +1 -1
- package/dist/modules/workflow/agent-tools/workflow.tools.js +38 -2
- package/dist/modules/workflow/agent-tools/workflow.tools.js.map +1 -1
- package/dist/modules/workflow/git/git.service.d.ts +3 -1
- package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
- package/dist/modules/workflow/git/git.service.js +17 -4
- package/dist/modules/workflow/git/git.service.js.map +1 -1
- package/dist/modules/workflow/git/node-git-runner.d.ts.map +1 -1
- package/dist/modules/workflow/git/node-git-runner.js +5 -0
- package/dist/modules/workflow/git/node-git-runner.js.map +1 -1
- package/dist/modules/workflow/git/pull-request.service.d.ts +45 -0
- package/dist/modules/workflow/git/pull-request.service.d.ts.map +1 -1
- package/dist/modules/workflow/git/pull-request.service.js +99 -0
- package/dist/modules/workflow/git/pull-request.service.js.map +1 -1
- package/dist/modules/workflow/workflow.routes.d.ts.map +1 -1
- package/dist/modules/workflow/workflow.routes.js +3 -1
- package/dist/modules/workflow/workflow.routes.js.map +1 -1
- package/dist/modules/workflow/workflow.service.d.ts +34 -7
- package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
- package/dist/modules/workflow/workflow.service.js +148 -48
- package/dist/modules/workflow/workflow.service.js.map +1 -1
- package/dist/modules/workspace/startup/kb-startup-runner.d.ts +66 -0
- package/dist/modules/workspace/startup/kb-startup-runner.d.ts.map +1 -1
- package/dist/modules/workspace/startup/kb-startup-runner.js +148 -0
- package/dist/modules/workspace/startup/kb-startup-runner.js.map +1 -1
- package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
- package/dist/modules/workspace/workspace.service.js +17 -1
- package/dist/modules/workspace/workspace.service.js.map +1 -1
- package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
- package/dist/modules/workspace/workspace.tools.js +28 -2
- package/dist/modules/workspace/workspace.tools.js.map +1 -1
- package/dist/shared/domain-errors.d.ts +39 -0
- package/dist/shared/domain-errors.d.ts.map +1 -1
- package/dist/shared/domain-errors.js +55 -0
- package/dist/shared/domain-errors.js.map +1 -1
- package/dist/shared/git.contract.d.ts +10 -0
- package/dist/shared/git.contract.d.ts.map +1 -1
- package/dist/shared/git.contract.js.map +1 -1
- package/package.json +3 -3
- package/src/core/create-core-server.ts +37 -1
- package/src/core/create-core-services.ts +65 -8
- package/src/modules/access/__tests__/access-requests.recut.test.ts +134 -0
- package/src/modules/access/__tests__/access-requests.routes.test.ts +610 -0
- package/src/modules/access/access-requests.contract.ts +93 -0
- package/src/modules/access/access-requests.routes.ts +286 -0
- package/src/modules/access/access-requests.service.ts +420 -0
- package/src/modules/access-model/access-grammar.ts +22 -0
- package/src/modules/auth/__tests__/auth.service.test.ts +38 -0
- package/src/modules/auth/auth.service.ts +28 -1
- package/src/modules/github-app/__tests__/github-app.test.ts +848 -0
- package/src/modules/github-app/github-app.client.ts +268 -0
- package/src/modules/github-app/github-app.connection.ts +204 -0
- package/src/modules/github-app/github-app.routes.ts +359 -0
- package/src/modules/github-app/index.ts +19 -0
- package/src/modules/kb-fs/__tests__/remote-url.test.ts +38 -0
- package/src/modules/kb-fs/remote-url.ts +35 -0
- package/src/modules/plugins/__tests__/join-proposals.test.ts +100 -19
- package/src/modules/plugins/__tests__/join-requests.service.test.ts +27 -11
- package/src/modules/plugins/__tests__/join-requests.settlement.test.ts +371 -0
- package/src/modules/plugins/__tests__/plugins.routes.test.ts +1 -1
- package/src/modules/plugins/join-proposals.ts +87 -19
- package/src/modules/plugins/join-requests.service.ts +199 -39
- package/src/modules/plugins/plugins.routes.ts +3 -2
- package/src/modules/settings/__tests__/repository-source.test.ts +191 -0
- package/src/modules/settings/__tests__/setup.routes.git-mode.test.ts +353 -0
- package/src/modules/settings/__tests__/setup.routes.github-app.test.ts +282 -0
- package/src/modules/settings/__tests__/setup.routes.managed-phase.test.ts +233 -0
- package/src/modules/settings/deployment-settings.service.ts +109 -3
- package/src/modules/settings/managed-repository.ts +68 -0
- package/src/modules/settings/repository-source.ts +197 -0
- package/src/modules/settings/setup.routes.ts +214 -10
- package/src/modules/skills/__tests__/skill-access-requests.routes.test.ts +5 -1
- package/src/modules/skills/skill-access-requests.routes.ts +25 -75
- package/src/modules/tool-helpers/tool-context.ts +15 -0
- package/src/modules/workflow/__tests__/apply-failure.test.ts +9 -1
- package/src/modules/workflow/__tests__/workflow.service.facade.test.ts +159 -8
- package/src/modules/workflow/__tests__/workflow.service.update-from-target.test.ts +146 -40
- package/src/modules/workflow/agent-tools/__tests__/workflow.tools.test.ts +141 -1
- package/src/modules/workflow/agent-tools/workflow.tools.ts +49 -3
- package/src/modules/workflow/git/__tests__/git.service.pull.test.ts +121 -0
- package/src/modules/workflow/git/__tests__/pull-request.service.getPrDetail.test.ts +145 -2
- package/src/modules/workflow/git/__tests__/pull-request.service.viewer-can-delete.test.ts +166 -0
- package/src/modules/workflow/git/git.service.ts +25 -4
- package/src/modules/workflow/git/node-git-runner.ts +6 -0
- package/src/modules/workflow/git/pull-request.service.ts +119 -0
- package/src/modules/workflow/workflow.routes.ts +3 -1
- package/src/modules/workflow/workflow.service.ts +170 -52
- package/src/modules/workspace/__tests__/workspace.service.unknown-branch.test.ts +43 -0
- package/src/modules/workspace/__tests__/workspace.tools.branch-errors.test.ts +233 -7
- package/src/modules/workspace/__tests__/workspace.tools.test.ts +35 -3
- package/src/modules/workspace/startup/__tests__/kb-startup-runner.test.ts +211 -0
- package/src/modules/workspace/startup/kb-startup-runner.ts +159 -0
- package/src/modules/workspace/workspace.service.ts +17 -1
- package/src/modules/workspace/workspace.tools.ts +35 -0
- package/src/shared/domain-errors.ts +58 -0
- package/src/shared/git.contract.ts +10 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { createSign } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
/** A GitHub App's identity and keys, as GitHub issued them. */
|
|
4
|
+
export interface GitHubAppCredentials {
|
|
5
|
+
appId: string;
|
|
6
|
+
slug: string;
|
|
7
|
+
/** PEM. */
|
|
8
|
+
privateKey: string;
|
|
9
|
+
clientId: string;
|
|
10
|
+
clientSecret: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** What GitHub hands back when an app is created from a manifest. */
|
|
14
|
+
export interface RegisteredApp extends GitHubAppCredentials {
|
|
15
|
+
/** The account that owns the app. */
|
|
16
|
+
owner: string;
|
|
17
|
+
htmlUrl: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface Installation {
|
|
21
|
+
id: string;
|
|
22
|
+
/** The user or organisation it is installed on. */
|
|
23
|
+
account: string;
|
|
24
|
+
/** `all`, or `selected` when the admin chose repositories. */
|
|
25
|
+
repositorySelection: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface InstallationToken {
|
|
29
|
+
token: string;
|
|
30
|
+
/** Epoch milliseconds. */
|
|
31
|
+
expiresAt: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface InstallationRepository {
|
|
35
|
+
/** `owner/name`. */
|
|
36
|
+
fullName: string;
|
|
37
|
+
private: boolean;
|
|
38
|
+
defaultBranch: string;
|
|
39
|
+
/** Whether the installation may push to it. */
|
|
40
|
+
writable: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type GitHubFailureKind = 'unreachable' | 'refused' | 'not-found' | 'unexpected';
|
|
44
|
+
|
|
45
|
+
/** A call to GitHub that did not give what was asked. The message never carries a credential. */
|
|
46
|
+
export class GitHubAppError extends Error {
|
|
47
|
+
constructor(
|
|
48
|
+
readonly kind: GitHubFailureKind,
|
|
49
|
+
message: string,
|
|
50
|
+
readonly status = 0,
|
|
51
|
+
) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = 'GitHubAppError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const API = 'https://api.github.com';
|
|
58
|
+
const WEB = 'https://github.com';
|
|
59
|
+
const API_VERSION = '2022-11-28';
|
|
60
|
+
/** Generous for an API that answers in a fraction of a second, short for something git is waiting on. */
|
|
61
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
62
|
+
/** Repositories listed per installation before the list is said to be cut short. */
|
|
63
|
+
const MAX_REPOSITORIES = 500;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A private key as an operator is likely to have supplied it: the PEM
|
|
67
|
+
* itself, the PEM with its line breaks written as `\n` (the only way most
|
|
68
|
+
* environment files can hold it), or the PEM in base64.
|
|
69
|
+
*/
|
|
70
|
+
export function normalizePrivateKey(raw: string): string {
|
|
71
|
+
const value = raw.trim();
|
|
72
|
+
if (value.includes('-----BEGIN')) return value.replace(/\\n/g, '\n');
|
|
73
|
+
try {
|
|
74
|
+
const decoded = Buffer.from(value, 'base64').toString('utf8');
|
|
75
|
+
if (decoded.includes('-----BEGIN')) return decoded.trim();
|
|
76
|
+
} catch {
|
|
77
|
+
// Not base64: handed on as it is, and the signing says what is wrong with it.
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The JWT an app presents to GitHub as itself: RS256 over its id, good for
|
|
84
|
+
* a few minutes. Issued a minute in the past, as GitHub advises, so a clock
|
|
85
|
+
* that runs slightly ahead of theirs is not refused.
|
|
86
|
+
*/
|
|
87
|
+
export function appJwt(credentials: Pick<GitHubAppCredentials, 'appId' | 'privateKey'>, now: number = Date.now()): string {
|
|
88
|
+
const seconds = Math.floor(now / 1000);
|
|
89
|
+
const part = (value: unknown) => Buffer.from(JSON.stringify(value), 'utf8').toString('base64url');
|
|
90
|
+
const body = `${part({ alg: 'RS256', typ: 'JWT' })}.${part({ iat: seconds - 60, exp: seconds + 9 * 60, iss: credentials.appId })}`;
|
|
91
|
+
let signature: string;
|
|
92
|
+
try {
|
|
93
|
+
signature = createSign('RSA-SHA256').update(body).end().sign(normalizePrivateKey(credentials.privateKey), 'base64url');
|
|
94
|
+
} catch {
|
|
95
|
+
// What the key was is never quoted.
|
|
96
|
+
throw new GitHubAppError('refused', 'The GitHub App private key could not be read. It must be the PEM GitHub issued.');
|
|
97
|
+
}
|
|
98
|
+
return `${body}.${signature}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* What the deployment asks of GitHub, as a GitHub App: every call it makes,
|
|
103
|
+
* and nothing that decides anything. Injected with `fetch` so suites answer
|
|
104
|
+
* for GitHub.
|
|
105
|
+
*/
|
|
106
|
+
export class GitHubAppClient {
|
|
107
|
+
constructor(
|
|
108
|
+
private readonly fetchImpl: typeof fetch = fetch,
|
|
109
|
+
private readonly now: () => number = Date.now,
|
|
110
|
+
/** How long one request to GitHub may take. */
|
|
111
|
+
private readonly timeoutMs: number = REQUEST_TIMEOUT_MS,
|
|
112
|
+
) {}
|
|
113
|
+
|
|
114
|
+
/** The app GitHub created from a manifest, for the code it sent the browser back with. Good once, for an hour. */
|
|
115
|
+
async convertManifest(code: string): Promise<RegisteredApp> {
|
|
116
|
+
const body = await this.call<Record<string, unknown>>(`${API}/app-manifests/${encodeURIComponent(code)}/conversions`, {
|
|
117
|
+
method: 'POST',
|
|
118
|
+
});
|
|
119
|
+
const owner = (body.owner as { login?: unknown } | undefined)?.login;
|
|
120
|
+
const app: RegisteredApp = {
|
|
121
|
+
appId: String(body.id ?? ''),
|
|
122
|
+
slug: String(body.slug ?? ''),
|
|
123
|
+
privateKey: String(body.pem ?? ''),
|
|
124
|
+
clientId: String(body.client_id ?? ''),
|
|
125
|
+
clientSecret: String(body.client_secret ?? ''),
|
|
126
|
+
owner: typeof owner === 'string' ? owner : '',
|
|
127
|
+
htmlUrl: String(body.html_url ?? ''),
|
|
128
|
+
};
|
|
129
|
+
if (!app.appId || !app.slug || !app.privateKey || !app.clientId || !app.clientSecret) {
|
|
130
|
+
throw new GitHubAppError('unexpected', 'GitHub created the app but did not return its keys.');
|
|
131
|
+
}
|
|
132
|
+
return app;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A token for the PERSON who has just come back from GitHub, in exchange
|
|
137
|
+
* for the code they came back with. Used for one question (see
|
|
138
|
+
* {@link installationsOf}) and then dropped.
|
|
139
|
+
*/
|
|
140
|
+
async exchangeUserCode(credentials: Pick<GitHubAppCredentials, 'clientId' | 'clientSecret'>, code: string): Promise<string> {
|
|
141
|
+
const body = await this.call<Record<string, unknown>>(`${WEB}/login/oauth/access_token`, {
|
|
142
|
+
method: 'POST',
|
|
143
|
+
headers: { 'Content-Type': 'application/json' },
|
|
144
|
+
body: JSON.stringify({ client_id: credentials.clientId, client_secret: credentials.clientSecret, code }),
|
|
145
|
+
});
|
|
146
|
+
// GitHub answers a refused exchange with 200 and an `error` field.
|
|
147
|
+
if (typeof body.access_token !== 'string' || !body.access_token) {
|
|
148
|
+
throw new GitHubAppError('refused', 'GitHub did not accept the sign-in that came back with the installation.');
|
|
149
|
+
}
|
|
150
|
+
return body.access_token;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The installations of this app that the person holding `userToken` can reach. */
|
|
154
|
+
async installationsOf(userToken: string): Promise<Installation[]> {
|
|
155
|
+
const found: Installation[] = [];
|
|
156
|
+
for (let page = 1; page <= 10; page += 1) {
|
|
157
|
+
const body = await this.call<{ installations?: unknown[] }>(`${API}/user/installations?per_page=100&page=${page}`, {
|
|
158
|
+
headers: { Authorization: `Bearer ${userToken}` },
|
|
159
|
+
});
|
|
160
|
+
const batch = Array.isArray(body.installations) ? body.installations : [];
|
|
161
|
+
for (const item of batch) found.push(installationOf(item));
|
|
162
|
+
if (batch.length < 100) break;
|
|
163
|
+
}
|
|
164
|
+
return found;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** One installation, asked for as the app. */
|
|
168
|
+
async installation(credentials: GitHubAppCredentials, id: string): Promise<Installation> {
|
|
169
|
+
const body = await this.call<unknown>(`${API}/app/installations/${encodeURIComponent(id)}`, {
|
|
170
|
+
headers: { Authorization: `Bearer ${appJwt(credentials, this.now())}` },
|
|
171
|
+
});
|
|
172
|
+
return installationOf(body);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A token for the installation: what git presents. Good for an hour. */
|
|
176
|
+
async installationToken(credentials: GitHubAppCredentials, id: string): Promise<InstallationToken> {
|
|
177
|
+
const body = await this.call<Record<string, unknown>>(`${API}/app/installations/${encodeURIComponent(id)}/access_tokens`, {
|
|
178
|
+
method: 'POST',
|
|
179
|
+
headers: { Authorization: `Bearer ${appJwt(credentials, this.now())}` },
|
|
180
|
+
});
|
|
181
|
+
const expiresAt = Date.parse(String(body.expires_at ?? ''));
|
|
182
|
+
if (typeof body.token !== 'string' || !body.token || Number.isNaN(expiresAt)) {
|
|
183
|
+
throw new GitHubAppError('unexpected', 'GitHub did not return a token for the installation.');
|
|
184
|
+
}
|
|
185
|
+
return { token: body.token, expiresAt };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The repositories the installation reaches, and whether the list was cut short. */
|
|
189
|
+
repositories(installationToken: string): Promise<{ repositories: InstallationRepository[]; more: boolean }> {
|
|
190
|
+
return this.listRepositories(`${API}/installation/repositories`, installationToken);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The repositories of an installation that THE PERSON holding `userToken`
|
|
195
|
+
* reaches, each with that person's own permissions: `writable` is whether
|
|
196
|
+
* they may push to it, which is another question from whether the
|
|
197
|
+
* installation may. An installation the person does not reach at all is
|
|
198
|
+
* GitHub's to refuse.
|
|
199
|
+
*/
|
|
200
|
+
repositoriesOf(userToken: string, installationId: string): Promise<{ repositories: InstallationRepository[]; more: boolean }> {
|
|
201
|
+
return this.listRepositories(`${API}/user/installations/${encodeURIComponent(installationId)}/repositories`, userToken);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private async listRepositories(url: string, token: string): Promise<{ repositories: InstallationRepository[]; more: boolean }> {
|
|
205
|
+
const repositories: InstallationRepository[] = [];
|
|
206
|
+
let total = 0;
|
|
207
|
+
for (let page = 1; repositories.length < MAX_REPOSITORIES; page += 1) {
|
|
208
|
+
const body = await this.call<{ total_count?: unknown; repositories?: unknown[] }>(
|
|
209
|
+
`${url}?per_page=100&page=${page}`,
|
|
210
|
+
{ headers: { Authorization: `Bearer ${token}` } },
|
|
211
|
+
);
|
|
212
|
+
total = typeof body.total_count === 'number' ? body.total_count : total;
|
|
213
|
+
const batch = Array.isArray(body.repositories) ? body.repositories : [];
|
|
214
|
+
for (const item of batch) {
|
|
215
|
+
const repo = item as Record<string, unknown>;
|
|
216
|
+
if (typeof repo.full_name !== 'string') continue;
|
|
217
|
+
repositories.push({
|
|
218
|
+
fullName: repo.full_name,
|
|
219
|
+
private: repo.private === true,
|
|
220
|
+
defaultBranch: typeof repo.default_branch === 'string' ? repo.default_branch : '',
|
|
221
|
+
writable: (repo.permissions as { push?: unknown } | undefined)?.push === true,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
if (batch.length < 100) break;
|
|
225
|
+
}
|
|
226
|
+
repositories.sort((a, b) => a.fullName.localeCompare(b.fullName));
|
|
227
|
+
return { repositories, more: total > repositories.length };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private async call<T>(url: string, init: RequestInit): Promise<T> {
|
|
231
|
+
let res: Response;
|
|
232
|
+
try {
|
|
233
|
+
res = await this.fetchImpl(url, {
|
|
234
|
+
...init,
|
|
235
|
+
// A deadline of ours: left to the platform, a host that accepts
|
|
236
|
+
// the connection and says nothing is waited on for minutes, by
|
|
237
|
+
// whatever was waiting on this call.
|
|
238
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
239
|
+
headers: {
|
|
240
|
+
Accept: 'application/vnd.github+json',
|
|
241
|
+
'X-GitHub-Api-Version': API_VERSION,
|
|
242
|
+
'User-Agent': 'hexis',
|
|
243
|
+
...(init.headers as Record<string, string> | undefined),
|
|
244
|
+
},
|
|
245
|
+
});
|
|
246
|
+
} catch (err) {
|
|
247
|
+
throw new GitHubAppError('unreachable', `GitHub could not be reached: ${err instanceof Error ? err.message : String(err)}`);
|
|
248
|
+
}
|
|
249
|
+
if (!res.ok) {
|
|
250
|
+
// GitHub's own words name the cause (a permission, a suspended app) and carry no credential of ours.
|
|
251
|
+
const said = ((await res.json().catch(() => ({}))) as { message?: unknown }).message;
|
|
252
|
+
const detail = typeof said === 'string' && said ? `: ${said.slice(0, 200)}` : '';
|
|
253
|
+
const kind: GitHubFailureKind = res.status === 404 ? 'not-found' : res.status === 401 || res.status === 403 ? 'refused' : 'unexpected';
|
|
254
|
+
throw new GitHubAppError(kind, `GitHub answered ${res.status}${detail}`, res.status);
|
|
255
|
+
}
|
|
256
|
+
return (await res.json().catch(() => ({}))) as T;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function installationOf(raw: unknown): Installation {
|
|
261
|
+
const item = (raw ?? {}) as Record<string, unknown>;
|
|
262
|
+
const account = (item.account as { login?: unknown } | undefined)?.login;
|
|
263
|
+
return {
|
|
264
|
+
id: String(item.id ?? ''),
|
|
265
|
+
account: typeof account === 'string' ? account : '',
|
|
266
|
+
repositorySelection: typeof item.repository_selection === 'string' ? item.repository_selection : '',
|
|
267
|
+
};
|
|
268
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { logger } from '../../shared/logging.js';
|
|
2
|
+
import type { GitHubAppRepository, SettingReader } from '../settings/repository-source.js';
|
|
3
|
+
import {
|
|
4
|
+
GitHubAppClient,
|
|
5
|
+
type GitHubAppCredentials,
|
|
6
|
+
type InstallationRepository,
|
|
7
|
+
} from './github-app.client.js';
|
|
8
|
+
|
|
9
|
+
/** Renewed this long before it would expire, so no git call starts on a token with minutes to live. */
|
|
10
|
+
const RENEW_AHEAD_MS = 10 * 60_000;
|
|
11
|
+
/** How long a failed renewal is remembered the first time, and the most it grows to. */
|
|
12
|
+
const FIRST_WAIT_MS = 5_000;
|
|
13
|
+
const LONGEST_WAIT_MS = 5 * 60_000;
|
|
14
|
+
|
|
15
|
+
/** The repositories a person may connect, as a setting holds them: one `owner/name` a line. */
|
|
16
|
+
export function repositoriesAsSetting(names: string[]): string {
|
|
17
|
+
return [...new Set(names.map((name) => name.trim()).filter(Boolean))].join('\n');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface GitHubAppConnectionOptions {
|
|
21
|
+
/** The deployment's settings, as they are in effect. */
|
|
22
|
+
read: SettingReader;
|
|
23
|
+
/** Where a setting's value comes from: what tells an app the operator supplied from one setup registered. */
|
|
24
|
+
sourceOf(key: string): 'env' | 'stored' | 'unset';
|
|
25
|
+
client?: GitHubAppClient;
|
|
26
|
+
now?: () => number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The deployment's connection to GitHub through a GitHub App: the app it
|
|
31
|
+
* acts as, the installation it was given, the repositories it may be
|
|
32
|
+
* pointed at, and the token that stands for the first two when git runs.
|
|
33
|
+
*
|
|
34
|
+
* THE TOKEN EXPIRES. An installation token is good for an hour, which is
|
|
35
|
+
* the point of it: nothing long-lived is stored that reaches the
|
|
36
|
+
* repository. It is kept in memory, renewed before it runs out, and never
|
|
37
|
+
* written anywhere. A deployment that restarts asks for a new one.
|
|
38
|
+
*
|
|
39
|
+
* What is stored is what cannot be asked for again: the app's private key,
|
|
40
|
+
* encrypted like every secret, the number of the installation, and the
|
|
41
|
+
* repositories the person who connected it could push to.
|
|
42
|
+
*
|
|
43
|
+
* WHAT THE INSTALLATION REACHES IS NOT WHAT THE DEPLOYMENT MAY USE. An
|
|
44
|
+
* installation's token reads and writes every repository the installation
|
|
45
|
+
* covers. The person who connected it may hold far less: being able to
|
|
46
|
+
* read ONE of those repositories is enough for GitHub to count the
|
|
47
|
+
* installation among theirs. So the deployment is limited to what that
|
|
48
|
+
* person could push to with their own account, recorded when they
|
|
49
|
+
* connected (see {@link permits}); the installation's reach is what git
|
|
50
|
+
* works through, never what is offered.
|
|
51
|
+
*/
|
|
52
|
+
export class GitHubAppConnection implements GitHubAppRepository {
|
|
53
|
+
private readonly client: GitHubAppClient;
|
|
54
|
+
private readonly now: () => number;
|
|
55
|
+
private readonly log = () => logger('github-app');
|
|
56
|
+
/** The token in hand and what it is a token FOR: another app or installation is another token. */
|
|
57
|
+
private held: { for: string; token: string; expiresAt: number } | null = null;
|
|
58
|
+
/** One renewal at a time, shared by every git call that arrives during it. */
|
|
59
|
+
private renewing: Promise<void> | null = null;
|
|
60
|
+
/** The last renewal failed: how many in a row have, and until when GitHub is not asked again. */
|
|
61
|
+
private failed: { times: number; until: number } | null = null;
|
|
62
|
+
|
|
63
|
+
constructor(private readonly opts: GitHubAppConnectionOptions) {
|
|
64
|
+
this.client = opts.client ?? new GitHubAppClient();
|
|
65
|
+
this.now = opts.now ?? Date.now;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The app the deployment acts as, or null while any part of it is missing. */
|
|
69
|
+
credentials(read: SettingReader = this.opts.read): GitHubAppCredentials | null {
|
|
70
|
+
const credentials = {
|
|
71
|
+
appId: read('githubAppId'),
|
|
72
|
+
slug: read('githubAppSlug'),
|
|
73
|
+
privateKey: read('githubAppPrivateKey'),
|
|
74
|
+
clientId: read('githubAppClientId'),
|
|
75
|
+
clientSecret: read('githubAppClientSecret'),
|
|
76
|
+
};
|
|
77
|
+
return Object.values(credentials).every(Boolean) ? credentials : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Who supplied the app: whoever operates the deployment, or the setup screen. Null: there is none. */
|
|
81
|
+
registeredBy(): 'environment' | 'setup' | null {
|
|
82
|
+
if (!this.credentials()) return null;
|
|
83
|
+
return this.opts.sourceOf('githubAppId') === 'env' ? 'environment' : 'setup';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
installationId(read: SettingReader = this.opts.read): string {
|
|
87
|
+
return read('githubInstallationId');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
url(read: SettingReader = this.opts.read): string {
|
|
91
|
+
const repository = read('githubRepository');
|
|
92
|
+
return repository ? `https://github.com/${repository}.git` : '';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
answered(read: SettingReader = this.opts.read): boolean {
|
|
96
|
+
return Boolean(this.credentials(read) && this.installationId(read) && read('githubRepository'));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Whether the deployment may be pointed at `repository`: it is one the
|
|
101
|
+
* person who connected the installation could push to.
|
|
102
|
+
*
|
|
103
|
+
* An installation the OPERATOR supplied, through the environment, has no
|
|
104
|
+
* such person. It is the operator's statement about their own
|
|
105
|
+
* deployment, and everything it reaches is permitted, as everything an
|
|
106
|
+
* access token reaches is.
|
|
107
|
+
*/
|
|
108
|
+
permits(repository: string, read: SettingReader = this.opts.read): boolean {
|
|
109
|
+
if (this.opts.sourceOf('githubInstallationId') === 'env') return true;
|
|
110
|
+
const wanted = repository.trim().toLowerCase();
|
|
111
|
+
if (!wanted) return false;
|
|
112
|
+
// GitHub's names do not tell case apart.
|
|
113
|
+
return read('githubRepositoriesPermitted')
|
|
114
|
+
.split('\n')
|
|
115
|
+
.some((name) => name.trim().toLowerCase() === wanted);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
token(): string | null {
|
|
119
|
+
const held = this.held;
|
|
120
|
+
if (!held || held.for !== this.holder() || held.expiresAt <= this.now()) return null;
|
|
121
|
+
return held.token;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Have a token for the call about to be made, WITHOUT MAKING THE CALL
|
|
126
|
+
* WAIT ON GITHUB UNLESS IT HAS TO. This runs before every git call the
|
|
127
|
+
* deployment makes, the ones that never leave the disk included.
|
|
128
|
+
*
|
|
129
|
+
* - A token with time to spare: nothing is asked.
|
|
130
|
+
* - A token that is good but close to running out: a renewal is started
|
|
131
|
+
* and the call goes ahead with the token in hand.
|
|
132
|
+
* - No token that is good: the call waits for one, and gets what GitHub
|
|
133
|
+
* says, unless GitHub has just failed to give one. A failure is
|
|
134
|
+
* remembered for a short while that grows with each one in a row, and
|
|
135
|
+
* inside it nothing is asked: git runs with no token, and a call that
|
|
136
|
+
* needed one is told so by the host, at once.
|
|
137
|
+
*
|
|
138
|
+
* `asked` is for an admin waiting on the answer itself (the setup screen
|
|
139
|
+
* listing repositories, proving a connection): GitHub is asked whatever
|
|
140
|
+
* is remembered, and the failure is thrown.
|
|
141
|
+
*/
|
|
142
|
+
async prepare(opts: { asked?: boolean } = {}): Promise<void> {
|
|
143
|
+
const credentials = this.credentials();
|
|
144
|
+
const installationId = this.installationId();
|
|
145
|
+
if (!credentials || !installationId) return;
|
|
146
|
+
const held = this.held?.for === this.holder() ? this.held : null;
|
|
147
|
+
const good = held !== null && held.expiresAt > this.now();
|
|
148
|
+
if (good && held.expiresAt - this.now() > RENEW_AHEAD_MS) return;
|
|
149
|
+
if (!opts.asked && this.failed && this.now() < this.failed.until) return;
|
|
150
|
+
|
|
151
|
+
this.renewing ??= this.renew(credentials, installationId).finally(() => {
|
|
152
|
+
this.renewing = null;
|
|
153
|
+
});
|
|
154
|
+
if (good && !opts.asked) {
|
|
155
|
+
// Not waited on, so not thrown to anyone: the renewal has logged it.
|
|
156
|
+
this.renewing.catch(() => undefined);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
await this.renewing;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The repositories the deployment may be pointed at: those the
|
|
164
|
+
* installation reaches AND the person who connected it could push to.
|
|
165
|
+
* Asked of GitHub each time, so a repository taken out of the
|
|
166
|
+
* installation since is not offered.
|
|
167
|
+
*/
|
|
168
|
+
async repositories(): Promise<{ repositories: InstallationRepository[]; more: boolean }> {
|
|
169
|
+
await this.prepare({ asked: true });
|
|
170
|
+
const token = this.token();
|
|
171
|
+
if (!token) return { repositories: [], more: false };
|
|
172
|
+
const reached = await this.client.repositories(token);
|
|
173
|
+
return { repositories: reached.repositories.filter((r) => this.permits(r.fullName)), more: reached.more };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Drop the token in hand: the installation it was for is no longer the deployment's. */
|
|
177
|
+
forget(): void {
|
|
178
|
+
this.held = null;
|
|
179
|
+
this.failed = null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private async renew(credentials: GitHubAppCredentials, installationId: string): Promise<void> {
|
|
183
|
+
const holder = this.holder();
|
|
184
|
+
try {
|
|
185
|
+
const issued = await this.client.installationToken(credentials, installationId);
|
|
186
|
+
this.held = { for: holder, token: issued.token, expiresAt: issued.expiresAt };
|
|
187
|
+
this.failed = null;
|
|
188
|
+
} catch (err) {
|
|
189
|
+
const times = (this.failed?.times ?? 0) + 1;
|
|
190
|
+
const wait = Math.min(FIRST_WAIT_MS * 2 ** (times - 1), LONGEST_WAIT_MS);
|
|
191
|
+
this.failed = { times, until: this.now() + wait };
|
|
192
|
+
// Once per failure, and a failure is once per wait.
|
|
193
|
+
this.log().error(`GitHub gave no token for the installation; not asked again for ${Math.round(wait / 1000)} s:`, {
|
|
194
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
195
|
+
failuresInARow: times,
|
|
196
|
+
});
|
|
197
|
+
throw err;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private holder(): string {
|
|
202
|
+
return `${this.opts.read('githubAppId')}:${this.installationId()}`;
|
|
203
|
+
}
|
|
204
|
+
}
|