@logto/connector-github 1.2.0 → 1.4.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/lib/constant.d.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import type { ConnectorMetadata } from '@logto/connector-kit';
2
2
  export declare const authorizationEndpoint = "https://github.com/login/oauth/authorize";
3
- export declare const scope = "read:user";
3
+ /**
4
+ * `read:user` read user profile data; `user:email` read user email addresses (including private email addresses).
5
+ * Ref: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
6
+ */
7
+ export declare const scope = "read:user user:email";
4
8
  export declare const accessTokenEndpoint = "https://github.com/login/oauth/access_token";
5
9
  export declare const userInfoEndpoint = "https://api.github.com/user";
10
+ export declare const userEmailsEndpoint = "https://api.github.com/user/emails";
6
11
  export declare const defaultMetadata: ConnectorMetadata;
7
12
  export declare const defaultTimeout = 5000;
package/lib/index.js CHANGED
@@ -1,5 +1,4 @@
1
- import { got, HTTPError } from 'got';
2
- import { ConnectorPlatform, ConnectorConfigFormItemType, ConnectorError, ConnectorErrorCodes, ConnectorType, validateConfig, parseJson } from '@logto/connector-kit';
1
+ import { ConnectorPlatform, ConnectorConfigFormItemType, ConnectorError, ConnectorErrorCodes, ConnectorType, validateConfig, jsonGuard } from '@logto/connector-kit';
3
2
  import { z } from 'zod';
4
3
 
5
4
  // https://github.com/facebook/jest/issues/7547
@@ -27,349 +26,565 @@ const notFalsy = (value) => Boolean(value);
27
26
  */
28
27
  const conditional = (exp) => (notFalsy(exp) ? exp : undefined);
29
28
 
