@lbdudc/linea-git 0.2.2 → 0.3.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.
@@ -0,0 +1,6 @@
1
+ import type { DeviceAuthorization, DevicePoll } from './provider.js';
2
+ export declare const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
3
+ /** Asks a host to start a device authorization. `unsupported` when the host has no such endpoint. */
4
+ export declare function startDevice(url: string, params: Record<string, string | undefined>): Promise<DeviceAuthorization>;
5
+ /** One poll of the token endpoint: still pending (maybe told to slow down), the tokens, or an error that ends the flow. */
6
+ export declare function pollDevice(url: string, params: Record<string, string | undefined>, interval?: number): Promise<DevicePoll>;
package/dist/device.js ADDED
@@ -0,0 +1,50 @@
1
+ import { GitDeviceFlowError, GitError } from './errors.js';
2
+ export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
3
+ /** POSTs a form and reads the JSON answer, whatever its status (OAuth errors come as 4xx with a body). */
4
+ async function postForm(url, params) {
5
+ const body = new URLSearchParams();
6
+ for (const [key, value] of Object.entries(params))
7
+ if (value !== undefined && value !== '')
8
+ body.set(key, value);
9
+ const response = await fetch(url, {
10
+ method: 'POST',
11
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'linea' },
12
+ body,
13
+ signal: AbortSignal.timeout(30000)
14
+ });
15
+ const data = (await response.json().catch(() => ({})));
16
+ return { status: response.status, data };
17
+ }
18
+ /** Asks a host to start a device authorization. `unsupported` when the host has no such endpoint. */
19
+ export async function startDevice(url, params) {
20
+ const { status, data } = await postForm(url, params);
21
+ if (data.error === 'device_flow_disabled')
22
+ throw new GitDeviceFlowError('device_flow_disabled', data.error_description ?? 'device flow is off for this OAuth app');
23
+ if (status === 404 || status === 405)
24
+ throw new GitDeviceFlowError('unsupported', 'this host does not offer device sign-in');
25
+ if (status >= 400 || data.error || !data.device_code)
26
+ throw new GitError(data.error_description ?? data.error ?? `device authorization failed (${status})`, status);
27
+ return {
28
+ deviceCode: data.device_code,
29
+ userCode: data.user_code,
30
+ verificationUri: data.verification_uri ?? data.verification_url,
31
+ verificationUriComplete: data.verification_uri_complete,
32
+ expiresIn: Number(data.expires_in ?? 900),
33
+ interval: Number(data.interval ?? 5)
34
+ };
35
+ }
36
+ /** One poll of the token endpoint: still pending (maybe told to slow down), the tokens, or an error that ends the flow. */
37
+ export async function pollDevice(url, params, interval = 5) {
38
+ const { status, data } = await postForm(url, { grant_type: DEVICE_GRANT, ...params });
39
+ if (data.access_token)
40
+ return { status: 'done', tokens: { accessToken: data.access_token, refreshToken: data.refresh_token ?? null } };
41
+ switch (data.error) {
42
+ case 'authorization_pending': return { status: 'pending', interval };
43
+ case 'slow_down': return { status: 'pending', interval: Number(data.interval ?? interval + 5) };
44
+ case 'expired_token': throw new GitDeviceFlowError('expired_token', 'the code expired');
45
+ case 'access_denied': throw new GitDeviceFlowError('access_denied', 'sign-in was refused');
46
+ case 'device_flow_disabled': throw new GitDeviceFlowError('device_flow_disabled', data.error_description);
47
+ default: throw new GitError(data.error_description ?? data.error ?? `device sign-in failed (${status})`, status);
48
+ }
49
+ }
50
+ //# sourceMappingURL=device.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device.js","sourceRoot":"","sources":["../src/device.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAK1D,MAAM,CAAC,MAAM,YAAY,GAAG,8CAA8C,CAAA;AAE1E,0GAA0G;AAC1G,KAAK,UAAU,QAAQ,CAAC,GAAW,EAAE,MAA0C;IAC7E,MAAM,IAAI,GAAG,IAAI,eAAe,EAAE,CAAA;IAClC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE;YAAE,IAAI,CAAC,GAAG,CA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BAAsB,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAA;QACzG,OAAO,CAAC,CAAC,MAAM,IAAI,QAAQ,CAAC,IAAI,CAAC,iBAAiB,IAAI,IAAI,CAAC,KAAK,IAAI,0BAA0B,MAAM,GAAG,EAAE,MAAM,CAAC,CAAA;IAClH,CAAC;AACH,CAAC","sourcesContent":["import { GitDeviceFlowError, GitError } from './errors.js'\nimport type { DeviceAuthorization, DevicePoll, Tokens } from './provider.js'\n\ntype Json = Record<string, any>\n\nexport const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'\n\n/** POSTs a form and reads the JSON answer, whatever its status (OAuth errors come as 4xx with a body). */\nasync function postForm(url: string, params: Record<string, string | undefined>): Promise<{ status: number, data: Json }> {\n const body = new URLSearchParams()\n for (const [key, value] of Object.entries(params)) if (value !== undefined && value !== '') body.set(key, value)\n const response = await fetch(url, {\n method: 'POST',\n headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'linea' },\n body,\n signal: AbortSignal.timeout(30000)\n })\n const data = (await response.json().catch(() => ({}))) as Json\n return { status: response.status, data }\n}\n\n/** Asks a host to start a device authorization. `unsupported` when the host has no such endpoint. */\nexport async function startDevice(url: string, params: Record<string, string | undefined>): Promise<DeviceAuthorization> {\n const { status, data } = await postForm(url, params)\n if (data.error === 'device_flow_disabled') throw new GitDeviceFlowError('device_flow_disabled', data.error_description ?? 'device flow is off for this OAuth app')\n if (status === 404 || status === 405) throw new GitDeviceFlowError('unsupported', 'this host does not offer device sign-in')\n if (status >= 400 || data.error || !data.device_code) throw new GitError(data.error_description ?? data.error ?? `device authorization failed (${status})`, status)\n return {\n deviceCode: data.device_code,\n userCode: data.user_code,\n verificationUri: data.verification_uri ?? data.verification_url,\n verificationUriComplete: data.verification_uri_complete,\n expiresIn: Number(data.expires_in ?? 900),\n interval: Number(data.interval ?? 5)\n }\n}\n\n/** One poll of the token endpoint: still pending (maybe told to slow down), the tokens, or an error that ends the flow. */\nexport async function pollDevice(url: string, params: Record<string, string | undefined>, interval = 5): Promise<DevicePoll> {\n const { status, data } = await postForm(url, { grant_type: DEVICE_GRANT, ...params })\n if (data.access_token) return { status: 'done', tokens: { accessToken: data.access_token, refreshToken: data.refresh_token ?? null } satisfies Tokens }\n switch (data.error) {\n case 'authorization_pending': return { status: 'pending', interval }\n case 'slow_down': return { status: 'pending', interval: Number(data.interval ?? interval + 5) }\n case 'expired_token': throw new GitDeviceFlowError('expired_token', 'the code expired')\n case 'access_denied': throw new GitDeviceFlowError('access_denied', 'sign-in was refused')\n case 'device_flow_disabled': throw new GitDeviceFlowError('device_flow_disabled', data.error_description)\n default: throw new GitError(data.error_description ?? data.error ?? `device sign-in failed (${status})`, status)\n }\n}\n"]}
package/dist/errors.d.ts CHANGED
@@ -24,3 +24,8 @@ export declare class PackageVersionExistsError extends Error {
24
24
  export declare class PackageVersionInvalidError extends Error {
25
25
  constructor(message: string);
26
26
  }
27
+ /** The device authorization flow cannot go on: the code expired, the user refused, the host's app has it off, or the host has none. */
28
+ export declare class GitDeviceFlowError extends GitAuthError {
29
+ reason: 'expired_token' | 'access_denied' | 'device_flow_disabled' | 'unsupported';
30
+ constructor(reason: 'expired_token' | 'access_denied' | 'device_flow_disabled' | 'unsupported', message?: string);
31
+ }
package/dist/errors.js CHANGED
@@ -44,4 +44,13 @@ export class PackageVersionInvalidError extends Error {
44
44
  this.name = 'PackageVersionInvalidError';
45
45
  }
46
46
  }
