@noldova/git.github 0.0.0-stage → 0.0.1

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -2
  3. package/module.json +16 -0
  4. package/package.json +48 -4
  5. package/settings.json +4 -0
  6. package/src/api/index.d.ts +73 -0
  7. package/src/api/index.js +8 -0
  8. package/src/api/window.d.ts +19 -0
  9. package/src/api/window.js +8 -0
  10. package/src/exceptions/github.exception.js +13 -0
  11. package/src/exceptions/sign-in-answer-unreadable.exception.js +15 -0
  12. package/src/exceptions/sign-in-denied.exception.js +14 -0
  13. package/src/exceptions/sign-in-error.exception.js +16 -0
  14. package/src/exceptions/sign-in-expired.exception.js +14 -0
  15. package/src/exceptions/sign-in-expiry-invalid.exception.js +16 -0
  16. package/src/exceptions/sign-in-not-kept.exception.js +15 -0
  17. package/src/exceptions/sign-in-refused.exception.js +13 -0
  18. package/src/exceptions/sign-in-request-refused.exception.js +18 -0
  19. package/src/exceptions/sign-in-token-refused.exception.js +14 -0
  20. package/src/exceptions/sign-in-unreachable.exception.js +17 -0
  21. package/src/interfaces/i-github-token.js +8 -0
  22. package/src/models/account-read.js +15 -0
  23. package/src/models/cached-answer.js +20 -0
  24. package/src/models/device-grant.js +19 -0
  25. package/src/models/device-poll.js +26 -0
  26. package/src/models/github-repository.js +26 -0
  27. package/src/models/kept-sign-in.js +26 -0
  28. package/src/resources.js +294 -0
  29. package/src/runtime-part.js +87 -0
  30. package/src/services/github-access.js +28 -0
  31. package/src/services/github-api.js +167 -0
  32. package/src/services/github-avatars.js +115 -0
  33. package/src/services/github-device-flow.js +144 -0
  34. package/src/services/github-reads.js +149 -0
  35. package/src/services/github-sign-in.js +280 -0
  36. package/src/tools/bound-repository.js +58 -0
  37. package/src/tools/github-pr-checks-tool.js +47 -0
  38. package/src/tools/github-pr-create-tool.js +97 -0
  39. package/src/tools/github-read-tool.js +62 -0
  40. package/src/tools/github-tool-failures.js +46 -0
  41. package/src/tools/github-tools.js +25 -0
  42. package/src/types/fetcher.js +8 -0
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ export class GitHubAvatars {
10
+ fetcher;
11
+ log;
12
+ kept = new Map();
13
+ constructor(fetcher, log) {
14
+ this.fetcher = fetcher;
15
+ this.log = log;
16
+ }
17
+ async readAsync(address, signal) {
18
+ const url = GitHubAvatars.avatarUrlOf(address, undefined);
19
+ if (url === null)
20
+ return null;
21
+ url.searchParams.set(Resources.avatarSizeParameter, Resources.avatarSize);
22
+ const avatar = this.kept.get(url.href) ?? await this.fetchWithinAsync(url, signal);
23
+ if (avatar !== null)
24
+ this.keep(url.href, avatar);
25
+ return avatar;
26
+ }
27
+ async fetchWithinAsync(first, signal) {
28
+ const deadline = new AbortController();
29
+ const timer = setTimeout(() => deadline.abort(), Resources.avatarDeadline);
30
+ try {
31
+ return await this.fetchAsync(first, signal, AbortSignal.any([signal, deadline.signal]));
32
+ }
33
+ finally {
34
+ clearTimeout(timer);
35
+ }
36
+ }
37
+ async fetchAsync(first, signal, within) {
38
+ let url = first;
39
+ for (let hop = 0; url !== null && hop <= Resources.avatarRedirects; hop++) {
40
+ const response = await this.askAsync(url, signal, within);
41
+ if (response === null || !Resources.redirectStatuses.includes(response.status))
42
+ return response === null ? null : this.dataOfAsync(response, signal, within);
43
+ await response.body?.cancel();
44
+ url = GitHubAvatars.avatarUrlOf(response.headers.get(Resources.locationHeader), url.href);
45
+ }
46
+ return this.drop(Resources.avatarRedirectedAway);
47
+ }
48
+ async askAsync(url, signal, within) {
49
+ try {
50
+ return await this.fetcher(url.href, {
51
+ headers: { [Resources.acceptHeader]: Resources.avatarAccept, [Resources.userAgentHeader]: Resources.userAgent },
52
+ redirect: Resources.manualRedirect,
53
+ signal: within
54
+ });
55
+ }
56
+ catch (error) {
57
+ return this.dropFailed(error, signal, within);
58
+ }
59
+ }
60
+ dropFailed(error, signal, within) {
61
+ signal.throwIfAborted();
62
+ if (within.aborted)
63
+ return this.drop(Resources.avatarTimedOut);
64
+ if (error instanceof TypeError)
65
+ return this.drop(String(error));
66
+ throw error;
67
+ }
68
+ drop(reason) {
69
+ this.log.write(Resources.formatAvatarDropped(reason));
70
+ return null;
71
+ }
72
+ keep(address, avatar) {
73
+ this.kept.delete(address);
74
+ this.kept.set(address, avatar);
75
+ for (const oldest of this.kept.keys()) {
76
+ if (this.kept.size <= Resources.cacheSize)
77
+ break;
78
+ this.kept.delete(oldest);
79
+ }
80
+ }
81
+ static avatarUrlOf(address, base) {
82
+ const url = address === null ? null : URL.parse(address, base);
83
+ return url !== null && url.protocol === Resources.httpsProtocol && url.host === Resources.avatarHost && url.username.length === 0
84
+ && url.password.length === 0 ? url : null;
85
+ }
86
+ async dataOfAsync(response, signal, within) {
87
+ const type = (response.headers.get(Resources.contentTypeHeader) ?? "").split(Resources.mediaTypeParameterSeparator, 1).join("").trim().toLowerCase();
88
+ const body = response.body;
89
+ if (!response.ok || !Resources.avatarTypes.includes(type) || body === null) {
90
+ await body?.cancel();
91
+ return this.drop(response.ok ? Resources.avatarNotImage : Resources.formatAvatarRefused(response.status));
92
+ }
93
+ const bytes = await this.bytesOfAsync(body, signal, within);
94
+ return bytes === null ? null : Resources.formatDataUrl(type, bytes.toString(Resources.base64Encoding));
95
+ }
96
+ async bytesOfAsync(body, signal, within) {
97
+ const reader = body.getReader();
98
+ const chunks = [];
99
+ let length = 0;
100
+ try {
101
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
102
+ length += read.value.length;
103
+ if (length > Resources.maximumAvatarBytes) {
104
+ await reader.cancel();
105
+ return this.drop(Resources.avatarTooLarge);
106
+ }
107
+ chunks.push(read.value);
108
+ }
109
+ }
110
+ catch (error) {
111
+ return this.dropFailed(error, signal, within);
112
+ }
113
+ return length === 0 ? this.drop(Resources.avatarEmpty) : Buffer.concat(chunks);
114
+ }
115
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { JsonException, JsonReader } from "@noldova/context.json";
9
+ import { DeviceCode, HostAccount, HostingProtocolException } from "@noldova/git.hosting.protocol";
10
+ import { GitHubNames } from "@noldova/git.github.protocol";
11
+ import { SignInAnswerUnreadableException } from "../exceptions/sign-in-answer-unreadable.exception.js";
12
+ import { SignInDeniedException } from "../exceptions/sign-in-denied.exception.js";
13
+ import { SignInErrorException } from "../exceptions/sign-in-error.exception.js";
14
+ import { SignInExpiredException } from "../exceptions/sign-in-expired.exception.js";
15
+ import { SignInExpiryInvalidException } from "../exceptions/sign-in-expiry-invalid.exception.js";
16
+ import { SignInRequestRefusedException } from "../exceptions/sign-in-request-refused.exception.js";
17
+ import { SignInUnreachableException } from "../exceptions/sign-in-unreachable.exception.js";
18
+ import { AccountRead } from "../models/account-read.js";
19
+ import { DeviceGrant } from "../models/device-grant.js";
20
+ import { DevicePoll } from "../models/device-poll.js";
21
+ import { Resources } from "../resources.js";
22
+ export class GitHubDeviceFlow {
23
+ fetcher;
24
+ avatars;
25
+ constructor(fetcher, avatars) {
26
+ this.fetcher = fetcher;
27
+ this.avatars = avatars;
28
+ }
29
+ async requestCodeAsync(now, signal) {
30
+ const reader = await this.postAsync(Resources.deviceCodeUrl, { [Resources.clientIdField]: GitHubNames.clientId, [Resources.scopeField]: Resources.scope }, signal);
31
+ return GitHubDeviceFlow.read(() => {
32
+ const deviceCode = reader.readNonBlankString(Resources.deviceCodeField);
33
+ const expiresIn = GitHubDeviceFlow.expiryOf(reader);
34
+ return new DeviceGrant(deviceCode, new DeviceCode(reader.readString(Resources.userCodeField), reader.readString(Resources.verificationUriField), now + expiresIn), expiresIn, GitHubDeviceFlow.intervalOf(reader) ?? Resources.defaultInterval);
35
+ });
36
+ }
37
+ async pollAsync(deviceCode, signal) {
38
+ const reader = await this.postAsync(Resources.accessTokenUrl, {
39
+ [Resources.clientIdField]: GitHubNames.clientId, [Resources.deviceCodeField]: deviceCode, [Resources.grantTypeField]: Resources.grantType
40
+ }, signal);
41
+ return GitHubDeviceFlow.read(() => {
42
+ if (!reader.hasField(Resources.errorField))
43
+ return DevicePoll.granted(reader.readNonBlankString(Resources.accessTokenField));
44
+ const error = reader.readString(Resources.errorField);
45
+ if (error === Resources.pendingError)
46
+ return DevicePoll.pending();
47
+ if (error === Resources.slowDownError)
48
+ return DevicePoll.slowedDown(GitHubDeviceFlow.intervalOf(reader));
49
+ if (error === Resources.expiredError)
50
+ throw new SignInExpiredException();
51
+ if (error === Resources.deniedError)
52
+ throw new SignInDeniedException();
53
+ throw new SignInErrorException(error);
54
+ });
55
+ }
56
+ async readAccountAsync(token, signal) {
57
+ const response = await this.fetchAsync(Resources.userUrl, {
58
+ headers: {
59
+ [Resources.acceptHeader]: Resources.gitHubJsonType, [Resources.authorizationHeader]: Resources.formatBearer(token),
60
+ [Resources.userAgentHeader]: Resources.userAgent, [Resources.apiVersionHeader]: Resources.apiVersion
61
+ }
62
+ }, signal);
63
+ if (response.status === Resources.unauthorizedStatus) {
64
+ await GitHubDeviceFlow.dropBodyAsync(response);
65
+ return null;
66
+ }
67
+ const reader = await GitHubDeviceFlow.readBodyAsync(Resources.userUrl, response, signal);
68
+ const scopes = (response.headers.get(Resources.scopesHeader) ?? "").split(Resources.scopeSeparator).map(t => t.trim()).filter(t => t.length > 0);
69
+ return GitHubDeviceFlow.read(() => new AccountRead(new HostAccount(reader.readNonBlankString(Resources.loginField), reader.readNullableString(Resources.nameField), null, scopes), reader.readNullableString(Resources.avatarUrlField)));
70
+ }
71
+ async withAvatarAsync(read, signal) {
72
+ const avatar = await this.avatars.readAsync(read.avatarUrl, signal);
73
+ const { login, name, scopes } = read.account;
74
+ return avatar === null ? read.account : new HostAccount(login, name, avatar, scopes);
75
+ }
76
+ async postAsync(url, body, signal) {
77
+ const response = await this.fetchAsync(url, {
78
+ method: Resources.postMethod,
79
+ headers: {
80
+ [Resources.acceptHeader]: Resources.jsonType, [Resources.contentTypeHeader]: Resources.jsonType, [Resources.userAgentHeader]: Resources.userAgent
81
+ },
82
+ body: JSON.stringify(body)
83
+ }, signal);
84
+ return GitHubDeviceFlow.readBodyAsync(url, response, signal);
85
+ }
86
+ async fetchAsync(url, init, signal) {
87
+ let response;
88
+ try {
89
+ response = await this.fetcher(url, { ...init, signal: AbortSignal.any([signal, AbortSignal.timeout(Resources.requestTimeout)]) });
90
+ }
91
+ catch (error) {
92
+ throw GitHubDeviceFlow.unreachable(url, error, signal);
93
+ }
94
+ signal.throwIfAborted();
95
+ return response;
96
+ }
97
+ static async readBodyAsync(url, response, signal) {
98
+ if (!response.ok) {
99
+ await GitHubDeviceFlow.dropBodyAsync(response);
100
+ throw new SignInRequestRefusedException(url, response.status);
101
+ }
102
+ let text;
103
+ try {
104
+ text = await response.text();
105
+ }
106
+ catch (error) {
107
+ throw GitHubDeviceFlow.unreachable(url, error, signal);
108
+ }
109
+ signal.throwIfAborted();
110
+ return GitHubDeviceFlow.read(() => JsonReader.parse(text));
111
+ }
112
+ static async dropBodyAsync(response) {
113
+ await response.body?.cancel();
114
+ }
115
+ static unreachable(url, error, signal) {
116
+ if (signal.aborted)
117
+ return signal.reason;
118
+ if (error instanceof TypeError || error instanceof DOMException && error.name === Resources.timeoutErrorName)
119
+ return new SignInUnreachableException(url, error);
120
+ return error;
121
+ }
122
+ static intervalOf(reader) {
123
+ if (!reader.hasField(Resources.intervalField))
124
+ return null;
125
+ const seconds = Math.max(reader.readInteger(Resources.intervalField), Resources.minimumIntervalSeconds);
126
+ return Math.min(seconds, Resources.maximumIntervalSeconds) * Resources.millisecondsPerSecond;
127
+ }
128
+ static expiryOf(reader) {
129
+ const seconds = reader.readInteger(Resources.expiresInField);
130
+ if (seconds < Resources.minimumExpirySeconds || seconds > Resources.maximumExpirySeconds)
131
+ throw new SignInExpiryInvalidException(seconds);
132
+ return seconds * Resources.millisecondsPerSecond;
133
+ }
134
+ static read(read) {
135
+ try {
136
+ return read();
137
+ }
138
+ catch (error) {
139
+ if (error instanceof JsonException || error instanceof HostingProtocolException)
140
+ throw new SignInAnswerUnreadableException(error);
141
+ throw error;
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { FailureCode } from "@noldova/desktop.protocol";
9
+ import { BranchPullRequest, CheckState, HostChanges, HostCheck, HostItem, HostPerson, HostReference, ReferenceKind, ReferenceState } from "@noldova/git.hosting.protocol";
10
+ import { GitHubNames } from "@noldova/git.github.protocol";
11
+ import { GitHubRepository } from "../models/github-repository.js";
12
+ import { Resources } from "../resources.js";
13
+ import { GitHubApi } from "./github-api.js";
14
+ export class GitHubReads {
15
+ api;
16
+ signIn;
17
+ avatars;
18
+ constructor(api, signIn, avatars) {
19
+ this.api = api;
20
+ this.signIn = signIn;
21
+ this.avatars = avatars;
22
+ }
23
+ readReferenceAsync(reference, signal) {
24
+ return this.readItemAsync(reference, signal, false);
25
+ }
26
+ readShownReferenceAsync(reference, signal) {
27
+ return this.readItemAsync(reference, signal, true);
28
+ }
29
+ async readBranchPullRequestAsync(query, signal) {
30
+ const none = new BranchPullRequest(null, []);
31
+ const token = this.signIn.token;
32
+ const repository = GitHubRepository.parse(query.path);
33
+ if (query.host !== Resources.host || token === null || repository === null)
34
+ return none;
35
+ const answer = await this.askAsync(token, async () => {
36
+ const head = encodeURIComponent(Resources.formatHeadFilter(repository.owner, query.branch));
37
+ const list = await this.api.getAsync(repository.pathOf(Resources.formatBranchPullsPath(head)), token, signal);
38
+ const first = list === null ? undefined : GitHubApi.read(() => list.readObjectArray(Resources.itemsField))[0];
39
+ if (first === undefined)
40
+ return none;
41
+ const number = GitHubApi.read(() => first.readInteger(Resources.numberField));
42
+ const pull = await this.api.getAsync(repository.pathOf(Resources.formatPullPath(number)), token, signal);
43
+ if (pull === null)
44
+ return none;
45
+ const pullRequest = GitHubApi.read(() => GitHubReads.pullRequestOf(new HostReference(GitHubNames.moduleId, repository.owner, repository.name, number), pull, null));
46
+ const commit = query.headCommit ?? GitHubApi.read(() => pull.readObject(Resources.headField).readString(Resources.shaField));
47
+ return new BranchPullRequest(pullRequest, await this.readChecksAsync(repository, commit, token, signal));
48
+ });
49
+ return this.signIn.token === token ? answer : none;
50
+ }
51
+ async createPullRequestAsync(draft, signal) {
52
+ const token = this.signIn.token;
53
+ if (token === null)
54
+ throw GitHubApi.failure(FailureCode.Unauthorized, Resources.signedOutMessage);
55
+ const repository = GitHubRepository.parse(draft.path);
56
+ if (draft.host !== Resources.host || repository === null)
57
+ throw GitHubApi.failure(FailureCode.InvalidParams, Resources.otherHostMessage);
58
+ return this.askAsync(token, async () => {
59
+ const created = await this.api.postAsync(repository.pathOf(Resources.pullsPath), token, {
60
+ [Resources.titleField]: draft.title, [Resources.bodyField]: draft.body, [Resources.headField]: draft.headBranch, [Resources.baseField]: draft.baseBranch,
61
+ [Resources.draftField]: draft.isDraft
62
+ }, signal);
63
+ return GitHubApi.read(() => GitHubReads.pullRequestOf(new HostReference(GitHubNames.moduleId, repository.owner, repository.name, created.readInteger(Resources.numberField)), created, null));
64
+ });
65
+ }
66
+ async readItemAsync(reference, signal, withAvatar) {
67
+ const token = this.signIn.token;
68
+ const repository = GitHubRepository.parse(Resources.formatRepositoryName(reference.owner, reference.repository));
69
+ if (reference.host !== GitHubNames.moduleId || token === null || repository === null)
70
+ return null;
71
+ const item = await this.askAsync(token, async () => {
72
+ const issue = await this.api.getAsync(repository.pathOf(Resources.formatIssuePath(reference.number)), token, signal);
73
+ if (issue === null)
74
+ return null;
75
+ const reading = withAvatar ? this.avatars.readAsync(GitHubApi.read(() => GitHubReads.avatarUrlOf(issue)), signal) : Promise.resolve(null);
76
+ const asking = issue.hasField(Resources.pullRequestField)
77
+ ? this.api.getAsync(repository.pathOf(Resources.formatPullPath(reference.number)), token, signal) : Promise.resolve(issue);
78
+ const [pull, avatar] = await Promise.all([asking, reading]);
79
+ signal.throwIfAborted();
80
+ if (pull === issue)
81
+ return GitHubApi.read(() => GitHubReads.issueOf(reference, issue, avatar));
82
+ return pull === null ? null : GitHubApi.read(() => GitHubReads.pullRequestOf(reference, pull, avatar));
83
+ });
84
+ return this.signIn.token === token ? item : null;
85
+ }
86
+ async readChecksAsync(repository, commit, token, signal) {
87
+ const checks = [];
88
+ for (let page = 1;; page++) {
89
+ const runs = await this.api.getAsync(repository.pathOf(Resources.formatCheckRunsPath(commit, page)), token, signal);
90
+ if (runs === null)
91
+ return checks;
92
+ const total = GitHubApi.read(() => runs.readInteger(Resources.totalCountField));
93
+ const read = GitHubApi.read(() => runs.readObjectArray(Resources.checkRunsField).map(GitHubReads.checkOf));
94
+ checks.push(...read);
95
+ if (read.length === 0 || checks.length >= total)
96
+ return checks;
97
+ }
98
+ }
99
+ async askAsync(token, ask) {
100
+ try {
101
+ return await ask();
102
+ }
103
+ catch (error) {
104
+ if (GitHubApi.isUnauthorized(error))
105
+ await this.signIn.refusedAsync(token);
106
+ throw error;
107
+ }
108
+ }
109
+ static avatarUrlOf(item) {
110
+ return item.readNullableObject(Resources.userField)?.readNullableString(Resources.avatarUrlField) ?? null;
111
+ }
112
+ static profileOf(user) {
113
+ const address = user.hasField(Resources.htmlUrlField) ? user.readNullableString(Resources.htmlUrlField) : null;
114
+ const url = address === null ? null : URL.parse(address);
115
+ return url === null || url.protocol !== Resources.httpsProtocol || url.username.length > 0 || url.password.length > 0 ? null : address;
116
+ }
117
+ static issueOf(reference, issue, avatar) {
118
+ const isOpen = issue.readString(Resources.stateField) === Resources.openState;
119
+ const notPlanned = issue.readNullableString(Resources.stateReasonField) === Resources.notPlannedReason;
120
+ const state = isOpen ? ReferenceState.Open : notPlanned ? ReferenceState.ClosedNotPlanned : ReferenceState.ClosedDone;
121
+ const closedAt = isOpen ? null : Date.parse(issue.readString(Resources.closedAtField));
122
+ return GitHubReads.itemOf(reference, ReferenceKind.Issue, state, issue, closedAt, avatar, null);
123
+ }
124
+ static pullRequestOf(reference, pull, avatar) {
125
+ const head = pull.readObject(Resources.headField);
126
+ const changes = new HostChanges(pull.readInteger(Resources.additionsField), pull.readInteger(Resources.deletionsField), pull.readInteger(Resources.changedFilesField), head.readString(Resources.refField), pull.readObject(Resources.baseField).readString(Resources.refField), head.readString(Resources.shaField));
127
+ const mergedAt = pull.readNullableString(Resources.mergedAtField);
128
+ const isOpen = pull.readString(Resources.stateField) === Resources.openState;
129
+ const state = mergedAt !== null ? ReferenceState.Merged : !isOpen ? ReferenceState.Closed
130
+ : pull.readBoolean(Resources.draftField) ? ReferenceState.Draft : ReferenceState.Open;
131
+ const closedAt = mergedAt !== null ? Date.parse(mergedAt) : isOpen ? null : Date.parse(pull.readString(Resources.closedAtField));
132
+ return GitHubReads.itemOf(reference, ReferenceKind.PullRequest, state, pull, closedAt, avatar, changes);
133
+ }
134
+ static itemOf(reference, kind, state, item, closedAt, avatar, changes) {
135
+ const user = item.readNullableObject(Resources.userField);
136
+ const author = user === null ? null : new HostPerson(user.readNonBlankString(Resources.loginField), avatar, GitHubReads.profileOf(user));
137
+ return new HostItem(reference, kind, state, item.readString(Resources.titleField), item.readString(Resources.htmlUrlField), author, Date.parse(item.readString(Resources.createdAtField)), closedAt, item.readInteger(Resources.commentsField), changes);
138
+ }
139
+ static checkOf(run) {
140
+ const status = run.readString(Resources.statusField);
141
+ const state = status !== Resources.completedCheckStatus ? (status === Resources.runningCheckStatus ? CheckState.Running : CheckState.Queued)
142
+ : GitHubReads.conclusionOf(run.readString(Resources.conclusionField));
143
+ return new HostCheck(run.readNonBlankString(Resources.nameField), state, run.readNullableString(Resources.htmlUrlField));
144
+ }
145
+ static conclusionOf(conclusion) {
146
+ return Resources.succeededConclusions.includes(conclusion) ? CheckState.Succeeded
147
+ : Resources.neutralConclusions.includes(conclusion) ? CheckState.Neutral : CheckState.Failed;
148
+ }
149
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import timers from "node:timers/promises";
9
+ import { JsonException, JsonReader } from "@noldova/context.json";
10
+ import { SecretFailureReason, SecretFailures } from "@noldova/desktop.protocol";
11
+ import { MethodFailureException } from "@noldova/desktop.runtime";
12
+ import { HostingProtocolException, HostSignIn, SignInFailure, SignInState } from "@noldova/git.hosting.protocol";
13
+ import { GitHubException } from "../exceptions/github.exception.js";
14
+ import { SignInDeniedException } from "../exceptions/sign-in-denied.exception.js";
15
+ import { SignInExpiredException } from "../exceptions/sign-in-expired.exception.js";
16
+ import { SignInNotKeptException } from "../exceptions/sign-in-not-kept.exception.js";
17
+ import { SignInTokenRefusedException } from "../exceptions/sign-in-token-refused.exception.js";
18
+ import { SignInUnreachableException } from "../exceptions/sign-in-unreachable.exception.js";
19
+ import { KeptSignIn } from "../models/kept-sign-in.js";
20
+ import { Resources } from "../resources.js";
21
+ export class GitHubSignIn {
22
+ flow;
23
+ secrets;
24
+ appWindows;
25
+ log;
26
+ changed;
27
+ stopped = new AbortController();
28
+ signIn = HostSignIn.signedOut();
29
+ waiting = null;
30
+ unfollowWindows = null;
31
+ generation = 0;
32
+ saves = 0;
33
+ heldToken = null;
34
+ unreadable = false;
35
+ constructor(flow, secrets, appWindows, log, changed) {
36
+ this.flow = flow;
37
+ this.secrets = secrets;
38
+ this.appWindows = appWindows;
39
+ this.log = log;
40
+ this.changed = changed;
41
+ }
42
+ get current() {
43
+ return this.signIn;
44
+ }
45
+ get token() {
46
+ return this.heldToken;
47
+ }
48
+ get keptUnreadable() {
49
+ return this.unreadable;
50
+ }
51
+ async restoreAsync() {
52
+ if (this.stopped.signal.aborted)
53
+ return;
54
+ let kept;
55
+ try {
56
+ kept = await this.secrets.readAsync(Resources.signInSecret);
57
+ }
58
+ catch (error) {
59
+ if (this.stopped.signal.aborted)
60
+ return;
61
+ if (!(error instanceof MethodFailureException))
62
+ throw error;
63
+ if (SecretFailures.reasonOf(error.failure) !== SecretFailureReason.NotConnected) {
64
+ this.unreadable = true;
65
+ this.log.write(Resources.formatKeptSignInUnread(error.failure.message));
66
+ }
67
+ else if (this.unfollowWindows === null)
68
+ this.unfollowWindows = this.appWindows.onChanged(() => this.restoreOnceConnected());
69
+ return;
70
+ }
71
+ this.unreadable = false;
72
+ if (kept === null)
73
+ return;
74
+ let restored;
75
+ try {
76
+ restored = KeptSignIn.fromJson(JsonReader.parseValue(kept));
77
+ }
78
+ catch (error) {
79
+ if (!(error instanceof JsonException || error instanceof HostingProtocolException))
80
+ throw error;
81
+ this.unreadable = true;
82
+ this.log.write(Resources.formatSignInFailed(SignInFailure.Unkept));
83
+ return;
84
+ }
85
+ if (this.signIn.state !== SignInState.SignedOut || this.stopped.signal.aborted)
86
+ return;
87
+ this.heldToken = restored.token;
88
+ this.set(HostSignIn.signedIn(restored.account));
89
+ this.background(this.checkAsync(restored.token, this.generation));
90
+ }
91
+ async startAsync() {
92
+ if (this.signIn.state !== SignInState.SignedOut || this.waiting !== null || this.stopped.signal.aborted)
93
+ return this.signIn;
94
+ const waiting = new AbortController();
95
+ this.waiting = waiting;
96
+ const signal = AbortSignal.any([waiting.signal, this.stopped.signal]);
97
+ try {
98
+ const grant = await this.flow.requestCodeAsync(Date.now(), signal);
99
+ this.set(HostSignIn.waiting(grant.code));
100
+ this.background(this.waitAsync(grant, signal));
101
+ }
102
+ catch (error) {
103
+ this.end(error, signal);
104
+ }
105
+ return this.signIn;
106
+ }
107
+ cancel() {
108
+ if (this.waiting === null)
109
+ return this.signIn;
110
+ this.waiting.abort();
111
+ this.waiting = null;
112
+ this.set(HostSignIn.signedOut());
113
+ return this.signIn;
114
+ }
115
+ async signOutAsync() {
116
+ this.cancel();
117
+ if (this.signIn.state === SignInState.SignedIn)
118
+ await this.forgetAsync(null);
119
+ return this.signIn;
120
+ }
121
+ async refusedAsync(token) {
122
+ if (this.heldToken === token)
123
+ await this.forgetAsync(SignInFailure.Revoked);
124
+ }
125
+ dispose() {
126
+ this.stopped.abort();
127
+ this.waiting = null;
128
+ this.heldToken = null;
129
+ this.unfollowWindows?.();
130
+ this.unfollowWindows = null;
131
+ }
132
+ restoreOnceConnected() {
133
+ this.unfollowWindows?.();
134
+ this.unfollowWindows = null;
135
+ this.background(this.restoreAsync());
136
+ }
137
+ async waitAsync(grant, signal) {
138
+ let interval = grant.interval;
139
+ const expiry = new AbortController();
140
+ const timer = setTimeout(() => expiry.abort(), grant.expiresIn);
141
+ try {
142
+ for (;;) {
143
+ await timers.setTimeout(interval, undefined, { signal });
144
+ if (expiry.signal.aborted)
145
+ throw new SignInExpiredException();
146
+ const poll = await this.flow.pollAsync(grant.deviceCode, signal);
147
+ if (poll.token !== null) {
148
+ await this.keepAsync(poll.token, signal);
149
+ return;
150
+ }
151
+ if (poll.slowDown)
152
+ interval = poll.interval ?? interval + Resources.slowDownStep;
153
+ }
154
+ }
155
+ catch (error) {
156
+ this.end(error, signal);
157
+ }
158
+ finally {
159
+ clearTimeout(timer);
160
+ }
161
+ }
162
+ async keepAsync(token, signal) {
163
+ const read = await this.flow.readAccountAsync(token, signal);
164
+ if (read === null)
165
+ throw new SignInTokenRefusedException();
166
+ const { account } = read;
167
+ const save = ++this.saves;
168
+ try {
169
+ await this.secrets.saveAsync(Resources.signInSecret, JSON.stringify(new KeptSignIn(token, account).toJson()));
170
+ }
171
+ catch (error) {
172
+ if (!(error instanceof MethodFailureException))
173
+ throw error;
174
+ throw new SignInNotKeptException(error);
175
+ }
176
+ if (signal.aborted) {
177
+ if (!this.stopped.signal.aborted && save === this.saves)
178
+ await this.removeKeptAsync();
179
+ return;
180
+ }
181
+ this.waiting = null;
182
+ this.generation++;
183
+ this.unreadable = false;
184
+ this.heldToken = token;
185
+ this.log.write(Resources.formatSignedIn(account.login));
186
+ this.set(HostSignIn.signedIn(account));
187
+ this.background(this.showAvatarAsync(read, this.generation));
188
+ }
189
+ async checkAsync(token, generation) {
190
+ let read;
191
+ try {
192
+ read = await this.flow.readAccountAsync(token, this.stopped.signal);
193
+ }
194
+ catch (error) {
195
+ if (this.stopped.signal.aborted)
196
+ return;
197
+ if (!(error instanceof GitHubException))
198
+ throw error;
199
+ this.log.write(Resources.formatSignInNotChecked(error.message));
200
+ return;
201
+ }
202
+ if (this.signIn.state !== SignInState.SignedIn || this.generation !== generation)
203
+ return;
204
+ if (read === null) {
205
+ await this.forgetAsync(SignInFailure.Revoked);
206
+ return;
207
+ }
208
+ this.set(HostSignIn.signedIn(read.account));
209
+ await this.showAvatarAsync(read, generation);
210
+ }
211
+ async showAvatarAsync(read, generation) {
212
+ let account;
213
+ try {
214
+ account = await this.flow.withAvatarAsync(read, this.stopped.signal);
215
+ }
216
+ catch (error) {
217
+ if (this.stopped.signal.aborted)
218
+ return;
219
+ throw error;
220
+ }
221
+ if (account !== read.account && this.generation === generation)
222
+ this.set(HostSignIn.signedIn(account));
223
+ }
224
+ async forgetAsync(failure) {
225
+ this.generation++;
226
+ this.heldToken = null;
227
+ let isRemoved = false;
228
+ try {
229
+ isRemoved = await this.removeKeptAsync();
230
+ }
231
+ finally {
232
+ this.set(HostSignIn.signedOut(failure ?? (isRemoved ? undefined : SignInFailure.Unforgotten)));
233
+ }
234
+ }
235
+ async removeKeptAsync() {
236
+ try {
237
+ await this.secrets.removeAsync(Resources.signInSecret);
238
+ return true;
239
+ }
240
+ catch (error) {
241
+ if (!(error instanceof MethodFailureException))
242
+ throw error;
243
+ this.log.write(Resources.tokenNotForgotten);
244
+ return false;
245
+ }
246
+ }
247
+ end(error, signal) {
248
+ if (signal.aborted)
249
+ return;
250
+ this.waiting = null;
251
+ if (!(error instanceof GitHubException)) {
252
+ if (this.signIn.state === SignInState.Waiting)
253
+ this.set(HostSignIn.signedOut());
254
+ throw error;
255
+ }
256
+ const failure = GitHubSignIn.failureOf(error);
257
+ this.log.write(Resources.formatSignInFailed(failure));
258
+ this.set(HostSignIn.signedOut(failure));
259
+ }
260
+ set(signIn) {
261
+ if (this.stopped.signal.aborted)
262
+ return;
263
+ this.signIn = signIn;
264
+ this.changed(signIn);
265
+ }
266
+ background(work) {
267
+ work.catch((error) => this.log.write(Resources.formatSignInBroken(String(error))));
268
+ }
269
+ static failureOf(error) {
270
+ if (error instanceof SignInExpiredException)
271
+ return SignInFailure.Expired;
272
+ if (error instanceof SignInDeniedException)
273
+ return SignInFailure.Denied;
274
+ if (error instanceof SignInUnreachableException)
275
+ return SignInFailure.Unreachable;
276
+ if (error instanceof SignInNotKeptException)
277
+ return SignInFailure.Unkept;
278
+ return SignInFailure.Refused;
279
+ }
280
+ }