30
- function getDefaultExportFromCjs (x) {
31
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
32
- }
33
-
34
- var token = '%[a-f0-9]{2}';
35
- var singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');
36
- var multiMatcher = new RegExp('(' + token + ')+', 'gi');
37
-
38
- function decodeComponents(components, split) {
39
- try {
40
- // Try to decode the entire string first
41
- return [decodeURIComponent(components.join(''))];
42
- } catch (err) {
43
- // Do nothing
44
- }
45
-
46
- if (components.length === 1) {
47
- return components;
48
- }
49
-
50
- split = split || 1;
51
-
52
- // Split the array in 2 parts
53
- var left = components.slice(0, split);
54
- var right = components.slice(split);
55
-
56
- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
57
- }
58
-
59
- function decode$1(input) {
60
- try {
61
- return decodeURIComponent(input);
62
- } catch (err) {
63
- var tokens = input.match(singleMatcher) || [];
64
-
65
- for (var i = 1; i < tokens.length; i++) {
66
- input = decodeComponents(tokens, i).join('');
67
-
68
- tokens = input.match(singleMatcher) || [];
69
- }
70
-
71
- return input;
72
- }
29
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
30
+ class HTTPError extends Error {
31
+ constructor(response, request, options) {
32
+ const code = (response.status || response.status === 0) ? response.status : '';
33
+ const title = response.statusText || '';
34
+ const status = `${code} ${title}`.trim();
35
+ const reason = status ? `status code ${status}` : 'an unknown error';
36
+ super(`Request failed with ${reason}`);
37
+ Object.defineProperty(this, "response", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "request", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ Object.defineProperty(this, "options", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: void 0
54
+ });
55
+ this.name = 'HTTPError';
56
+ this.response = response;
57
+ this.request = request;
58
+ this.options = options;
59
+ }
73
60
  }
74
61
 
75
- function customDecodeURIComponent(input) {
76
- // Keep track of all the replacements and prefill the map with the `BOM`
77
- var replaceMap = {
78
- '%FE%FF': '\uFFFD\uFFFD',
79
- '%FF%FE': '\uFFFD\uFFFD'
80
- };
81
-
82
- var match = multiMatcher.exec(input);
83
- while (match) {
84
- try {
85
- // Decode as big chunks as possible
86
- replaceMap[match[0]] = decodeURIComponent(match[0]);
87
- } catch (err) {
88
- var result = decode$1(match[0]);
89
-
90
- if (result !== match[0]) {
91
- replaceMap[match[0]] = result;
92
- }
93
- }
94
-
95
- match = multiMatcher.exec(input);
96
- }
97
-
98
- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
99
- replaceMap['%C2'] = '\uFFFD';
100
-
101
- var entries = Object.keys(replaceMap);
102
-
103
- for (var i = 0; i < entries.length; i++) {
104
- // Replace all decoded components
105
- var key = entries[i];
106
- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
107
- }
108
-
109
- return input;
62
+ class TimeoutError extends Error {
63
+ constructor(request) {
64
+ super('Request timed out');
65
+ Object.defineProperty(this, "request", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: void 0
70
+ });
71
+ this.name = 'TimeoutError';
72
+ this.request = request;
73
+ }
110
74
  }
111
75
 
112
- var decodeUriComponent = function (encodedURI) {
113
- if (typeof encodedURI !== 'string') {
114
- throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
115
- }
116
-
117
- try {
118
- encodedURI = encodedURI.replace(/\+/g, ' ');
76
+ // eslint-disable-next-line @typescript-eslint/ban-types
77
+ const isObject = (value) => value !== null && typeof value === 'object';
119
78
 
120
- // Try the built in decoder first
121
- return decodeURIComponent(encodedURI);
122
- } catch (err) {
123
- // Fallback to a more advanced decoder
124
- return customDecodeURIComponent(encodedURI);
125
- }
79
+ const validateAndMerge = (...sources) => {
80
+ for (const source of sources) {
81
+ if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
82
+ throw new TypeError('The `options` argument must be an object');
83
+ }
84
+ }
85
+ return deepMerge({}, ...sources);
126
86
  };
127
-
128
- var decodeComponent = /*@__PURE__*/getDefaultExportFromCjs(decodeUriComponent);
129
-
130
- var splitOnFirst = (string, separator) => {
131
- if (!(typeof string === 'string' && typeof separator === 'string')) {
132
- throw new TypeError('Expected the arguments to be of type `string`');
133
- }
134
-
135
- if (separator === '') {
136
- return [string];
137
- }
138
-
139
- const separatorIndex = string.indexOf(separator);
140
-
141
- if (separatorIndex === -1) {
142
- return [string];
143
- }
144
-
145
- return [
146
- string.slice(0, separatorIndex),
147
- string.slice(separatorIndex + separator.length)
148
- ];
87
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
88
+ const result = new globalThis.Headers(source1);
89
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
90
+ const source = new globalThis.Headers(source2);
91
+ for (const [key, value] of source.entries()) {
92
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
93
+ result.delete(key);
94
+ }
95
+ else {
96
+ result.set(key, value);
97
+ }
98
+ }
99
+ return result;
100
+ };
101
+ // TODO: Make this strongly-typed (no `any`).
102
+ const deepMerge = (...sources) => {
103
+ let returnValue = {};
104
+ let headers = {};
105
+ for (const source of sources) {
106
+ if (Array.isArray(source)) {
107
+ if (!Array.isArray(returnValue)) {
108
+ returnValue = [];
109
+ }
110
+ returnValue = [...returnValue, ...source];
111
+ }
112
+ else if (isObject(source)) {
113
+ for (let [key, value] of Object.entries(source)) {
114
+ if (isObject(value) && key in returnValue) {
115
+ value = deepMerge(returnValue[key], value);
116
+ }
117
+ returnValue = { ...returnValue, [key]: value };
118
+ }
119
+ if (isObject(source.headers)) {
120
+ headers = mergeHeaders(headers, source.headers);
121
+ returnValue.headers = headers;
122
+ }
123
+ }
124
+ }
125
+ return returnValue;
149
126
  };
150
127
 
