@bakers-build/addon-forge-github 0.0.0-stage → 0.8.1-next.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 keytec GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @bakers-build/addon-forge-github
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ bakers.build forge backend for GitHub: a GitHub App installation token scoped to one repository. Implements @bakers-build/addon-forge's ForgeBackend contract.
4
+
5
+ Part of the bakers.build CLI. Install the meta package `@bakers-build/bakers` to get the `bakers` CLI with all addons. Source: https://github.com/bakers-build/bakers-build (bakers-cli/).
@@ -0,0 +1,3 @@
1
+ import { type ForgeBackendFactory } from '@bakers-build/addon-forge/backend';
2
+ declare const factory: ForgeBackendFactory;
3
+ export default factory;
@@ -0,0 +1,196 @@
1
+ // The GitHub forge backend: a GitHub App's installation token, minted with
2
+ // an RS256 app JWT, scoped to the one configured repository and cached until
3
+ // shortly before it expires; or, with `auth: 'gh'`, the conductor's own `gh`
4
+ // login. The repository comes from config, never from a clone's `origin`.
5
+ import { createSign } from 'node:crypto';
6
+ import { cliToken, requestJson, } from '@bakers-build/addon-forge/backend';
7
+ const API = 'https://api.github.com';
8
+ const REFRESH_MS = 60_000;
9
+ function settingsOf(raw) {
10
+ const s = (raw ?? {});
11
+ if (typeof s.repository !== 'string' ||
12
+ !/^[\w.-]+\/[\w.-]+$/.test(s.repository))
13
+ throw new Error("repository must be 'owner/repo'");
14
+ if (s.auth === 'gh')
15
+ return {
16
+ repository: s.repository,
17
+ gh: true,
18
+ appId: '',
19
+ installationId: '',
20
+ privateKey: '',
21
+ };
22
+ if (s.auth !== undefined)
23
+ throw new Error("auth must be 'gh' or left out for a GitHub App");
24
+ for (const k of ['app_id', 'installation_id'])
25
+ if (typeof s[k] !== 'number' && (typeof s[k] !== 'string' || s[k] === ''))
26
+ throw new Error(`${k} must be the App's numeric ${k.replace('_', ' ')}`);
27
+ const fromEnv = typeof s.private_key_env === 'string'
28
+ ? process.env[s.private_key_env]
29
+ : undefined;
30
+ const privateKey = typeof s.private_key === 'string' ? s.private_key : fromEnv;
31
+ if (!privateKey)
32
+ throw new Error('private_key or private_key_env (naming a set environment variable) must give the App private key');
33
+ return {
34
+ repository: s.repository,
35
+ gh: false,
36
+ appId: String(s.app_id),
37
+ installationId: String(s.installation_id),
38
+ privateKey,
39
+ };
40
+ }
41
+ const b64url = (v) => Buffer.from(v).toString('base64url');
42
+ function appJwt(appId, key) {
43
+ const now = Math.floor(Date.now() / 1000);
44
+ const head = `${b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))}.${b64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: appId }))}`;
45
+ return `${head}.${createSign('RSA-SHA256').update(head).sign(key, 'base64url')}`;
46
+ }
47
+ const prOf = (p) => ({
48
+ number: p.number,
49
+ url: p.html_url,
50
+ head: p.head.ref,
51
+ base: p.base.ref,
52
+ title: p.title,
53
+ headSha: p.head.sha,
54
+ });
55
+ function runStatus(r) {
56
+ if (r.status !== 'completed')
57
+ return 'pending';
58
+ return ['success', 'neutral', 'skipped'].includes(r.conclusion ?? '')
59
+ ? 'success'
60
+ : 'failure';
61
+ }
62
+ function stateStatus(state) {
63
+ if (state === 'success')
64
+ return 'success';
65
+ return state === 'pending' ? 'pending' : 'failure';
66
+ }
67
+ const basic = (token) => Buffer.from(`x-access-token:${token}`).toString('base64');
68
+ const factory = async (raw, context) => {
69
+ const s = settingsOf(raw);
70
+ const doFetch = context.fetch ?? fetch;
71
+ const [owner] = s.repository.split('/');
72
+ const repo = `${API}/repos/${s.repository}`;
73
+ let token;
74
+ // Every JWT and token ever minted: a value replaced by a refresh may still be echoed.
75
+ const minted = [];
76
+ const ghToken = cliToken('gh', ['auth', 'token', '--hostname', 'github.com'], minted);
77
+ const accessToken = async () => {
78
+ if (s.gh) {
79
+ const value = await ghToken();
80
+ if (!minted.includes(basic(value)))
81
+ minted.push(basic(value));
82
+ return value;
83
+ }
84
+ if (token && Date.now() < token.until)
85
+ return token.value;
86
+ const jwt = appJwt(s.appId, s.privateKey);
87
+ minted.push(jwt);
88
+ const out = (await requestJson(doFetch, `${API}/app/installations/${s.installationId}/access_tokens`, {
89
+ method: 'POST',
90
+ headers: {
91
+ authorization: `Bearer ${jwt}`,
92
+ accept: 'application/vnd.github+json',
93
+ 'content-type': 'application/json',
94
+ },
95
+ body: JSON.stringify({ repositories: [s.repository.split('/')[1]] }),
96
+ }));
97
+ minted.push(out.token, basic(out.token));
98
+ token = {
99
+ value: out.token,
100
+ until: Date.parse(out.expires_at) - REFRESH_MS,
101
+ };
102
+ return out.token;
103
+ };
104
+ const api = async (path, init = {}) => requestJson(doFetch, `${repo}${path}`, {
105
+ method: init.method ?? 'GET',
106
+ headers: {
107
+ authorization: `Bearer ${await accessToken()}`,
108
+ accept: 'application/vnd.github+json',
109
+ 'content-type': 'application/json',
110
+ },
111
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
112
+ ...(init.allow404 ? { allow404: true } : {}),
113
+ });
114
+ const pull = async (n) => (await api(`/pulls/${n}`));
115
+ const backend = {
116
+ id: 'github',
117
+ secrets: () => [...(s.privateKey ? [s.privateKey] : []), ...minted],
118
+ gitAuth: async () => ({
119
+ url: `https://github.com/${s.repository}.git`,
120
+ header: `Authorization: Basic ${basic(await accessToken())}`,
121
+ }),
122
+ findOpenPr: async (head) => {
123
+ const list = (await api(`/pulls?state=open&head=${encodeURIComponent(`${owner}:${head}`)}`));
124
+ const found = list.find((p) => p.head.ref === head);
125
+ return found && prOf(found);
126
+ },
127
+ createPr: async ({ head, base, title, body }) => prOf((await api('/pulls', {
128
+ method: 'POST',
129
+ body: { head, base, title, body },
130
+ }))),
131
+ updatePr: async (pr, { title, body }) => prOf((await api(`/pulls/${pr.number}`, {
132
+ method: 'PATCH',
133
+ body: { title, body },
134
+ }))),
135
+ openPrsWithBase: async (base) => (await api(`/pulls?state=open&base=${encodeURIComponent(base)}&per_page=100`))
136
+ .filter((p) => p.base.ref === base)
137
+ .map(prOf),
138
+ checks: async (ref, base) => {
139
+ const at = encodeURIComponent(ref);
140
+ const b = encodeURIComponent(base);
141
+ const [runs, status, rules, branch] = await Promise.all([
142
+ api(`/commits/${at}/check-runs?per_page=100`),
143
+ api(`/commits/${at}/status`),
144
+ api(`/rules/branches/${b}`, { allow404: true }),
145
+ api(`/branches/${b}`, { allow404: true }),
146
+ ]);
147
+ const required = new Set([
148
+ ...(rules ?? [])
149
+ .filter((r) => r.type === 'required_status_checks')
150
+ .flatMap((r) => r.parameters?.required_status_checks ?? [])
151
+ .map((c) => c.context),
152
+ ...(branch?.protection?.required_status_checks?.contexts ?? []),
153
+ ]);
154
+ const rows = [
155
+ ...runs.check_runs.map((r) => ({
156
+ name: r.name,
157
+ status: runStatus(r),
158
+ required: required.has(r.name),
159
+ })),
160
+ ...status.statuses.map((st) => ({
161
+ name: st.context,
162
+ status: stateStatus(st.state),
163
+ required: required.has(st.context),
164
+ })),
165
+ ];
166
+ for (const name of required)
167
+ if (!rows.some((r) => r.name === name))
168
+ rows.push({ name, status: 'missing', required: true });
169
+ return rows;
170
+ },
171
+ mergeBlocker: async (pr) => {
172
+ const p = await pull(pr.number);
173
+ if (p.mergeable === null || p.mergeable === undefined)
174
+ return 'mergeability is not computed yet; call again shortly';
175
+ return p.mergeable ? undefined : 'merge conflict with its base';
176
+ },
177
+ merge: async (pr, o) => {
178
+ await api(`/pulls/${pr.number}/merge`, {
179
+ method: 'PUT',
180
+ body: {
181
+ merge_method: o.method,
182
+ commit_title: o.subject,
183
+ commit_message: o.body,
184
+ sha: pr.headSha,
185
+ },
186
+ });
187
+ if (o.deleteSource)
188
+ await api(`/git/refs/heads/${pr.head.split('/').map(encodeURIComponent).join('/')}`, {
189
+ method: 'DELETE',
190
+ });
191
+ },
192
+ isMerged: async (pr) => (await pull(pr.number)).merged === true,
193
+ };
194
+ return backend;
195
+ };
196
+ export default factory;
@@ -0,0 +1,57 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://bakers.build/schema/addon-forge-github/options.schema.json",
4
+ "title": "@bakers-build/addon-forge-github options",
5
+ "description": "The forge entry's with.backend.with: a GitHub App, or the conductor's gh login with auth 'gh'.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": [
9
+ "repository"
10
+ ],
11
+ "properties": {
12
+ "repository": {
13
+ "type": "string",
14
+ "pattern": "^[\\w.-]+/[\\w.-]+$",
15
+ "description": "owner/repo."
16
+ },
17
+ "auth": {
18
+ "const": "gh",
19
+ "description": "Use the conductor's own gh login instead of a GitHub App."
20
+ },
21
+ "app_id": {
22
+ "type": [
23
+ "integer",
24
+ "string"
25
+ ],
26
+ "minLength": 1
27
+ },
28
+ "installation_id": {
29
+ "type": [
30
+ "integer",
31
+ "string"
32
+ ],
33
+ "minLength": 1
34
+ },
35
+ "private_key": {
36
+ "type": "string",
37
+ "minLength": 1,
38
+ "description": "The App private key (PEM); machine config only."
39
+ },
40
+ "private_key_env": {
41
+ "type": "string",
42
+ "minLength": 1,
43
+ "description": "Names the conductor environment variable that holds the credential."
44
+ }
45
+ },
46
+ "if": {
47
+ "required": [
48
+ "auth"
49
+ ]
50
+ },
51
+ "else": {
52
+ "required": [
53
+ "app_id",
54
+ "installation_id"
55
+ ]
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-forge-github",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.1-next.2",
4
+ "description": "bakers.build forge backend for GitHub: a GitHub App installation token scoped to one repository. Implements @bakers-build/addon-forge's ForgeBackend contract.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./dist/src/index.js",
9
+ "./options.schema.json": "./options.schema.json"
10
+ },
11
+ "files": [
12
+ "dist/src",
13
+ "options.schema.json"
14
+ ],
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/bakers-build/bakers-build.git",
21
+ "directory": "bakers-cli/addons/forge-github"
22
+ },
23
+ "peerDependencies": {
24
+ "@bakers-build/addon-forge": "^0.8.1-next.2",
25
+ "@bakers-build/core": "^0.8.1-next.2"
26
+ },
27
+ "bakersBuild": {
28
+ "commit": "0177880667693d1c36c65ffced82d2f3a17cbf2a",
29
+ "channel": "next"
30
+ }
31
+ }