47
+ /** The device authorization flow cannot go on: the code expired, the user refused, the host's app has it off, or the host has none. */
48
+ export class GitDeviceFlowError extends GitAuthError {
49
+ reason;
50
+ constructor(reason, message = reason) {
51
+ super(message);
52
+ this.name = 'GitDeviceFlowError';
53
+ this.reason = reason;
54
+ }
55
+ }
47
56
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,+IAA+I;AAC/I,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,MAAM,GAAG,GAAG,CAAA;IAEZ,YAAY,OAAO,GAAG,cAAc;QAClC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;IAC5B,CAAC;CACF;AAED,4FAA4F;AAC5F,MAAM,OAAO,QAAS,SAAQ,KAAK;IACjC,MAAM,CAAS;IAEf,YAAY,OAAe,EAAE,MAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,UAAU,CAAA;QACtB,IAAI,MAAM,KAAK,SAAS;YAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IAChD,CAAC;CACF;AAED,4GAA4G;AAC5G,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAA;IACtC,CAAC;CACF;AAED,6EAA6E;AAC7E,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC7C,YAAY,OAAO,GAAG,mBAAmB;QACvC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAA;IACpC,CAAC;CACF;AAED,6DAA6D;AAC7D,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IAClD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAA;IACzC,CAAC;CACF;AAED,yHAAyH;AACzH,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IACnD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAA;IAC1C,CAAC;CACF","sourcesContent":["/** The token is expired or revoked. Hosts raise their own class (GitLab's, from gitlab-commando); this one is for providers that have none. */\nexport class GitAuthError extends Error {\n status = 401\n\n constructor(message = 'unauthorized') {\n super(message)\n this.name = 'GitAuthError'\n }\n}\n\n/** The host refused or failed a request; `status` is the HTTP status when there was one. */\nexport class GitError extends Error {\n status?: number\n\n constructor(message: string, status?: number) {\n super(message)\n this.name = 'GitError'\n if (status !== undefined) this.status = status\n }\n}\n\n/** A package from a place the deployment does not trust (packages carry scripts that run in the server). */\nexport class PackageNotAllowedError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PackageNotAllowedError'\n }\n}\n\n/** There is no such package (or it is not a module / metamodel as asked). */\nexport class PackageNotFoundError extends Error {\n constructor(message = 'Package not found') {\n super(message)\n this.name = 'PackageNotFoundError'\n }\n}\n\n/** The version is already published: a tag does not move. */\nexport class PackageVersionExistsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PackageVersionExistsError'\n }\n}\n\n/** The version of a manifest cannot be published: it is not semver, or it is not greater than the last one published. */\nexport class PackageVersionInvalidError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PackageVersionInvalidError'\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,+IAA+I;AAC/I,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,MAAM,GAAG,GAAG,CAAA;IAEZ,YAAY,OAAO,GAAG,cAAc;QAClC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,cAAc,CAAA;IAC5B,CAAC;CACF;AAED,4FAA4F;AAC5F,MAAM,OAAO,QAAS,SAAQ,KAAK;IACjC,MAAM,CAAS;IAEf,YAAY,OAAe,EAAE,MAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,UAAU,CAAA;QACtB,IAAI,MAAM,KAAK,SAAS;YAAE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IAChD,CAAC;CACF;AAED,4GAA4G;AAC5G,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAA;IACtC,CAAC;CACF;AAED,6EAA6E;AAC7E,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IAC7C,YAAY,OAAO,GAAG,mBAAmB;QACvC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAA;IACpC,CAAC;CACF;AAED,6DAA6D;AAC7D,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IAClD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAA;IACzC,CAAC;CACF;AAED,yHAAyH;AACzH,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IACnD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAA;IAC1C,CAAC;CACF;AAED,uIAAuI;AACvI,MAAM,OAAO,kBAAmB,SAAQ,YAAY;IAClD,MAAM,CAA4E;IAElF,YAAY,MAAkF,EAAE,UAAkB,MAAM;QACtH,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAA;QAChC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;CACF","sourcesContent":["/** The token is expired or revoked. Hosts raise their own class (GitLab's, from gitlab-commando); this one is for providers that have none. */\nexport class GitAuthError extends Error {\n status = 401\n\n constructor(message = 'unauthorized') {\n super(message)\n this.name = 'GitAuthError'\n }\n}\n\n/** The host refused or failed a request; `status` is the HTTP status when there was one. */\nexport class GitError extends Error {\n status?: number\n\n constructor(message: string, status?: number) {\n super(message)\n this.name = 'GitError'\n if (status !== undefined) this.status = status\n }\n}\n\n/** A package from a place the deployment does not trust (packages carry scripts that run in the server). */\nexport class PackageNotAllowedError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PackageNotAllowedError'\n }\n}\n\n/** There is no such package (or it is not a module / metamodel as asked). */\nexport class PackageNotFoundError extends Error {\n constructor(message = 'Package not found') {\n super(message)\n this.name = 'PackageNotFoundError'\n }\n}\n\n/** The version is already published: a tag does not move. */\nexport class PackageVersionExistsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PackageVersionExistsError'\n }\n}\n\n/** The version of a manifest cannot be published: it is not semver, or it is not greater than the last one published. */\nexport class PackageVersionInvalidError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PackageVersionInvalidError'\n }\n}\n\n/** The device authorization flow cannot go on: the code expired, the user refused, the host's app has it off, or the host has none. */\nexport class GitDeviceFlowError extends GitAuthError {\n reason: 'expired_token' | 'access_denied' | 'device_flow_disabled' | 'unsupported'\n\n constructor(reason: 'expired_token' | 'access_denied' | 'device_flow_disabled' | 'unsupported', message: string = reason) {\n super(message)\n this.name = 'GitDeviceFlowError'\n this.reason = reason\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
- import type { AuthConfig, Capabilities, ChangeRequest, CiRunners, Comment, CommitSummary, Comparison, Delivery, DiffPosition, FileAction, FileDiff, GitProvider, Id, Issue, IssueChanges, IssueFilter, Label, Member, MergeOptions, MergeRequest, MergeRequestChanges, MergeRequestFilter, Milestone, Namespace, Page, Pipeline, PipelineJob, Release, ReleaseChanges, Repository, RepositoryFile, Template, TemplateKind, Thread, Tokens, PendingDeletion } from '../provider.js';
1
+ import type { AccessEntry, AuthConfig, Capabilities, ChangeRequest, CiRunners, Comment, CommitSummary, Comparison, Delivery, DiffPosition, FileAction, FileDiff, GitProvider, Id, Issue, IssueChanges, IssueFilter, HostUser, Label, LabelEvent, Member, MergeOptions, MergeRequest, MergeRequestChanges, MergeRequestFilter, Milestone, Namespace, Page, Pipeline, PipelineJob, Release, ReleaseChanges, Repository, RepositoryFile, Template, TemplateKind, Thread, Tokens, PendingDeletion } from '../provider.js';
2
2
  import { GitHubClient } from './client.js';
3
+ import type { DeviceAuthorization, DevicePoll } from '../provider.js';
3
4
  import { type GitHubConfig } from './config.js';
4
5
  export interface GitHubProviderOptions {
5
6
  config?: GitHubConfig;
@@ -33,6 +34,13 @@ export declare class GitHubProvider implements GitProvider {
33
34
  private placeOf;
34
35
  authConfig(): AuthConfig;
35
36
  private tokenRequest;
37
+ startDeviceAuthorization({ scope }?: {
38
+ scope?: string;
39
+ }): Promise<DeviceAuthorization>;
40
+ pollDeviceAuthorization({ deviceCode, interval }: {
41
+ deviceCode: string;
42
+ interval?: number;
43
+ }): Promise<DevicePoll>;
36
44
  exchangeCode({ code, redirectUri }: {
37
45
  code: string;
38
46
  redirectUri: string;
@@ -121,6 +129,25 @@ export declare class GitHubProvider implements GitProvider {
121
129
  id: Id;
122
130
  username: string;
123
131
  }): Promise<number>;
132
+ listAccess({ token, id }: {
133
+ token: string;
134
+ id: Id;
135
+ }): Promise<AccessEntry[]>;
136
+ setAccess({ token, id, username, accessLevel }: {
137
+ token: string;
138
+ id: Id;
139
+ username: string;
140
+ accessLevel: number;
141
+ }): Promise<void>;
142
+ removeAccess({ token, id, username }: {
143
+ token: string;
144
+ id: Id;
145
+ username: string;
146
+ }): Promise<void>;
147
+ searchUsers({ token, query }: {
148
+ token: string;
149
+ query: string;
150
+ }): Promise<HostUser[]>;
124
151
  private toFile;
125
152
  getFileRevision({ token, id, path, ref }: {
126
153
  token: string;
@@ -293,6 +320,11 @@ export declare class GitHubProvider implements GitProvider {
293
320
  id: Id;
294
321
  number: number;
295
322
  }): Promise<Comment[]>;
323
+ listIssueLabelEvents({ token, id, number }: {
324
+ token: string;
325
+ id: Id;
326
+ number: number;
327
+ }): Promise<LabelEvent[]>;
296
328
  addIssueComment({ token, id, number, body }: {
297
329
  token: string;
298
330
  id: Id;
@@ -1,7 +1,9 @@
1
1
  import crypto from 'node:crypto';
2
+ import { ACCESS } from '../access.js';
2
3
  import { readRepositoryTemplates } from '../templates.js';
3
4
  import { GitAuthError, GitError } from '../errors.js';
4
5
  import { GitHubClient } from './client.js';
6
+ import { pollDevice, startDevice } from '../device.js';
5
7
  import { GITHUB_SCOPE, githubApiUrl, githubWebIdeUrl, githubWebUrl } from './config.js';
6
8
  const PARENT_TOPIC = 'linea-in-';
7
9
  const ACCOUNT = 'account:';
@@ -131,6 +133,12 @@ export class GitHubProvider {
131
133
  throw new GitAuthError(data.error_description ?? data.error ?? 'unauthorized');
132
134
  return { accessToken: data.access_token, refreshToken: data.refresh_token ?? null };
133
135
  }
136
+ startDeviceAuthorization({ scope = GITHUB_SCOPE } = {}) {
137
+ return startDevice(`${githubWebUrl(this.config)}/login/device/code`, { client_id: this.config.clientId, scope });
138
+ }
139
+ pollDeviceAuthorization({ deviceCode, interval }) {
140
+ return pollDevice(`${githubWebUrl(this.config)}/login/oauth/access_token`, { device_code: deviceCode, client_id: this.config.clientId, client_secret: this.config.clientSecret }, interval);
141
+ }
134
142
  exchangeCode({ code, redirectUri }) {
135
143
  return this.tokenRequest({ code, redirect_uri: redirectUri });
136
144
  }
@@ -281,6 +289,31 @@ export class GitHubProvider {
281
289
  async getAccessLevel({ token, id }) {
282
290
  return accessLevelOf((await this.repoJson(token, id)).permissions);
283
291
  }
292
+ async listAccess({ token, id }) {
293
+ const repo = await this.repoJson(token, id);
294
+ const path = `/repos/${repo.full_name}/collaborators`;
295
+ const [everybody, direct] = await Promise.all([
296
+ this.client.paginate({ token, path: `${path}?affiliation=all` }),
297
+ this.client.paginate({ token, path: `${path}?affiliation=direct` })
298
+ ]);
299
+ const own = new Set(direct.map((member) => member.login));
300
+ return everybody
301
+ .map((member) => ({ username: member.login, accessLevel: LEVELS[member.role_name] ?? accessLevelOf(member.permissions), source: own.has(member.login) ? 'direct' : 'inherited' }))
302
+ .filter((entry) => entry.accessLevel >= ACCESS.REPORTER);
303
+ }
304
+ async setAccess({ token, id, username, accessLevel }) {
305
+ const repo = await this.repoJson(token, id);
306
+ const permission = accessLevel >= ACCESS.OWNER ? 'admin' : accessLevel >= ACCESS.MAINTAINER ? 'maintain' : accessLevel >= ACCESS.DEVELOPER ? 'push' : 'pull';
307
+ await this.json(token, `/repos/${repo.full_name}/collaborators/${encodeURIComponent(username)}`, { method: 'PUT', body: { permission } });
308
+ }
309
+ async removeAccess({ token, id, username }) {
310
+ const repo = await this.repoJson(token, id);
311
+ await this.json(token, `/repos/${repo.full_name}/collaborators/${encodeURIComponent(username)}`, { method: 'DELETE' });
312
+ }
313
+ async searchUsers({ token, query }) {
314
+ const found = await this.json(token, `/search/users?q=${encodeURIComponent(query)}&per_page=10`);
315
+ return (found.items ?? []).map((user) => ({ username: user.login, name: user.login, avatarUrl: user.avatar_url ?? null }));
316
+ }
284
317
  // ── files, commits ───────────────────────────────────────────────────────
285
318
  async toFile(token, repo, json) {
286
319
  let content = String(json.content ?? '').replace(/\n/g, '');
@@ -643,6 +676,14 @@ export class GitHubProvider {
643
676
  const repo = await this.repoJson(token, id);
644
677
  return (await this.client.paginate({ token, path: `/repos/${repo.full_name}/issues/${number}/comments` })).map((json) => this.toComment(json));
645
678
  }
679
+ async listIssueLabelEvents({ token, id, number }) {
680
+ const repo = await this.repoJson(token, id);
681
+ const events = await this.client.paginate({ token, path: `/repos/${repo.full_name}/issues/${number}/events` });
682
+ return events
683
+ .filter((event) => (event.event === 'labeled' || event.event === 'unlabeled') && event.label?.name)
684
+ .map((event) => ({ label: event.label.name, action: event.event === 'unlabeled' ? 'removed' : 'added', author: event.actor?.login, createdAt: event.created_at }))
685
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
686
+ }
646
687
  async addIssueComment({ token, id, number, body }) {
647
688
  const repo = await this.repoJson(token, id);
648
689
  return this.toComment(await this.json(token, `/repos/${repo.full_name}/issues/${number}/comments`, { method: 'POST', body: { body } }));