151
- var splitOnFirst$1 = /*@__PURE__*/getDefaultExportFromCjs(splitOnFirst);
152
-
153
- function parserForArrayFormat(options) {
154
- let result;
155
-
156
- switch (options.arrayFormat) {
157
- case 'index': {
158
- return (key, value, accumulator) => {
159
- result = /\[(\d*)]$/.exec(key);
160
-
161
- key = key.replace(/\[\d*]$/, '');
162
-
163
- if (!result) {
164
- accumulator[key] = value;
165
- return;
166
- }
167
-
168
- if (accumulator[key] === undefined) {
169
- accumulator[key] = {};
170
- }
171
-
172
- accumulator[key][result[1]] = value;
173
- };
174
- }
175
-
176
- case 'bracket': {
177
- return (key, value, accumulator) => {
178
- result = /(\[])$/.exec(key);
179
- key = key.replace(/\[]$/, '');
180
-
181
- if (!result) {
182
- accumulator[key] = value;
183
- return;
184
- }
185
-
186
- if (accumulator[key] === undefined) {
187
- accumulator[key] = [value];
188
- return;
189
- }
190
-
191
- accumulator[key] = [...accumulator[key], value];
192
- };
193
- }
194
-
195
- case 'colon-list-separator': {
196
- return (key, value, accumulator) => {
197
- result = /(:list)$/.exec(key);
198
- key = key.replace(/:list$/, '');
199
-
200
- if (!result) {
201
- accumulator[key] = value;
202
- return;
203
- }
204
-
205
- if (accumulator[key] === undefined) {
206
- accumulator[key] = [value];
207
- return;
208
- }
209
-
210
- accumulator[key] = [...accumulator[key], value];
211
- };
212
- }
213
-
214
- case 'comma':
215
- case 'separator': {
216
- return (key, value, accumulator) => {
217
- const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
218
- const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));
219
- value = isEncodedArray ? decode(value, options) : value;
220
- const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : (value === null ? value : decode(value, options));
221
- accumulator[key] = newValue;
222
- };
223
- }
224
-
225
- case 'bracket-separator': {
226
- return (key, value, accumulator) => {
227
- const isArray = /(\[])$/.test(key);
228
- key = key.replace(/\[]$/, '');
229
-
230
- if (!isArray) {
231
- accumulator[key] = value ? decode(value, options) : value;
232
- return;
233
- }
234
-
235
- const arrayValue = value === null
236
- ? []
237
- : value.split(options.arrayFormatSeparator).map(item => decode(item, options));
238
-
239
- if (accumulator[key] === undefined) {
240
- accumulator[key] = arrayValue;
241
- return;
242
- }
243
-
244
- accumulator[key] = [...accumulator[key], ...arrayValue];
245
- };
246
- }
247
-
248
- default: {
249
- return (key, value, accumulator) => {
250
- if (accumulator[key] === undefined) {
251
- accumulator[key] = value;
252
- return;
253
- }
254
-
255
- accumulator[key] = [...[accumulator[key]].flat(), value];
256
- };
257
- }
258
- }
259
- }
260
-
261
- function validateArrayFormatSeparator(value) {
262
- if (typeof value !== 'string' || value.length !== 1) {
263
- throw new TypeError('arrayFormatSeparator must be single character string');
264
- }
265
- }
128
+ const supportsRequestStreams = (() => {
129
+ let duplexAccessed = false;
130
+ let hasContentType = false;
131
+ const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
132
+ const supportsRequest = typeof globalThis.Request === 'function';
133
+ if (supportsReadableStream && supportsRequest) {
134
+ hasContentType = new globalThis.Request('https://empty.invalid', {
135
+ body: new globalThis.ReadableStream(),
136
+ method: 'POST',
137
+ // @ts-expect-error - Types are outdated.
138
+ get duplex() {
139
+ duplexAccessed = true;
140
+ return 'half';
141
+ },
142
+ }).headers.has('Content-Type');
143
+ }
144
+ return duplexAccessed && !hasContentType;
145
+ })();
146
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
147
+ const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';
148
+ const supportsFormData = typeof globalThis.FormData === 'function';
149
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
150
+ const responseTypes = {
151
+ json: 'application/json',
152
+ text: 'text/*',
153
+ formData: 'multipart/form-data',
154
+ arrayBuffer: '*/*',
155
+ blob: '*/*',
156
+ };
157
+ // The maximum value of a 32bit int (see issue #117)
158
+ const maxSafeTimeout = 2_147_483_647;
159
+ const stop = Symbol('stop');
160
+ const kyOptionKeys = {
161
+ json: true,
162
+ parseJson: true,
163
+ searchParams: true,
164
+ prefixUrl: true,
165
+ retry: true,
166
+ timeout: true,
167
+ hooks: true,
168
+ throwHttpErrors: true,
169
+ onDownloadProgress: true,
170
+ fetch: true,
171
+ };
172
+ const requestOptionsRegistry = {
173
+ method: true,
174
+ headers: true,
175
+ body: true,
176
+ mode: true,
177
+ credentials: true,
178
+ cache: true,
179
+ redirect: true,
180
+ referrer: true,
181
+ referrerPolicy: true,
182
+ integrity: true,
183
+ keepalive: true,
184
+ signal: true,
185
+ window: true,
186
+ dispatcher: true,
187
+ duplex: true,
188
+ priority: true,
189
+ };
266
190
 
267
- function decode(value, options) {
268
- if (options.decode) {
269
- return decodeComponent(value);
270
- }
191
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
192
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
193
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
194
+ const retryAfterStatusCodes = [413, 429, 503];
195
+ const defaultRetryOptions = {
196
+ limit: 2,
197
+ methods: retryMethods,
198
+ statusCodes: retryStatusCodes,
199
+ afterStatusCodes: retryAfterStatusCodes,
200
+ maxRetryAfter: Number.POSITIVE_INFINITY,
201
+ backoffLimit: Number.POSITIVE_INFINITY,
202
+ delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
203
+ };
204
+ const normalizeRetryOptions = (retry = {}) => {
205
+ if (typeof retry === 'number') {
206
+ return {
207
+ ...defaultRetryOptions,
208
+ limit: retry,
209
+ };
210
+ }
211
+ if (retry.methods && !Array.isArray(retry.methods)) {
212
+ throw new Error('retry.methods must be an array');
213
+ }
214
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
215
+ throw new Error('retry.statusCodes must be an array');
216
+ }
217
+ return {
218
+ ...defaultRetryOptions,
219
+ ...retry,
220
+ afterStatusCodes: retryAfterStatusCodes,
221
+ };
222
+ };
271
223
 
