yaml-dsl-spec-schema-reader-github 0.0.0-stage → 0.4.2-snapshot.20261127004226

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/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # yaml-dsl-spec-schema-reader-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
+ The YAML DSL standard's reader of schema URLs on GitHub, from [yaml-dsl-spec](https://github.com/litebitus/yaml-dsl-spec), registered on a schema cache to read `https://github.com/` links, a private release asset through GitHub's API with the machine's tokens.
4
+
5
+ Its API is designed in the [package design](https://github.com/litebitus/yaml-dsl-spec/blob/main/docs/package-design.md).
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ /* The YAML DSL standard's reader of schema URLs on GitHub, `https://github.com/` links. */
4
+
5
+ const { GithubSchemaReader } = require('./lib/github-schema-reader');
6
+
7
+ module.exports = { GithubSchemaReader };
@@ -0,0 +1,303 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * The YAML DSL standard's reader of schema URLs on GitHub: a link read as
5
+ * written, and, with the machine's credentials, a release asset read through
6
+ * GitHub's API with each of the machine's tokens in turn.
7
+ */
8
+
9
+ const { spawn } = require('child_process');
10
+
11
+ const { schemaResolution } = require('yaml-dsl-spec');
12
+
13
+ const {
14
+ answerOf, refusedAnswer, failedAnswer, httpGet, httpConditionalHeaders,
15
+ } = schemaResolution;
16
+
17
+ const GITHUB_PREFIXES = ['https://github.com/', 'https://www.github.com/'];
18
+ const GITHUB_API = 'https://api.github.com';
19
+ const GITHUB_API_HOST = 'api.github.com';
20
+ const GITHUB_REFUSER = 'GitHub';
21
+ const GITHUB_JSON = 'application/vnd.github+json';
22
+ const GH_LOGIN_TIMEOUT_MILLISECONDS = 10 * 1000;
23
+ const STATUS_OK = 200;
24
+ const STATUS_NOT_MODIFIED = 304;
25
+ const STATUS_UNAUTHORIZED = 401;
26
+ const STATUS_FORBIDDEN = 403;
27
+ const STATUS_NOT_FOUND = 404;
28
+ const NO_TOKEN_FIX = 'set `GH_TOKEN`, run `gh auth login`, or add a `.netrc` entry for api.github.com';
29
+
30
+ /** The machine's tokens, `{ credentialOrigin, authorization, renewalFix }`, read when first needed. */
31
+ class MachineTokens {
32
+ constructor() {
33
+ this.tokensRead = null;
34
+ }
35
+
36
+ /** A promise of the tokens, in the order they are tried. */
37
+ githubTokens() {
38
+ if (this.tokensRead === null) this.tokensRead = machineTokens();
39
+ return this.tokensRead;
40
+ }
41
+
42
+ /** Reads the tokens again when next asked, after every one was refused. */
43
+ forgetTokens() {
44
+ this.tokensRead = null;
45
+ }
46
+ }
47
+
48
+ /** `GH_TOKEN`, `GITHUB_TOKEN`, the `gh` command's login, then the `.netrc` entry for api.github.com. */
49
+ async function machineTokens() {
50
+ const tokens = [];
51
+ for (const variableName of ['GH_TOKEN', 'GITHUB_TOKEN']) {
52
+ const variableToken = process.env[variableName];
53
+ if (variableToken) {
54
+ tokens.push({
55
+ credentialOrigin: `\`${variableName}\``,
56
+ authorization: `Bearer ${variableToken}`,
57
+ renewalFix: `replace \`${variableName}\``,
58
+ });
59
+ }
60
+ }
61
+ const loginToken = await ghLoginToken();
62
+ if (loginToken !== null) {
63
+ tokens.push({
64
+ credentialOrigin: '`gh auth token`',
65
+ authorization: `Bearer ${loginToken}`,
66
+ renewalFix: 'run `gh auth login`',
67
+ });
68
+ }
69
+ const login = schemaResolution.netrcLogin(GITHUB_API_HOST);
70
+ if (login !== null) {
71
+ tokens.push({
72
+ credentialOrigin: login.credentialOrigin,
73
+ authorization: login.authorization(),
74
+ renewalFix: login.renewalFix,
75
+ });
76
+ }
77
+ return tokens;
78
+ }
79
+
80
+ /**
81
+ * The token of the account `gh auth login` logged in to github.com, where the
82
+ * `gh` command is installed and answers within its time; `null` otherwise.
83
+ */
84
+ function ghLoginToken() {
85
+ return new Promise((resolve) => {
86
+ let ghCommand;
87
+ try {
88
+ ghCommand = spawn('gh', ['auth', 'token', '--hostname', 'github.com'], { stdio: ['ignore', 'pipe', 'ignore'] });
89
+ } catch {
90
+ resolve(null);
91
+ return;
92
+ }
93
+ const outputChunks = [];
94
+ const loginTimer = setTimeout(() => {
95
+ ghCommand.kill();
96
+ resolve(null);
97
+ }, GH_LOGIN_TIMEOUT_MILLISECONDS);
98
+ ghCommand.stdout.on('data', (outputChunk) => outputChunks.push(outputChunk));
99
+ ghCommand.on('error', () => {
100
+ clearTimeout(loginTimer);
101
+ resolve(null);
102
+ });
103
+ ghCommand.on('close', (exitCode) => {
104
+ clearTimeout(loginTimer);
105
+ const loginToken = Buffer.concat(outputChunks).toString('utf8').trim();
106
+ resolve(exitCode === 0 && loginToken !== '' ? loginToken : null);
107
+ });
108
+ });
109
+ }
110
+
111
+ /** The URL reader of GitHub links. */
112
+ class GithubSchemaReader {
113
+ constructor() {
114
+ this.urlPrefixes = [...GITHUB_PREFIXES];
115
+ this.readsRemoteSources = true;
116
+ this.tokenSource = new MachineTokens();
117
+ this.githubApi = GITHUB_API;
118
+ }
119
+
120
+ async readSchemaUrl(request) {
121
+ if (request.machineCredentials) {
122
+ const release = this.githubRelease(request.fetchUrl);
123
+ if (release !== null && release.releaseAsset !== null) {
124
+ return this.releaseAnswer(release.owner, release.repository, release.releaseAsset, request);
125
+ }
126
+ }
127
+ return linkAnswer(request);
128
+ }
129
+
130
+ githubRelease(url) {
131
+ const prefix = this.urlPrefixes.find(
132
+ (linkPrefix) => url.slice(0, linkPrefix.length).toLowerCase() === linkPrefix.toLowerCase(),
133
+ );
134
+ return prefix === undefined ? null : githubReleaseOf(url.slice(prefix.length));
135
+ }
136
+
137
+ /**
138
+ * A release asset read through GitHub's API, each token tried in turn until one
139
+ * is let in, each one refused before it listed.
140
+ */
141
+ async releaseAnswer(owner, repository, releaseAsset, request) {
142
+ const tokens = await this.tokenSource.githubTokens();
143
+ if (tokens.length === 0) {
144
+ return refusedAnswer([{
145
+ refusedBy: GITHUB_REFUSER,
146
+ credentialOrigin: null,
147
+ refusalReason: 'no GitHub token is set',
148
+ renewalFix: NO_TOKEN_FIX,
149
+ }]);
150
+ }
151
+ const answerWith = (readOutcome, readRefusals) => ({ readOutcome, readRefusals });
152
+ const failedOutcome = (failureReason) => ({ outcomeKind: 'readFailed', failureReason });
153
+ const repositoryName = `\`${owner}/${repository}\``;
154
+ const repositoryUrl = `${this.githubApi}/repos/${owner}/${repository}`;
155
+ const releaseUrl = `${repositoryUrl}/releases/${releaseApiPath(releaseAsset.release)}`;
156
+ const refusals = [];
157
+ let missingReason = null;
158
+ for (const token of tokens) {
159
+ const apiHeaders = { Authorization: token.authorization, Accept: GITHUB_JSON };
160
+ let releaseReply;
161
+ try {
162
+ releaseReply = await httpGet(releaseUrl, apiHeaders, request.signal);
163
+ } catch (error) {
164
+ return answerWith(failedOutcome(error.message), refusals);
165
+ }
166
+ if (releaseReply.statusCode === STATUS_UNAUTHORIZED || releaseReply.statusCode === STATUS_FORBIDDEN) {
167
+ refusals.push(tokenRefusal(token, releaseReply.statusCode));
168
+ continue;
169
+ }
170
+ if (releaseReply.statusCode !== STATUS_OK) {
171
+ if (await this.repositorySeen(repositoryUrl, apiHeaders, request)) {
172
+ missingReason = `${repositoryName} has no ${releaseShownName(releaseAsset.release)}`;
173
+ break;
174
+ }
175
+ continue;
176
+ }
177
+ let listing;
178
+ try {
179
+ listing = JSON.parse(releaseReply.replyText);
180
+ } catch (error) {
181
+ return answerWith(failedOutcome(error.message), refusals);
182
+ }
183
+ const listedAssets = listing !== null && Array.isArray(listing.assets) ? listing.assets : [];
184
+ const listedAsset = listedAssets.find((listed) => listed !== null && listed.name === releaseAsset.assetName);
185
+ if (listedAsset === undefined || typeof listedAsset.url !== 'string') {
186
+ missingReason = `${releaseShownName(releaseAsset.release)} of ${repositoryName} `
187
+ + `has no asset \`${releaseAsset.assetName}\``;
188
+ break;
189
+ }
190
+ const downloadHeaders = {
191
+ ...httpConditionalHeaders(request.keptCopyVersion),
192
+ Authorization: token.authorization,
193
+ Accept: 'application/octet-stream',
194
+ };
195
+ let download;
196
+ try {
197
+ download = await httpGet(listedAsset.url, downloadHeaders, request.signal);
198
+ } catch (error) {
199
+ return answerWith(failedOutcome(error.message), refusals);
200
+ }
201
+ if (download.statusCode === STATUS_UNAUTHORIZED || download.statusCode === STATUS_FORBIDDEN) {
202
+ refusals.push(tokenRefusal(token, download.statusCode));
203
+ continue;
204
+ }
205
+ return answerWith(sentAnswer(download).readOutcome, refusals);
206
+ }
207
+ if (missingReason !== null) return answerWith({ outcomeKind: 'sourceMissing', missingReason }, refusals);
208
+ if (refusals.length === tokens.length) {
209
+ this.tokenSource.forgetTokens();
210
+ return refusedAnswer(refusals);
211
+ }
212
+ return answerWith(failedOutcome(`no credential can see ${repositoryName}`), refusals);
213
+ }
214
+
215
+ /** Whether the repository answers a token's request. */
216
+ async repositorySeen(repositoryUrl, apiHeaders, request) {
217
+ try {
218
+ const repositoryReply = await httpGet(repositoryUrl, apiHeaders, request.signal);
219
+ return repositoryReply.statusCode === STATUS_OK;
220
+ } catch {
221
+ return false;
222
+ }
223
+ }
224
+ }
225
+
226
+ /** The reader of the GitHub at `githubApi`, its links read under `linkPrefixes`, with `tokenSource`'s tokens. */
227
+ function githubSchemaReaderAt(tokenSource, githubApi, linkPrefixes) {
228
+ const reader = new GithubSchemaReader();
229
+ reader.tokenSource = tokenSource;
230
+ reader.githubApi = githubApi;
231
+ reader.urlPrefixes = linkPrefixes;
232
+ return reader;
233
+ }
234
+
235
+ /** The link read as written, the machine's credentials never sent. */
236
+ async function linkAnswer(request) {
237
+ let reply;
238
+ try {
239
+ reply = await httpGet(request.fetchUrl, httpConditionalHeaders(request.keptCopyVersion), request.signal);
240
+ } catch (error) {
241
+ return failedAnswer(error.message);
242
+ }
243
+ if ([STATUS_UNAUTHORIZED, STATUS_FORBIDDEN, STATUS_NOT_FOUND].includes(reply.statusCode)) {
244
+ return refusedAnswer([{
245
+ refusedBy: GITHUB_REFUSER,
246
+ credentialOrigin: null,
247
+ refusalReason: String(reply.statusCode),
248
+ renewalFix: null,
249
+ }]);
250
+ }
251
+ return sentAnswer(reply);
252
+ }
253
+
254
+ function sentAnswer(reply) {
255
+ if (reply.statusCode === STATUS_OK) {
256
+ return answerOf({ outcomeKind: 'textSent', schemaText: reply.replyText, copyVersion: reply.copyVersion });
257
+ }
258
+ if (reply.statusCode === STATUS_NOT_MODIFIED) return answerOf({ outcomeKind: 'copyConfirmed' });
259
+ return failedAnswer(`GitHub answered ${reply.statusCode}`);
260
+ }
261
+
262
+ function tokenRefusal(token, status) {
263
+ return {
264
+ refusedBy: GITHUB_REFUSER,
265
+ credentialOrigin: token.credentialOrigin,
266
+ refusalReason: status === STATUS_UNAUTHORIZED ? '401 Bad credentials' : String(status),
267
+ renewalFix: token.renewalFix,
268
+ };
269
+ }
270
+
271
+ /** A release by its kind: `{ releaseKind: 'latestRelease' }` or `{ releaseKind: 'taggedRelease', releaseTag }`. */
272
+ function releaseApiPath(release) {
273
+ return release.releaseKind === 'latestRelease' ? 'latest' : `tags/${release.releaseTag.replaceAll('/', '%2F')}`;
274
+ }
275
+
276
+ function releaseShownName(release) {
277
+ return release.releaseKind === 'latestRelease' ? 'the latest release' : `release \`${release.releaseTag}\``;
278
+ }
279
+
280
+ /**
281
+ * The repository a link's path, after its host, names under
282
+ * `<owner>/<repo>/releases/`, and the release asset that path reads,
283
+ * `download/<tag>/<asset>` or `latest/download/<asset>`, `null` where it reads
284
+ * none; `null` for a path naming no repository's releases.
285
+ */
286
+ function githubReleaseOf(linkPath) {
287
+ const [pathOnly] = linkPath.split(/[?#]/u);
288
+ const steps = pathOnly.split('/');
289
+ const [owner, repository, releasesStep, ...releaseSteps] = steps;
290
+ if (steps.length < 3 || releasesStep !== 'releases' || owner === '' || repository === '') return null;
291
+ let releaseAsset = null;
292
+ if (releaseSteps.length === 3 && releaseSteps[0] === 'latest' && releaseSteps[1] === 'download') {
293
+ releaseAsset = { release: { releaseKind: 'latestRelease' }, assetName: releaseSteps[2] };
294
+ } else if (releaseSteps.length >= 3 && releaseSteps[0] === 'download') {
295
+ releaseAsset = {
296
+ release: { releaseKind: 'taggedRelease', releaseTag: releaseSteps.slice(1, -1).join('/') },
297
+ assetName: releaseSteps[releaseSteps.length - 1],
298
+ };
299
+ }
300
+ return { owner, repository, releaseAsset };
301
+ }
302
+
303
+ module.exports = { GithubSchemaReader, MachineTokens, githubSchemaReaderAt, githubReleaseOf, NO_TOKEN_FIX };
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "yaml-dsl-spec-schema-reader-github",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.2-snapshot.20261127004226",
4
+ "description": "The YAML DSL standard's reader of schema URLs on GitHub, a release asset read through GitHub's API with the machine's tokens.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/litebitus/yaml-dsl-spec.git",
9
+ "directory": "javascript/schema-reader-github"
10
+ },
11
+ "main": "index.js",
12
+ "files": [
13
+ "index.js",
14
+ "lib/*.js"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test --test-timeout=5000 --test-force-exit --experimental-test-coverage --test-coverage-exclude=test/** --test-coverage-exclude=../** --test-coverage-lines=90 test/"
18
+ },
19
+ "peerDependencies": {
20
+ "yaml-dsl-spec": "0.4.2-snapshot.20261127004226"
21
+ }
22
+ }