272
- return value;
224
+ // `Promise.race()` workaround (#91)
225
+ async function timeout(request, init, abortController, options) {
226
+ return new Promise((resolve, reject) => {
227
+ const timeoutId = setTimeout(() => {
228
+ if (abortController) {
229
+ abortController.abort();
230
+ }
231
+ reject(new TimeoutError(request));
232
+ }, options.timeout);
233
+ void options
234
+ .fetch(request, init)
235
+ .then(resolve)
236
+ .catch(reject)
237
+ .then(() => {
238
+ clearTimeout(timeoutId);
239
+ });
240
+ });
273
241
  }
274
242
 
275
- function keysSorter(input) {
276
- if (Array.isArray(input)) {
277
- return input.sort();
278
- }
279
-
280
- if (typeof input === 'object') {
281
- return keysSorter(Object.keys(input))
282
- .sort((a, b) => Number(a) - Number(b))
283
- .map(key => input[key]);
284
- }
285
-
286
- return input;
243
+ // https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
244
+ async function delay(ms, { signal }) {
245
+ return new Promise((resolve, reject) => {
246
+ if (signal) {
247
+ signal.throwIfAborted();
248
+ signal.addEventListener('abort', abortHandler, { once: true });
249
+ }
250
+ function abortHandler() {
251
+ clearTimeout(timeoutId);
252
+ reject(signal.reason);
253
+ }
254
+ const timeoutId = setTimeout(() => {
255
+ signal?.removeEventListener('abort', abortHandler);
256
+ resolve();
257
+ }, ms);
258
+ });
287
259
  }
288
260
 
289
- function parseValue(value, options) {
290
- if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {
291
- value = Number(value);
292
- } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
293
- value = value.toLowerCase() === 'true';
294
- }
261
+ const findUnknownOptions = (request, options) => {
262
+ const unknownOptions = {};
263
+ for (const key in options) {
264
+ if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {
265
+ unknownOptions[key] = options[key];
266
+ }
267
+ }
268
+ return unknownOptions;
269
+ };
295
270
 
296
- return value;
271
+ class Ky {
272
+ static create(input, options) {
273
+ const ky = new Ky(input, options);
274
+ const function_ = async () => {
275
+ if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {
276
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
277
+ }
278
+ // Delay the fetch so that body method shortcuts can set the Accept header
279
+ await Promise.resolve();
280
+ let response = await ky._fetch();
281
+ for (const hook of ky._options.hooks.afterResponse) {
282
+ // eslint-disable-next-line no-await-in-loop
283
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
284
+ if (modifiedResponse instanceof globalThis.Response) {
285
+ response = modifiedResponse;
286
+ }
287
+ }
288
+ ky._decorateResponse(response);
289
+ if (!response.ok && ky._options.throwHttpErrors) {
290
+ let error = new HTTPError(response, ky.request, ky._options);
291
+ for (const hook of ky._options.hooks.beforeError) {
292
+ // eslint-disable-next-line no-await-in-loop
293
+ error = await hook(error);
294
+ }
295
+ throw error;
296
+ }
297
+ // If `onDownloadProgress` is passed, it uses the stream API internally
298
+ /* istanbul ignore next */
299
+ if (ky._options.onDownloadProgress) {
300
+ if (typeof ky._options.onDownloadProgress !== 'function') {
301
+ throw new TypeError('The `onDownloadProgress` option must be a function');
302
+ }
303
+ if (!supportsResponseStreams) {
304
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
305
+ }
306
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
307
+ }
308
+ return response;
309
+ };
310
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
311
+ const result = (isRetriableMethod ? ky._retry(function_) : function_());
312
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
313
+ result[type] = async () => {
314
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
315
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
316
+ const awaitedResult = await result;
317
+ const response = awaitedResult.clone();
318
+ if (type === 'json') {
319
+ if (response.status === 204) {
320
+ return '';
321
+ }
322
+ const arrayBuffer = await response.clone().arrayBuffer();
323
+ const responseSize = arrayBuffer.byteLength;
324
+ if (responseSize === 0) {
325
+ return '';
326
+ }
327
+ if (options.parseJson) {
328
+ return options.parseJson(await response.text());
329
+ }
330
+ }
331
+ return response[type]();
332
+ };
333
+ }
334
+ return result;
335
+ }
336
+ // eslint-disable-next-line complexity
337
+ constructor(input, options = {}) {
338
+ Object.defineProperty(this, "request", {
339
+ enumerable: true,
340
+ configurable: true,
341
+ writable: true,
342
+ value: void 0
343
+ });
344
+ Object.defineProperty(this, "abortController", {
345
+ enumerable: true,
346
+ configurable: true,
347
+ writable: true,
348
+ value: void 0
349
+ });
350
+ Object.defineProperty(this, "_retryCount", {
351
+ enumerable: true,
352
+ configurable: true,
353
+ writable: true,
354
+ value: 0
355
+ });
356
+ Object.defineProperty(this, "_input", {
357
+ enumerable: true,
358
+ configurable: true,
359
+ writable: true,
360
+ value: void 0
361
+ });
362
+ Object.defineProperty(this, "_options", {
363
+ enumerable: true,
364
+ configurable: true,
365
+ writable: true,
366
+ value: void 0
367
+ });
368
+ this._input = input;
369
+ const credentials = this._input instanceof Request && 'credentials' in Request.prototype
370
+ ? this._input.credentials
371
+ : undefined;
372
+ this._options = {
373
+ ...(credentials && { credentials }), // For exactOptionalPropertyTypes
374
+ ...options,
375
+ headers: mergeHeaders(this._input.headers, options.headers),
376
+ hooks: deepMerge({
377
+ beforeRequest: [],
378
+ beforeRetry: [],
379
+ beforeError: [],
380
+ afterResponse: [],
381
+ }, options.hooks),
382
+ method: normalizeRequestMethod(options.method ?? this._input.method),
383
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
384
+ prefixUrl: String(options.prefixUrl || ''),
385
+ retry: normalizeRetryOptions(options.retry),
386
+ throwHttpErrors: options.throwHttpErrors !== false,
387
+ timeout: options.timeout ?? 10_000,
388
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
389
+ };
390
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
391
+ throw new TypeError('`input` must be a string, URL, or Request');
392
+ }
393
+ if (this._options.prefixUrl && typeof this._input === 'string') {
394
+ if (this._input.startsWith('/')) {
395
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
396
+ }
397
+ if (!this._options.prefixUrl.endsWith('/')) {
398
+ this._options.prefixUrl += '/';
399
+ }
400
+ this._input = this._options.prefixUrl + this._input;
401
+ }
402
+ if (supportsAbortController) {
403
+ this.abortController = new globalThis.AbortController();
404
+ if (this._options.signal) {
405
+ const originalSignal = this._options.signal;
406
+ this._options.signal.addEventListener('abort', () => {
407
+ this.abortController.abort(originalSignal.reason);
408
+ });
409
+ }
410
+ this._options.signal = this.abortController.signal;
411
+ }
412
+ if (supportsRequestStreams) {
413
+ // @ts-expect-error - Types are outdated.
414
+ this._options.duplex = 'half';
415
+ }
416
+ this.request = new globalThis.Request(this._input, this._options);
417
+ if (this._options.searchParams) {
418
+ // eslint-disable-next-line unicorn/prevent-abbreviations
419
+ const textSearchParams = typeof this._options.searchParams === 'string'
420
+ ? this._options.searchParams.replace(/^\?/, '')
421
+ : new URLSearchParams(this._options.searchParams).toString();
422
+ // eslint-disable-next-line unicorn/prevent-abbreviations
423
+ const searchParams = '?' + textSearchParams;
424
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
425
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
426
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
427
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
428
+ this.request.headers.delete('content-type');
429
+ }
430
+ // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
431
+ this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
432
+ }
433
+ if (this._options.json !== undefined) {
434
+ this._options.body = JSON.stringify(this._options.json);
435
+ this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
436
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
437
+ }
438
+ }
439
+ _calculateRetryDelay(error) {
440
+ this._retryCount++;
441
+ if (this._retryCount <= this._options.retry.limit && !(error instanceof TimeoutError)) {
442
+ if (error instanceof HTTPError) {
443
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
444
+ return 0;
445
+ }
446
+ const retryAfter = error.response.headers.get('Retry-After');
447
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
448
+ let after = Number(retryAfter);
449
+ if (Number.isNaN(after)) {
450
+ after = Date.parse(retryAfter) - Date.now();
451
+ }
452
+ else {
453
+ after *= 1000;
454
+ }
455
+ if (this._options.retry.maxRetryAfter !== undefined && after > this._options.retry.maxRetryAfter) {
456
+ return 0;
457
+ }
458
+ return after;
459
+ }
460
+ if (error.response.status === 413) {
461
+ return 0;
462
+ }
463
+ }
464
+ const retryDelay = this._options.retry.delay(this._retryCount);
465
+ return Math.min(this._options.retry.backoffLimit, retryDelay);
466
+ }
467
+ return 0;
468
+ }
469
+ _decorateResponse(response) {
470
+ if (this._options.parseJson) {
471
+ response.json = async () => this._options.parseJson(await response.text());
472
+ }
473
+ return response;
474
+ }
475
+ async _retry(function_) {
476
+ try {
477
+ return await function_();
478
+ }
479
+ catch (error) {
480
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
481
+ if (ms !== 0 && this._retryCount > 0) {
482
+ await delay(ms, { signal: this._options.signal });
483
+ for (const hook of this._options.hooks.beforeRetry) {
484
+ // eslint-disable-next-line no-await-in-loop
485
+ const hookResult = await hook({
486
+ request: this.request,
487
+ options: this._options,
488
+ error: error,
489
+ retryCount: this._retryCount,
490
+ });
491
+ // If `stop` is returned from the hook, the retry process is stopped
492
+ if (hookResult === stop) {
493
+ return;
494
+ }
495
+ }
496
+ return this._retry(function_);
497
+ }
498
+ throw error;
499
+ }
500
+ }
501
+ async _fetch() {
502
+ for (const hook of this._options.hooks.beforeRequest) {
503
+ // eslint-disable-next-line no-await-in-loop
504
+ const result = await hook(this.request, this._options);
505
+ if (result instanceof Request) {
506
+ this.request = result;
507
+ break;
508
+ }
509
+ if (result instanceof Response) {
510
+ return result;
511
+ }
512
+ }
513
+ const nonRequestOptions = findUnknownOptions(this.request, this._options);
514
+ if (this._options.timeout === false) {
515
+ return this._options.fetch(this.request.clone(), nonRequestOptions);
516
+ }
517
+ return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options);
518
+ }
519
+ /* istanbul ignore next */
520
+ _stream(response, onDownloadProgress) {
521
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
522
+ let transferredBytes = 0;
523
+ if (response.status === 204) {
524
+ if (onDownloadProgress) {
525
+ onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
526
+ }
527
+ return new globalThis.Response(null, {
528
+ status: response.status,
529
+ statusText: response.statusText,
530
+ headers: response.headers,
531
+ });
532
+ }
533
+ return new globalThis.Response(new globalThis.ReadableStream({
534
+ async start(controller) {
535
+ const reader = response.body.getReader();
536
+ if (onDownloadProgress) {
537
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
538
+ }
539
+ async function read() {
540
+ const { done, value } = await reader.read();
541
+ if (done) {
542
+ controller.close();
543
+ return;
544
+ }
545
+ if (onDownloadProgress) {
546
+ transferredBytes += value.byteLength;
547
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
548
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
549
+ }
550
+ controller.enqueue(value);
551
+ await read();
552
+ }
553
+ await read();
554
+ },
555
+ }), {
556
+ status: response.status,
557
+ statusText: response.statusText,
558
+ headers: response.headers,
559
+ });
560
+ }
297
561
  }
298
562
 
299
- function parse(query, options) {
300
- options = {
301
- decode: true,
302
- sort: true,
303
- arrayFormat: 'none',
304
- arrayFormatSeparator: ',',
305
- parseNumbers: false,
306
- parseBooleans: false,
307
- ...options,
308
- };
309
-
310
- validateArrayFormatSeparator(options.arrayFormatSeparator);
311
-
312
- const formatter = parserForArrayFormat(options);
313
-
314
- // Create an object with no prototype
315
- const returnValue = Object.create(null);
316
-
317
- if (typeof query !== 'string') {
318
- return returnValue;
319
- }
320
-
321
- query = query.trim().replace(/^[?#&]/, '');
322
-
323
- if (!query) {
324
- return returnValue;
325
- }
326
-
327
- for (const parameter of query.split('&')) {
328
- if (parameter === '') {
329
- continue;
330
- }
331
-
332
- let [key, value] = splitOnFirst$1(options.decode ? parameter.replace(/\+/g, ' ') : parameter, '=');
333
-
334
- // Missing `=` should be `null`:
335
- // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
336
- value = value === undefined ? null : (['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options));
337
- formatter(decode(key, options), value, returnValue);
338
- }
339
-
340
- for (const [key, value] of Object.entries(returnValue)) {
341
- if (typeof value === 'object' && value !== null) {
342
- for (const [key2, value2] of Object.entries(value)) {
343
- value[key2] = parseValue(value2, options);
344
- }
345
- } else {
346
- returnValue[key] = parseValue(value, options);
347
- }
348
- }
349
-
350
- if (options.sort === false) {
351
- return returnValue;
352
- }
353
-
354
- // TODO: Remove the use of `reduce`.
355
- // eslint-disable-next-line unicorn/no-array-reduce
356
- return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => {
357
- const value = returnValue[key];
358
- if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {
359
- // Sort object keys, not values
360
- result[key] = keysSorter(value);
361
- } else {
362
- result[key] = value;
363
- }
364
-
365
- return result;
366
- }, Object.create(null));
367
- }
563
+ /*! MIT License © Sindre Sorhus */
564
+ const createInstance = (defaults) => {
565
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
566
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
567
+ for (const method of requestMethods) {
568
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
569
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
570
+ }
571
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
572
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
573
+ ky.stop = stop;
574
+ return ky;
575
+ };
576
+ const ky = createInstance();
368
577
 
369
578
  const authorizationEndpoint = 'https://github.com/login/oauth/authorize';
370
- const scope = 'read:user';
579
+ /**
580
+ * `read:user` read user profile data; `user:email` read user email addresses (including private email addresses).
581
+ * Ref: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
582
+ */
583
+ const scope = 'read:user user:email';
371
584
  const accessTokenEndpoint = 'https://github.com/login/oauth/access_token';
372
585
  const userInfoEndpoint = 'https://api.github.com/user';
586
+ // Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
587
+ const userEmailsEndpoint = 'https://api.github.com/user/emails';
373
588
  const defaultMetadata = {
374
589
  id: 'github-universal',
375
590
  target: 'github',
@@ -421,6 +636,16 @@ const githubConfigGuard = z.object({
421
636
  clientSecret: z.string(),
422
637
  scope: z.string().optional(),
423
638
  });
639
+ /**
640
+ * This guard is used to validate the response from the GitHub API when requesting the user's email addresses.
641
+ * Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
642
+ */
643
+ const emailAddressGuard = z.object({
644
+ email: z.string(),
645
+ primary: z.boolean(),
646
+ verified: z.boolean(),
647
+ visibility: z.string().nullable(),
648
+ });
424
649
  const accessTokenResponseGuard = z.object({
425
650
  access_token: z.string(),
426
651
  scope: z.string(),
@@ -472,16 +697,17 @@ const authorizationCallbackHandler = async (parameterObject) => {
472
697
  const getAccessToken = async (config, codeObject) => {
473
698
  const { code } = codeObject;
474
699
  const { clientId: client_id, clientSecret: client_secret } = config;
475
- const httpResponse = await got.post({
476
- url: accessTokenEndpoint,
477
- json: {
700
+ const httpResponse = await ky
701
+ .post(accessTokenEndpoint, {
702
+ body: new URLSearchParams({
478
703
  client_id,
479
704
  client_secret,
480
705
  code,
481
- },
482
- timeout: { request: defaultTimeout },
483
- });
484
- const result = accessTokenResponseGuard.safeParse(parse(httpResponse.body));
706
+ }),
707
+ timeout: defaultTimeout,
708
+ })
709
+ .json();
710
+ const result = accessTokenResponseGuard.safeParse(httpResponse);
485
711
  if (!result.success) {
486
712
  throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
487
713
  }
@@ -494,29 +720,46 @@ const getUserInfo = (getConfig) => async (data) => {
494
720
  const config = await getConfig(defaultMetadata.id);
495
721
  validateConfig(config, githubConfigGuard);
496
722
  const { accessToken } = await getAccessToken(config, { code });
723
+ const authedApi = ky.create({
724
+ timeout: defaultTimeout,
725
+ hooks: {
726
+ beforeRequest: [
727
+ (request) => {
728
+ request.headers.set('Authorization', `Bearer ${accessToken}`);
729
+ },
730
+ ],
731
+ },
732
+ });
497
733
  try {
498
- const httpResponse = await got.get(userInfoEndpoint, {
499
- headers: {
500
- authorization: `token ${accessToken}`,
501
- },
502
- timeout: { request: defaultTimeout },
503
- });
504
- const result = userInfoResponseGuard.safeParse(parseJson(httpResponse.body));
505
- if (!result.success) {
506
- throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
734
+ const [userInfo, userEmails] = await Promise.all([
735
+ authedApi.get(userInfoEndpoint).json(),
736
+ authedApi.get(userEmailsEndpoint).json(),
737
+ ]);
738
+ const userInfoResult = userInfoResponseGuard.safeParse(userInfo);
739
+ const userEmailsResult = emailAddressGuard.array().safeParse(userEmails);
740
+ if (!userInfoResult.success) {
741
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userInfoResult.error);
742
+ }
743
+ if (!userEmailsResult.success) {
744
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, userEmailsResult.error);
507
745
  }
508
- const { id, avatar_url: avatar, email, name } = result.data;
746
+ const { id, avatar_url: avatar, email: publicEmail, name } = userInfoResult.data;
509
747
  return {
510
748
  id: String(id),
511
749
  avatar: conditional(avatar),
512
- email: conditional(email),
750
+ email: conditional(publicEmail ??
751
+ userEmailsResult.data.find(({ verified, primary }) => verified && primary)?.email),
513
752
  name: conditional(name),
753
+ rawData: jsonGuard.parse({
754
+ userInfo,
755
+ userEmails,
756
+ }),
514
757
  };
515
758
  }
516
759
  catch (error) {
517
760
  if (error instanceof HTTPError) {
518
- const { statusCode, body: rawBody } = error.response;
519
- if (statusCode === 401) {
761
+ const { status, body: rawBody } = error.response;
762
+ if (status === 401) {
520
763
  throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);
521
764
  }
522
765
  throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));
package/lib/types.d.ts CHANGED
@@ -13,6 +13,26 @@ export declare const githubConfigGuard: z.ZodObject<{
13
13
  scope?: string | undefined;
14
14
  }>;
15
15
  export type GithubConfig = z.infer<typeof githubConfigGuard>;
16
+ /**
17
+ * This guard is used to validate the response from the GitHub API when requesting the user's email addresses.
18
+ * Ref: https://docs.github.com/en/rest/users/emails?apiVersion=2022-11-28#list-email-addresses-for-the-authenticated-user
19
+ */
20
+ export declare const emailAddressGuard: z.ZodObject<{
21
+ email: z.ZodString;
22
+ primary: z.ZodBoolean;
23
+ verified: z.ZodBoolean;
24
+ visibility: z.ZodNullable<z.ZodString>;
25
+ }, "strip", z.ZodTypeAny, {
26
+ email: string;
27
+ primary: boolean;
28
+ verified: boolean;
29
+ visibility: string | null;
30
+ }, {
31
+ email: string;
32
+ primary: boolean;
33
+ verified: boolean;
34
+ visibility: string | null;
35
+ }>;
16
36
  export declare const accessTokenResponseGuard: z.ZodObject<{
17
37
  access_token: z.ZodString;
18
38
  scope: z.ZodString;
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@logto/connector-github",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "Github web connector implementation.",
5
5
  "author": "Silverhand Inc. <contact@silverhand.io>",
6
6
  "dependencies": {
7
- "@logto/connector-kit": "^2.1.0",
8
- "query-string": "^8.0.0"
7
+ "@logto/connector-kit": "^3.0.0",
8
+ "@silverhand/essentials": "^2.9.0",
9
+ "ky": "^1.2.3",
10
+ "query-string": "^9.0.0",
11
+ "snakecase-keys": "^8.0.0",
12
+ "zod": "^3.22.4"
9
13
  },
10
14
  "main": "./lib/index.js",
11
15
  "module": "./lib/index.js",
@@ -37,6 +41,26 @@
37
41
  "publishConfig": {
38
42
  "access": "public"
39
43
  },
44
+ "devDependencies": {
45
+ "@rollup/plugin-commonjs": "^25.0.7",
46
+ "@rollup/plugin-json": "^6.1.0",
47
+ "@rollup/plugin-node-resolve": "^15.2.3",
48
+ "@rollup/plugin-typescript": "^11.1.6",
49
+ "@silverhand/eslint-config": "6.0.1",
50
+ "@silverhand/ts-config": "6.0.0",
51
+ "@types/node": "^20.11.20",
52
+ "@types/supertest": "^6.0.2",
53
+ "@vitest/coverage-v8": "^1.4.0",
54
+ "eslint": "^8.56.0",
55
+ "lint-staged": "^15.0.2",
56
+ "nock": "14.0.0-beta.6",
57
+ "prettier": "^3.0.0",
58
+ "rollup": "^4.12.0",
59
+ "rollup-plugin-output-size": "^1.3.0",
60
+ "supertest": "^7.0.0",
61
+ "typescript": "^5.3.3",
62
+ "vitest": "^1.4.0"
63
+ },
40
64
  "scripts": {
41
65
  "precommit": "lint-staged",
42
66
  "build:test": "rm -rf lib/ && tsc -p tsconfig.test.json --sourcemap",
@@ -44,8 +68,7 @@
44
68
  "dev": "tsc -p tsconfig.build.json --watch --preserveWatchOutput --incremental",
45
69
  "lint": "eslint --ext .ts src",
46
70
  "lint:report": "pnpm lint --format json --output-file report.json",
47
- "test:only": "NODE_OPTIONS=--experimental-vm-modules jest",
48
- "test": "pnpm build:test && pnpm test:only",
49
- "test:ci": "pnpm test:only --silent --coverage"
71
+ "test": "vitest src",
72
+ "test:ci": "pnpm run test --silent --coverage"
50
73
  }
51
74
  }