@logto/connector-google 1.4.0 → 1.6.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/index.js CHANGED
@@ -1,1399 +1,223 @@
1
- import { got, HTTPError } from 'got';
2
- import { GoogleConnector, ConnectorPlatform, ConnectorConfigFormItemType, OidcPrompt, parseJson, ConnectorError, ConnectorErrorCodes, ConnectorType, validateConfig } from '@logto/connector-kit';
3
- import { z } from 'zod';
4
- import { Buffer } from 'node:buffer';
5
- import * as crypto from 'node:crypto';
6
- import { KeyObject, createPrivateKey, createPublicKey, constants, createSecretKey } from 'node:crypto';
7
- import * as util from 'node:util';
8
- import { promisify } from 'node:util';
9
- import * as http from 'node:http';
10
- import * as https from 'node:https';
11
- import { once } from 'node:events';
12
-
13
- // https://github.com/facebook/jest/issues/7547
14
- const assert = (value, error) => {
15
- if (!value) {
16
- // https://github.com/typescript-eslint/typescript-eslint/issues/3814
17
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
18
- throw error;
19
- }
20
- };
21
-
22
- // eslint-disable-next-line id-length
23
- // eslint-disable-next-line unicorn/prefer-native-coercion-functions
24
- const notFalsy = (value) => Boolean(value);
25
-
26
- /**
27
- * Conditional return the expression result when it's not {@link Falsy};
28
- * otherwise return `undefined`.
29
- *
30
- * @example
31
- * ```ts
32
- * conditional(1 && '2') // '2'
33
- * conditional(false && '1') // undefined
34
- * ```
35
- */
36
- const conditional = (exp) => (notFalsy(exp) ? exp : undefined);
37
-
38
- const encoder = new TextEncoder();
39
- const decoder = new TextDecoder();
40
- function concat(...buffers) {
41
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
42
- const buf = new Uint8Array(size);
43
- let i = 0;
44
- for (const buffer of buffers) {
45
- buf.set(buffer, i);
46
- i += buffer.length;
47
- }
48
- return buf;
49
- }
50
-
51
- function normalize(input) {
52
- let encoded = input;
53
- if (encoded instanceof Uint8Array) {
54
- encoded = decoder.decode(encoded);
55
- }
56
- return encoded;
57
- }
58
- const decode = (input) => new Uint8Array(Buffer.from(normalize(input), 'base64'));
59
-
60
- class JOSEError extends Error {
61
- static get code() {
62
- return 'ERR_JOSE_GENERIC';
63
- }
64
- code = 'ERR_JOSE_GENERIC';
65
- constructor(message) {
66
- super(message);
67
- this.name = this.constructor.name;
68
- Error.captureStackTrace?.(this, this.constructor);
69
- }
70
- }
71
- class JWTClaimValidationFailed extends JOSEError {
72
- static get code() {
73
- return 'ERR_JWT_CLAIM_VALIDATION_FAILED';
74
- }
75
- code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
76
- claim;
77
- reason;
78
- constructor(message, claim = 'unspecified', reason = 'unspecified') {
79
- super(message);
80
- this.claim = claim;
81
- this.reason = reason;
82
- }
83
- }
84
- class JWTExpired extends JOSEError {
85
- static get code() {
86
- return 'ERR_JWT_EXPIRED';
87
- }
88
- code = 'ERR_JWT_EXPIRED';
89
- claim;
90
- reason;
91
- constructor(message, claim = 'unspecified', reason = 'unspecified') {
92
- super(message);
93
- this.claim = claim;
94
- this.reason = reason;
95
- }
96
- }
97
- class JOSEAlgNotAllowed extends JOSEError {
98
- static get code() {
99
- return 'ERR_JOSE_ALG_NOT_ALLOWED';
100
- }
101
- code = 'ERR_JOSE_ALG_NOT_ALLOWED';
102
- }
103
- class JOSENotSupported extends JOSEError {
104
- static get code() {
105
- return 'ERR_JOSE_NOT_SUPPORTED';
106
- }
107
- code = 'ERR_JOSE_NOT_SUPPORTED';
108
- }
109
- class JWSInvalid extends JOSEError {
110
- static get code() {
111
- return 'ERR_JWS_INVALID';
112
- }
113
- code = 'ERR_JWS_INVALID';
114
- }
115
- class JWTInvalid extends JOSEError {
116
- static get code() {
117
- return 'ERR_JWT_INVALID';
118
- }
119
- code = 'ERR_JWT_INVALID';
120
- }
121
- class JWKSInvalid extends JOSEError {
122
- static get code() {
123
- return 'ERR_JWKS_INVALID';
124
- }
125
- code = 'ERR_JWKS_INVALID';
126
- }
127
- class JWKSNoMatchingKey extends JOSEError {
128
- static get code() {
129
- return 'ERR_JWKS_NO_MATCHING_KEY';
130
- }
131
- code = 'ERR_JWKS_NO_MATCHING_KEY';
132
- message = 'no applicable key found in the JSON Web Key Set';
133
- }
134
- class JWKSMultipleMatchingKeys extends JOSEError {
135
- [Symbol.asyncIterator];
136
- static get code() {
137
- return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
138
- }
139
- code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
140
- message = 'multiple matching keys found in the JSON Web Key Set';
141
- }
142
- class JWKSTimeout extends JOSEError {
143
- static get code() {
144
- return 'ERR_JWKS_TIMEOUT';
145
- }
146
- code = 'ERR_JWKS_TIMEOUT';
147
- message = 'request timed out';
148
- }
149
- class JWSSignatureVerificationFailed extends JOSEError {
150
- static get code() {
151
- return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
152
- }
153
- code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
154
- message = 'signature verification failed';
155
- }
156
-
157
- var isKeyObject = (obj) => util.types.isKeyObject(obj);
158
-
159
- const webcrypto = crypto.webcrypto;
160
- const isCryptoKey = (key) => util.types.isCryptoKey(key);
161
-
162
- function unusable(name, prop = 'algorithm.name') {
163
- return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
164
- }
165
- function isAlgorithm(algorithm, name) {
166
- return algorithm.name === name;
167
- }
168
- function getHashLength(hash) {
169
- return parseInt(hash.name.slice(4), 10);
170
- }
171
- function getNamedCurve$1(alg) {
172
- switch (alg) {
173
- case 'ES256':
174
- return 'P-256';
175
- case 'ES384':
176
- return 'P-384';
177
- case 'ES512':
178
- return 'P-521';
179
- default:
180
- throw new Error('unreachable');
181
- }
182
- }
183
- function checkUsage(key, usages) {
184
- if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
185
- let msg = 'CryptoKey does not support this operation, its usages must include ';
186
- if (usages.length > 2) {
187
- const last = usages.pop();
188
- msg += `one of ${usages.join(', ')}, or ${last}.`;
189
- }
190
- else if (usages.length === 2) {
191
- msg += `one of ${usages[0]} or ${usages[1]}.`;
192
- }
193
- else {
194
- msg += `${usages[0]}.`;
195
- }
196
- throw new TypeError(msg);
197
- }
198
- }
199
- function checkSigCryptoKey(key, alg, ...usages) {
200
- switch (alg) {
201
- case 'HS256':
202
- case 'HS384':
203
- case 'HS512': {
204
- if (!isAlgorithm(key.algorithm, 'HMAC'))
205
- throw unusable('HMAC');
206
- const expected = parseInt(alg.slice(2), 10);
207
- const actual = getHashLength(key.algorithm.hash);
208
- if (actual !== expected)
209
- throw unusable(`SHA-${expected}`, 'algorithm.hash');
210
- break;
211
- }
212
- case 'RS256':
213
- case 'RS384':
214
- case 'RS512': {
215
- if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
216
- throw unusable('RSASSA-PKCS1-v1_5');
217
- const expected = parseInt(alg.slice(2), 10);
218
- const actual = getHashLength(key.algorithm.hash);
219
- if (actual !== expected)
220
- throw unusable(`SHA-${expected}`, 'algorithm.hash');
221
- break;
222
- }
223
- case 'PS256':
224
- case 'PS384':
225
- case 'PS512': {
226
- if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
227
- throw unusable('RSA-PSS');
228
- const expected = parseInt(alg.slice(2), 10);
229
- const actual = getHashLength(key.algorithm.hash);
230
- if (actual !== expected)
231
- throw unusable(`SHA-${expected}`, 'algorithm.hash');
232
- break;
233
- }
234
- case 'EdDSA': {
235
- if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
236
- throw unusable('Ed25519 or Ed448');
237
- }
238
- break;
239
- }
240
- case 'ES256':
241
- case 'ES384':
242
- case 'ES512': {
243
- if (!isAlgorithm(key.algorithm, 'ECDSA'))
244
- throw unusable('ECDSA');
245
- const expected = getNamedCurve$1(alg);
246
- const actual = key.algorithm.namedCurve;
247
- if (actual !== expected)
248
- throw unusable(expected, 'algorithm.namedCurve');
249
- break;
250
- }
251
- default:
252
- throw new TypeError('CryptoKey does not support this operation');
253
- }
254
- checkUsage(key, usages);
255
- }
256
-
257
- function message(msg, actual, ...types) {
258
- if (types.length > 2) {
259
- const last = types.pop();
260
- msg += `one of type ${types.join(', ')}, or ${last}.`;
261
- }
262
- else if (types.length === 2) {
263
- msg += `one of type ${types[0]} or ${types[1]}.`;
264
- }
265
- else {
266
- msg += `of type ${types[0]}.`;
267
- }
268
- if (actual == null) {
269
- msg += ` Received ${actual}`;
270
- }
271
- else if (typeof actual === 'function' && actual.name) {
272
- msg += ` Received function ${actual.name}`;
273
- }
274
- else if (typeof actual === 'object' && actual != null) {
275
- if (actual.constructor?.name) {
276
- msg += ` Received an instance of ${actual.constructor.name}`;
277
- }
278
- }
279
- return msg;
280
- }
281
- var invalidKeyInput = (actual, ...types) => {
282
- return message('Key must be ', actual, ...types);
283
- };
284
- function withAlg(alg, actual, ...types) {
285
- return message(`Key for the ${alg} algorithm must be `, actual, ...types);
286
- }
287
-
288
- var isKeyLike = (key) => isKeyObject(key) || isCryptoKey(key);
289
- const types = ['KeyObject'];
290
- if (globalThis.CryptoKey || webcrypto?.CryptoKey) {
291
- types.push('CryptoKey');
292
- }
293
-
294
- const isDisjoint = (...headers) => {
295
- const sources = headers.filter(Boolean);
296
- if (sources.length === 0 || sources.length === 1) {
297
- return true;
298
- }
299
- let acc;
300
- for (const header of sources) {
301
- const parameters = Object.keys(header);
302
- if (!acc || acc.size === 0) {
303
- acc = new Set(parameters);
304
- continue;
305
- }
306
- for (const parameter of parameters) {
307
- if (acc.has(parameter)) {
308
- return false;
309
- }
310
- acc.add(parameter);
311
- }
312
- }
313
- return true;
314
- };
315
-
316
- function isObjectLike(value) {
317
- return typeof value === 'object' && value !== null;
318
- }
319
- function isObject(input) {
320
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
321
- return false;
322
- }
323
- if (Object.getPrototypeOf(input) === null) {
324
- return true;
325
- }
326
- let proto = input;
327
- while (Object.getPrototypeOf(proto) !== null) {
328
- proto = Object.getPrototypeOf(proto);
329
- }
330
- return Object.getPrototypeOf(input) === proto;
331
- }
332
-
333
- const namedCurveToJOSE = (namedCurve) => {
334
- switch (namedCurve) {
335
- case 'prime256v1':
336
- return 'P-256';
337
- case 'secp384r1':
338
- return 'P-384';
339
- case 'secp521r1':
340
- return 'P-521';
341
- case 'secp256k1':
342
- return 'secp256k1';
343
- default:
344
- throw new JOSENotSupported('Unsupported key curve for this operation');
345
- }
346
- };
347
- const getNamedCurve = (kee, raw) => {
348
- let key;
349
- if (isCryptoKey(kee)) {
350
- key = KeyObject.from(kee);
351
- }
352
- else if (isKeyObject(kee)) {
353
- key = kee;
354
- }
355
- else {
356
- throw new TypeError(invalidKeyInput(kee, ...types));
357
- }
358
- if (key.type === 'secret') {
359
- throw new TypeError('only "private" or "public" type keys can be used for this operation');
360
- }
361
- switch (key.asymmetricKeyType) {
362
- case 'ed25519':
363
- case 'ed448':
364
- return `Ed${key.asymmetricKeyType.slice(2)}`;
365
- case 'x25519':
366
- case 'x448':
367
- return `X${key.asymmetricKeyType.slice(1)}`;
368
- case 'ec': {
369
- const namedCurve = key.asymmetricKeyDetails.namedCurve;
370
- if (raw) {
371
- return namedCurve;
372
- }
373
- return namedCurveToJOSE(namedCurve);
374
- }
375
- default:
376
- throw new TypeError('Invalid asymmetric key type for this operation');
377
- }
378
- };
379
-
380
- var checkKeyLength = (key, alg) => {
381
- const { modulusLength } = key.asymmetricKeyDetails;
382
- if (typeof modulusLength !== 'number' || modulusLength < 2048) {
383
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
384
- }
385
- };
386
-
387
- const parse = (jwk) => {
388
- return (jwk.d ? createPrivateKey : createPublicKey)({ format: 'jwk', key: jwk });
389
- };
390
-
391
- async function importJWK(jwk, alg) {
392
- if (!isObject(jwk)) {
393
- throw new TypeError('JWK must be an object');
394
- }
395
- alg ||= jwk.alg;
396
- switch (jwk.kty) {
397
- case 'oct':
398
- if (typeof jwk.k !== 'string' || !jwk.k) {
399
- throw new TypeError('missing "k" (Key Value) Parameter value');
400
- }
401
- return decode(jwk.k);
402
- case 'RSA':
403
- if (jwk.oth !== undefined) {
404
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
405
- }
406
- case 'EC':
407
- case 'OKP':
408
- return parse({ ...jwk, alg });
409
- default:
410
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
411
- }
412
- }
413
-
414
- const symmetricTypeCheck = (alg, key) => {
415
- if (key instanceof Uint8Array)
416
- return;
417
- if (!isKeyLike(key)) {
418
- throw new TypeError(withAlg(alg, key, ...types, 'Uint8Array'));
419
- }
420
- if (key.type !== 'secret') {
421
- throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`);
422
- }
423
- };
424
- const asymmetricTypeCheck = (alg, key, usage) => {
425
- if (!isKeyLike(key)) {
426
- throw new TypeError(withAlg(alg, key, ...types));
427
- }
428
- if (key.type === 'secret') {
429
- throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`);
430
- }
431
- if (usage === 'sign' && key.type === 'public') {
432
- throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`);
433
- }
434
- if (usage === 'decrypt' && key.type === 'public') {
435
- throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`);
436
- }
437
- if (key.algorithm && usage === 'verify' && key.type === 'private') {
438
- throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`);
439
- }
440
- if (key.algorithm && usage === 'encrypt' && key.type === 'private') {
441
- throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`);
442
- }
443
- };
444
- const checkKeyType = (alg, key, usage) => {
445
- const symmetric = alg.startsWith('HS') ||
446
- alg === 'dir' ||
447
- alg.startsWith('PBES2') ||
448
- /^A\d{3}(?:GCM)?KW$/.test(alg);
449
- if (symmetric) {
450
- symmetricTypeCheck(alg, key);
451
- }
452
- else {
453
- asymmetricTypeCheck(alg, key, usage);
454
- }
455
- };
456
-
457
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
458
- if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
459
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
460
- }
461
- if (!protectedHeader || protectedHeader.crit === undefined) {
462
- return new Set();
463
- }
464
- if (!Array.isArray(protectedHeader.crit) ||
465
- protectedHeader.crit.length === 0 ||
466
- protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {
467
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
468
- }
469
- let recognized;
470
- if (recognizedOption !== undefined) {
471
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
472
- }
473
- else {
474
- recognized = recognizedDefault;
475
- }
476
- for (const parameter of protectedHeader.crit) {
477
- if (!recognized.has(parameter)) {
478
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
479
- }
480
- if (joseHeader[parameter] === undefined) {
481
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
482
- }
483
- if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
484
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
485
- }
486
- }
487
- return new Set(protectedHeader.crit);
488
- }
489
-
490
- const validateAlgorithms = (option, algorithms) => {
491
- if (algorithms !== undefined &&
492
- (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {
493
- throw new TypeError(`"${option}" option must be an array of strings`);
494
- }
495
- if (!algorithms) {
496
- return undefined;
497
- }
498
- return new Set(algorithms);
499
- };
500
-
501
- function dsaDigest(alg) {
502
- switch (alg) {
503
- case 'PS256':
504
- case 'RS256':
505
- case 'ES256':
506
- case 'ES256K':
507
- return 'sha256';
508
- case 'PS384':
509
- case 'RS384':
510
- case 'ES384':
511
- return 'sha384';
512
- case 'PS512':
513
- case 'RS512':
514
- case 'ES512':
515
- return 'sha512';
516
- case 'EdDSA':
517
- return undefined;
518
- default:
519
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
520
- }
521
- }
522
-
523
- const PSS = {
524
- padding: constants.RSA_PKCS1_PSS_PADDING,
525
- saltLength: constants.RSA_PSS_SALTLEN_DIGEST,
526
- };
527
- const ecCurveAlgMap = new Map([
528
- ['ES256', 'P-256'],
529
- ['ES256K', 'secp256k1'],
530
- ['ES384', 'P-384'],
531
- ['ES512', 'P-521'],
532
- ]);
533
- function keyForCrypto(alg, key) {
534
- switch (alg) {
535
- case 'EdDSA':
536
- if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType)) {
537
- throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448');
538
- }
539
- return key;
540
- case 'RS256':
541
- case 'RS384':
542
- case 'RS512':
543
- if (key.asymmetricKeyType !== 'rsa') {
544
- throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
545
- }
546
- checkKeyLength(key, alg);
547
- return key;
548
- case 'PS256':
549
- case 'PS384':
550
- case 'PS512':
551
- if (key.asymmetricKeyType === 'rsa-pss') {
552
- const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
553
- const length = parseInt(alg.slice(-3), 10);
554
- if (hashAlgorithm !== undefined &&
555
- (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {
556
- throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`);
557
- }
558
- if (saltLength !== undefined && saltLength > length >> 3) {
559
- throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`);
560
- }
561
- }
562
- else if (key.asymmetricKeyType !== 'rsa') {
563
- throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss');
564
- }
565
- checkKeyLength(key, alg);
566
- return { key, ...PSS };
567
- case 'ES256':
568
- case 'ES256K':
569
- case 'ES384':
570
- case 'ES512': {
571
- if (key.asymmetricKeyType !== 'ec') {
572
- throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec');
573
- }
574
- const actual = getNamedCurve(key);
575
- const expected = ecCurveAlgMap.get(alg);
576
- if (actual !== expected) {
577
- throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);
578
- }
579
- return { dsaEncoding: 'ieee-p1363', key };
580
- }
581
- default:
582
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
583
- }
584
- }
585
-
586
- function hmacDigest(alg) {
587
- switch (alg) {
588
- case 'HS256':
589
- return 'sha256';
590
- case 'HS384':
591
- return 'sha384';
592
- case 'HS512':
593
- return 'sha512';
594
- default:
595
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
596
- }
597
- }
598
-
599
- function getSignVerifyKey(alg, key, usage) {
600
- if (key instanceof Uint8Array) {
601
- if (!alg.startsWith('HS')) {
602
- throw new TypeError(invalidKeyInput(key, ...types));
603
- }
604
- return createSecretKey(key);
605
- }
606
- if (key instanceof KeyObject) {
607
- return key;
608
- }
609
- if (isCryptoKey(key)) {
610
- checkSigCryptoKey(key, alg, usage);
611
- return KeyObject.from(key);
612
- }
613
- throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
614
- }
615
-
616
- const oneShotSign = promisify(crypto.sign);
617
- const sign = async (alg, key, data) => {
618
- const keyObject = getSignVerifyKey(alg, key, 'sign');
619
- if (alg.startsWith('HS')) {
620
- const hmac = crypto.createHmac(hmacDigest(alg), keyObject);
621
- hmac.update(data);
622
- return hmac.digest();
623
- }
624
- return oneShotSign(dsaDigest(alg), data, keyForCrypto(alg, keyObject));
625
- };
626
-
627
- const oneShotVerify = promisify(crypto.verify);
628
- const verify = async (alg, key, signature, data) => {
629
- const keyObject = getSignVerifyKey(alg, key, 'verify');
630
- if (alg.startsWith('HS')) {
631
- const expected = await sign(alg, keyObject, data);
632
- const actual = signature;
633
- try {
634
- return crypto.timingSafeEqual(actual, expected);
635
- }
636
- catch {
637
- return false;
638
- }
639
- }
640
- const algorithm = dsaDigest(alg);
641
- const keyInput = keyForCrypto(alg, keyObject);
642
- try {
643
- return await oneShotVerify(algorithm, data, keyInput, signature);
644
- }
645
- catch {
646
- return false;
647
- }
648
- };
649
-
650
- async function flattenedVerify(jws, key, options) {
651
- if (!isObject(jws)) {
652
- throw new JWSInvalid('Flattened JWS must be an object');
653
- }
654
- if (jws.protected === undefined && jws.header === undefined) {
655
- throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
656
- }
657
- if (jws.protected !== undefined && typeof jws.protected !== 'string') {
658
- throw new JWSInvalid('JWS Protected Header incorrect type');
659
- }
660
- if (jws.payload === undefined) {
661
- throw new JWSInvalid('JWS Payload missing');
662
- }
663
- if (typeof jws.signature !== 'string') {
664
- throw new JWSInvalid('JWS Signature missing or incorrect type');
665
- }
666
- if (jws.header !== undefined && !isObject(jws.header)) {
667
- throw new JWSInvalid('JWS Unprotected Header incorrect type');
668
- }
669
- let parsedProt = {};
670
- if (jws.protected) {
671
- try {
672
- const protectedHeader = decode(jws.protected);
673
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
674
- }
675
- catch {
676
- throw new JWSInvalid('JWS Protected Header is invalid');
677
- }
678
- }
679
- if (!isDisjoint(parsedProt, jws.header)) {
680
- throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
681
- }
682
- const joseHeader = {
683
- ...parsedProt,
684
- ...jws.header,
685
- };
686
- const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
687
- let b64 = true;
688
- if (extensions.has('b64')) {
689
- b64 = parsedProt.b64;
690
- if (typeof b64 !== 'boolean') {
691
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
692
- }
693
- }
694
- const { alg } = joseHeader;
695
- if (typeof alg !== 'string' || !alg) {
696
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
697
- }
698
- const algorithms = options && validateAlgorithms('algorithms', options.algorithms);
699
- if (algorithms && !algorithms.has(alg)) {
700
- throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
701
- }
702
- if (b64) {
703
- if (typeof jws.payload !== 'string') {
704
- throw new JWSInvalid('JWS Payload must be a string');
705
- }
706
- }
707
- else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
708
- throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
709
- }
710
- let resolvedKey = false;
711
- if (typeof key === 'function') {
712
- key = await key(parsedProt, jws);
713
- resolvedKey = true;
714
- }
715
- checkKeyType(alg, key, 'verify');
716
- const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
717
- let signature;
718
- try {
719
- signature = decode(jws.signature);
720
- }
721
- catch {
722
- throw new JWSInvalid('Failed to base64url decode the signature');
723
- }
724
- const verified = await verify(alg, key, signature, data);
725
- if (!verified) {
726
- throw new JWSSignatureVerificationFailed();
727
- }
728
- let payload;
729
- if (b64) {
730
- try {
731
- payload = decode(jws.payload);
732
- }
733
- catch {
734
- throw new JWSInvalid('Failed to base64url decode the payload');
735
- }
736
- }
737
- else if (typeof jws.payload === 'string') {
738
- payload = encoder.encode(jws.payload);
739
- }
740
- else {
741
- payload = jws.payload;
742
- }
743
- const result = { payload };
744
- if (jws.protected !== undefined) {
745
- result.protectedHeader = parsedProt;
746
- }
747
- if (jws.header !== undefined) {
748
- result.unprotectedHeader = jws.header;
749
- }
750
- if (resolvedKey) {
751
- return { ...result, key };
752
- }
753
- return result;
754
- }
755
-
756
- async function compactVerify(jws, key, options) {
757
- if (jws instanceof Uint8Array) {
758
- jws = decoder.decode(jws);
759
- }
760
- if (typeof jws !== 'string') {
761
- throw new JWSInvalid('Compact JWS must be a string or Uint8Array');
762
- }
763
- const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
764
- if (length !== 3) {
765
- throw new JWSInvalid('Invalid Compact JWS');
766
- }
767
- const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
768
- const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
769
- if (typeof key === 'function') {
770
- return { ...result, key: verified.key };
771
- }
772
- return result;
773
- }
774
-
775
- var epoch = (date) => Math.floor(date.getTime() / 1000);
776
-
777
- const minute = 60;
778
- const hour = minute * 60;
779
- const day = hour * 24;
780
- const week = day * 7;
781
- const year = day * 365.25;
782
- const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
783
- var secs = (str) => {
784
- const matched = REGEX.exec(str);
785
- if (!matched || (matched[4] && matched[1])) {
786
- throw new TypeError('Invalid time period format');
787
- }
788
- const value = parseFloat(matched[2]);
789
- const unit = matched[3].toLowerCase();
790
- let numericDate;
791
- switch (unit) {
792
- case 'sec':
793
- case 'secs':
794
- case 'second':
795
- case 'seconds':
796
- case 's':
797
- numericDate = Math.round(value);
798
- break;
799
- case 'minute':
800
- case 'minutes':
801
- case 'min':
802
- case 'mins':
803
- case 'm':
804
- numericDate = Math.round(value * minute);
805
- break;
806
- case 'hour':
807
- case 'hours':
808
- case 'hr':
809
- case 'hrs':
810
- case 'h':
811
- numericDate = Math.round(value * hour);
812
- break;
813
- case 'day':
814
- case 'days':
815
- case 'd':
816
- numericDate = Math.round(value * day);
817
- break;
818
- case 'week':
819
- case 'weeks':
820
- case 'w':
821
- numericDate = Math.round(value * week);
822
- break;
823
- default:
824
- numericDate = Math.round(value * year);
825
- break;
826
- }
827
- if (matched[1] === '-' || matched[4] === 'ago') {
828
- return -numericDate;
829
- }
830
- return numericDate;
831
- };
832
-
833
- const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '');
834
- const checkAudiencePresence = (audPayload, audOption) => {
835
- if (typeof audPayload === 'string') {
836
- return audOption.includes(audPayload);
837
- }
838
- if (Array.isArray(audPayload)) {
839
- return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
840
- }
841
- return false;
842
- };
843
- var jwtPayload = (protectedHeader, encodedPayload, options = {}) => {
844
- const { typ } = options;
845
- if (typ &&
846
- (typeof protectedHeader.typ !== 'string' ||
847
- normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
848
- throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed');
849
- }
850
- let payload;
851
- try {
852
- payload = JSON.parse(decoder.decode(encodedPayload));
853
- }
854
- catch {
855
- }
856
- if (!isObject(payload)) {
857
- throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');
858
- }
859
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
860
- const presenceCheck = [...requiredClaims];
861
- if (maxTokenAge !== undefined)
862
- presenceCheck.push('iat');
863
- if (audience !== undefined)
864
- presenceCheck.push('aud');
865
- if (subject !== undefined)
866
- presenceCheck.push('sub');
867
- if (issuer !== undefined)
868
- presenceCheck.push('iss');
869
- for (const claim of new Set(presenceCheck.reverse())) {
870
- if (!(claim in payload)) {
871
- throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, 'missing');
872
- }
873
- }
874
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
875
- throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed');
876
- }
877
- if (subject && payload.sub !== subject) {
878
- throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed');
879
- }
880
- if (audience &&
881
- !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
882
- throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed');
883
- }
884
- let tolerance;
885
- switch (typeof options.clockTolerance) {
886
- case 'string':
887
- tolerance = secs(options.clockTolerance);
888
- break;
889
- case 'number':
890
- tolerance = options.clockTolerance;
891
- break;
892
- case 'undefined':
893
- tolerance = 0;
894
- break;
895
- default:
896
- throw new TypeError('Invalid clockTolerance option type');
897
- }
898
- const { currentDate } = options;
899
- const now = epoch(currentDate || new Date());
900
- if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
901
- throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid');
902
- }
903
- if (payload.nbf !== undefined) {
904
- if (typeof payload.nbf !== 'number') {
905
- throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid');
906
- }
907
- if (payload.nbf > now + tolerance) {
908
- throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed');
909
- }
910
- }
911
- if (payload.exp !== undefined) {
912
- if (typeof payload.exp !== 'number') {
913
- throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid');
914
- }
915
- if (payload.exp <= now - tolerance) {
916
- throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed');
917
- }
918
- }
919
- if (maxTokenAge) {
920
- const age = now - payload.iat;
921
- const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);
922
- if (age - tolerance > max) {
923
- throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed');
924
- }
925
- if (age < 0 - tolerance) {
926
- throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed');
927
- }
928
- }
929
- return payload;
930
- };
931
-
932
- async function jwtVerify(jwt, key, options) {
933
- const verified = await compactVerify(jwt, key, options);
934
- if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
935
- throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
936
- }
937
- const payload = jwtPayload(verified.protectedHeader, verified.payload, options);
938
- const result = { payload, protectedHeader: verified.protectedHeader };
939
- if (typeof key === 'function') {
940
- return { ...result, key: verified.key };
941
- }
942
- return result;
943
- }
944
-
945
- function getKtyFromAlg(alg) {
946
- switch (typeof alg === 'string' && alg.slice(0, 2)) {
947
- case 'RS':
948
- case 'PS':
949
- return 'RSA';
950
- case 'ES':
951
- return 'EC';
952
- case 'Ed':
953
- return 'OKP';
954
- default:
955
- throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
956
- }
957
- }
958
- function isJWKSLike(jwks) {
959
- return (jwks &&
960
- typeof jwks === 'object' &&
961
- Array.isArray(jwks.keys) &&
962
- jwks.keys.every(isJWKLike));
963
- }
964
- function isJWKLike(key) {
965
- return isObject(key);
966
- }
967
- function clone(obj) {
968
- if (typeof structuredClone === 'function') {
969
- return structuredClone(obj);
970
- }
971
- return JSON.parse(JSON.stringify(obj));
972
- }
973
- class LocalJWKSet {
974
- _jwks;
975
- _cached = new WeakMap();
976
- constructor(jwks) {
977
- if (!isJWKSLike(jwks)) {
978
- throw new JWKSInvalid('JSON Web Key Set malformed');
979
- }
980
- this._jwks = clone(jwks);
981
- }
982
- async getKey(protectedHeader, token) {
983
- const { alg, kid } = { ...protectedHeader, ...token?.header };
984
- const kty = getKtyFromAlg(alg);
985
- const candidates = this._jwks.keys.filter((jwk) => {
986
- let candidate = kty === jwk.kty;
987
- if (candidate && typeof kid === 'string') {
988
- candidate = kid === jwk.kid;
989
- }
990
- if (candidate && typeof jwk.alg === 'string') {
991
- candidate = alg === jwk.alg;
992
- }
993
- if (candidate && typeof jwk.use === 'string') {
994
- candidate = jwk.use === 'sig';
995
- }
996
- if (candidate && Array.isArray(jwk.key_ops)) {
997
- candidate = jwk.key_ops.includes('verify');
998
- }
999
- if (candidate && alg === 'EdDSA') {
1000
- candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';
1001
- }
1002
- if (candidate) {
1003
- switch (alg) {
1004
- case 'ES256':
1005
- candidate = jwk.crv === 'P-256';
1006
- break;
1007
- case 'ES256K':
1008
- candidate = jwk.crv === 'secp256k1';
1009
- break;
1010
- case 'ES384':
1011
- candidate = jwk.crv === 'P-384';
1012
- break;
1013
- case 'ES512':
1014
- candidate = jwk.crv === 'P-521';
1015
- break;
1016
- }
1017
- }
1018
- return candidate;
1019
- });
1020
- const { 0: jwk, length } = candidates;
1021
- if (length === 0) {
1022
- throw new JWKSNoMatchingKey();
1023
- }
1024
- if (length !== 1) {
1025
- const error = new JWKSMultipleMatchingKeys();
1026
- const { _cached } = this;
1027
- error[Symbol.asyncIterator] = async function* () {
1028
- for (const jwk of candidates) {
1029
- try {
1030
- yield await importWithAlgCache(_cached, jwk, alg);
1031
- }
1032
- catch { }
1033
- }
1034
- };
1035
- throw error;
1036
- }
1037
- return importWithAlgCache(this._cached, jwk, alg);
1038
- }
1039
- }
1040
- async function importWithAlgCache(cache, jwk, alg) {
1041
- const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
1042
- if (cached[alg] === undefined) {
1043
- const key = await importJWK({ ...jwk, ext: true }, alg);
1044
- if (key instanceof Uint8Array || key.type !== 'public') {
1045
- throw new JWKSInvalid('JSON Web Key Set members must be public keys');
1046
- }
1047
- cached[alg] = key;
1048
- }
1049
- return cached[alg];
1050
- }
1051
- function createLocalJWKSet(jwks) {
1052
- const set = new LocalJWKSet(jwks);
1053
- return async (protectedHeader, token) => set.getKey(protectedHeader, token);
1054
- }
1055
-
1056
- const fetchJwks = async (url, timeout, options) => {
1057
- let get;
1058
- switch (url.protocol) {
1059
- case 'https:':
1060
- get = https.get;
1061
- break;
1062
- case 'http:':
1063
- get = http.get;
1064
- break;
1065
- default:
1066
- throw new TypeError('Unsupported URL protocol.');
1067
- }
1068
- const { agent, headers } = options;
1069
- const req = get(url.href, {
1070
- agent,
1071
- timeout,
1072
- headers,
1073
- });
1074
- const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')]));
1075
- if (!response) {
1076
- req.destroy();
1077
- throw new JWKSTimeout();
1078
- }
1079
- if (response.statusCode !== 200) {
1080
- throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
1081
- }
1082
- const parts = [];
1083
- for await (const part of response) {
1084
- parts.push(part);
1085
- }
1086
- try {
1087
- return JSON.parse(decoder.decode(concat(...parts)));
1088
- }
1089
- catch {
1090
- throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
1091
- }
1092
- };
1093
-
1094
- function isCloudflareWorkers() {
1095
- return (typeof WebSocketPair !== 'undefined' ||
1096
- (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
1097
- (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
1098
- }
1099
- let USER_AGENT;
1100
- if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
1101
- const NAME = 'jose';
1102
- const VERSION = 'v5.2.4';
1103
- USER_AGENT = `${NAME}/${VERSION}`;
1104
- }
1105
- class RemoteJWKSet {
1106
- _url;
1107
- _timeoutDuration;
1108
- _cooldownDuration;
1109
- _cacheMaxAge;
1110
- _jwksTimestamp;
1111
- _pendingFetch;
1112
- _options;
1113
- _local;
1114
- constructor(url, options) {
1115
- if (!(url instanceof URL)) {
1116
- throw new TypeError('url must be an instance of URL');
1117
- }
1118
- this._url = new URL(url.href);
1119
- this._options = { agent: options?.agent, headers: options?.headers };
1120
- this._timeoutDuration =
1121
- typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
1122
- this._cooldownDuration =
1123
- typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
1124
- this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
1125
- }
1126
- coolingDown() {
1127
- return typeof this._jwksTimestamp === 'number'
1128
- ? Date.now() < this._jwksTimestamp + this._cooldownDuration
1129
- : false;
1130
- }
1131
- fresh() {
1132
- return typeof this._jwksTimestamp === 'number'
1133
- ? Date.now() < this._jwksTimestamp + this._cacheMaxAge
1134
- : false;
1135
- }
1136
- async getKey(protectedHeader, token) {
1137
- if (!this._local || !this.fresh()) {
1138
- await this.reload();
1139
- }
1140
- try {
1141
- return await this._local(protectedHeader, token);
1142
- }
1143
- catch (err) {
1144
- if (err instanceof JWKSNoMatchingKey) {
1145
- if (this.coolingDown() === false) {
1146
- await this.reload();
1147
- return this._local(protectedHeader, token);
1148
- }
1149
- }
1150
- throw err;
1151
- }
1152
- }
1153
- async reload() {
1154
- if (this._pendingFetch && isCloudflareWorkers()) {
1155
- this._pendingFetch = undefined;
1156
- }
1157
- const headers = new Headers(this._options.headers);
1158
- if (USER_AGENT && !headers.has('User-Agent')) {
1159
- headers.set('User-Agent', USER_AGENT);
1160
- this._options.headers = Object.fromEntries(headers.entries());
1161
- }
1162
- this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)
1163
- .then((json) => {
1164
- this._local = createLocalJWKSet(json);
1165
- this._jwksTimestamp = Date.now();
1166
- this._pendingFetch = undefined;
1167
- })
1168
- .catch((err) => {
1169
- this._pendingFetch = undefined;
1170
- throw err;
1171
- });
1172
- await this._pendingFetch;
1173
- }
1174
- }
1175
- function createRemoteJWKSet(url, options) {
1176
- const set = new RemoteJWKSet(url, options);
1177
- return async (protectedHeader, token) => set.getKey(protectedHeader, token);
1178
- }
1179
-
1180
- const authorizationEndpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
1181
- const accessTokenEndpoint = 'https://oauth2.googleapis.com/token';
1182
- const userInfoEndpoint = 'https://openidconnect.googleapis.com/v1/userinfo';
1183
- const scope = 'openid profile email';
1184
- // Instead of defining the metadata in the connector, we reuse the metadata from the connector-kit.
1185
- // This is not the normal practice, but Google One Tap is a special case.
1186
- // @see {@link GoogleConnector} for more information.
1187
- const defaultMetadata = {
1188
- id: GoogleConnector.factoryId,
1189
- target: GoogleConnector.target,
1190
- platform: ConnectorPlatform.Universal,
1191
- name: {
1192
- en: 'Google',
1193
- 'zh-CN': 'Google',
1194
- 'tr-TR': 'Google',
1195
- ko: 'Google',
1
+ // src/index.ts
2
+ import { conditional, assert } from "@silverhand/essentials";
3
+ import { got, HTTPError } from "got";
4
+ import {
5
+ ConnectorError,
6
+ ConnectorErrorCodes,
7
+ validateConfig,
8
+ ConnectorType,
9
+ parseJson,
10
+ GoogleConnector as GoogleConnector3
11
+ } from "@logto/connector-kit";
12
+ import { createRemoteJWKSet, jwtVerify } from "jose";
13
+
14
+ // src/constant.ts
15
+ import {
16
+ ConnectorConfigFormItemType,
17
+ ConnectorPlatform,
18
+ GoogleConnector,
19
+ OidcPrompt
20
+ } from "@logto/connector-kit";
21
+ var authorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth";
22
+ var accessTokenEndpoint = "https://oauth2.googleapis.com/token";
23
+ var userInfoEndpoint = "https://openidconnect.googleapis.com/v1/userinfo";
24
+ var scope = "openid profile email";
25
+ var defaultMetadata = {
26
+ id: GoogleConnector.factoryId,
27
+ target: GoogleConnector.target,
28
+ platform: ConnectorPlatform.Universal,
29
+ name: {
30
+ en: "Google",
31
+ "zh-CN": "Google",
32
+ "tr-TR": "Google",
33
+ ko: "Google"
34
+ },
35
+ logo: "./logo.svg",
36
+ logoDark: null,
37
+ description: {
38
+ en: "Google is a principal search engine technology and email service provider.",
39
+ "zh-CN": "Google \u662F\u5168\u7403\u6027\u7684\u641C\u7D22\u5F15\u64CE\u548C\u90AE\u4EF6\u670D\u52A1\u63D0\u4F9B\u5546\u3002",
40
+ "tr-TR": "Google, en b\xFCy\xFCk arama motoru teknolojisi ve e-posta servis sa\u011Flay\u0131c\u0131s\u0131d\u0131r.",
41
+ ko: "Google\uC740 \uAC00\uC7A5 \uD070 \uAC80\uC0C9 \uC5D4\uC9C4 \uAE30\uC220\uACFC \uC774\uBA54\uC77C \uC11C\uBE44\uC2A4 \uC81C\uACF5\uC790\uC785\uB2C8\uB2E4."
42
+ },
43
+ readme: "./README.md",
44
+ formItems: [
45
+ {
46
+ key: "clientId",
47
+ type: ConnectorConfigFormItemType.Text,
48
+ label: "Client ID",
49
+ required: true,
50
+ placeholder: "<client-id>"
1196
51
  },
1197
- logo: './logo.svg',
1198
- logoDark: null,
1199
- description: {
1200
- en: 'Google is a principal search engine technology and email service provider.',
1201
- 'zh-CN': 'Google 是全球性的搜索引擎和邮件服务提供商。',
1202
- 'tr-TR': 'Google, en büyük arama motoru teknolojisi ve e-posta servis sağlayıcısıdır.',
1203
- ko: 'Google은 가장 큰 검색 엔진 기술과 이메일 서비스 제공자입니다.',
52
+ {
53
+ key: "clientSecret",
54
+ type: ConnectorConfigFormItemType.Text,
55
+ label: "Client Secret",
56
+ required: true,
57
+ placeholder: "<client-secret>"
1204
58
  },
1205
- readme: './README.md',
1206
- formItems: [
1207
- {
1208
- key: 'clientId',
1209
- type: ConnectorConfigFormItemType.Text,
1210
- label: 'Client ID',
1211
- required: true,
1212
- placeholder: '<client-id>',
1213
- },
1214
- {
1215
- key: 'clientSecret',
1216
- type: ConnectorConfigFormItemType.Text,
1217
- label: 'Client Secret',
1218
- required: true,
1219
- placeholder: '<client-secret>',
1220
- },
1221
- {
1222
- key: 'scope',
1223
- type: ConnectorConfigFormItemType.Text,
1224
- label: 'Scope',
1225
- required: false,
1226
- placeholder: '<scope>',
1227
- description: "The `scope` determines permissions granted by the user's authorization. If you are not sure what to enter, do not worry, just leave it blank.",
1228
- },
1229
- {
1230
- key: 'prompts',
1231
- type: ConnectorConfigFormItemType.MultiSelect,
1232
- required: false,
1233
- label: 'Prompts',
1234
- // Google does not support `login` prompt.
1235
- // Ref: https://developers.google.com/identity/openid-connect/openid-connect#authenticationuriparameters
1236
- selectItems: Object.values(OidcPrompt)
1237
- .filter((prompt) => prompt !== OidcPrompt.Login)
1238
- .map((prompt) => ({
1239
- value: prompt,
1240
- })),
1241
- },
1242
- ],
1243
- };
1244
- const defaultTimeout = 5000;
1245
- // https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
1246
- const jwksUri = 'https://www.googleapis.com/oauth2/v3/certs';
1247
-
1248
- const accessTokenResponseGuard = z.object({
1249
- access_token: z.string(),
1250
- scope: z.string(),
1251
- token_type: z.string(),
59
+ {
60
+ key: "scope",
61
+ type: ConnectorConfigFormItemType.Text,
62
+ label: "Scope",
63
+ required: false,
64
+ placeholder: "<scope>",
65
+ description: "The `scope` determines permissions granted by the user's authorization. If you are not sure what to enter, do not worry, just leave it blank."
66
+ },
67
+ {
68
+ key: "prompts",
69
+ type: ConnectorConfigFormItemType.MultiSelect,
70
+ required: false,
71
+ label: "Prompts",
72
+ // Google does not support `login` prompt.
73
+ // Ref: https://developers.google.com/identity/openid-connect/openid-connect#authenticationuriparameters
74
+ selectItems: Object.values(OidcPrompt).filter((prompt) => prompt !== OidcPrompt.Login).map((prompt) => ({
75
+ value: prompt
76
+ })),
77
+ defaultValue: [OidcPrompt.SelectAccount]
78
+ }
79
+ ]
80
+ };
81
+ var defaultTimeout = 5e3;
82
+ var jwksUri = "https://www.googleapis.com/oauth2/v3/certs";
83
+
84
+ // src/types.ts
85
+ import { z } from "zod";
86
+ import { GoogleConnector as GoogleConnector2 } from "@logto/connector-kit";
87
+ var accessTokenResponseGuard = z.object({
88
+ access_token: z.string(),
89
+ scope: z.string(),
90
+ token_type: z.string()
1252
91
  });
1253
- const userInfoResponseGuard = z.object({
1254
- sub: z.string(),
1255
- name: z.string().optional(),
1256
- given_name: z.string().optional(),
1257
- family_name: z.string().optional(),
1258
- picture: z.string().optional(),
1259
- email: z.string().optional(),
1260
- email_verified: z.boolean().optional(),
1261
- locale: z.string().optional(),
92
+ var userInfoResponseGuard = z.object({
93
+ sub: z.string(),
94
+ name: z.string().optional(),
95
+ given_name: z.string().optional(),
96
+ family_name: z.string().optional(),
97
+ picture: z.string().optional(),
98
+ email: z.string().optional(),
99
+ email_verified: z.boolean().optional(),
100
+ locale: z.string().optional()
1262
101
  });
1263
- const authResponseGuard = z.object({
1264
- code: z.string(),
1265
- redirectUri: z.string(),
102
+ var authResponseGuard = z.object({
103
+ code: z.string(),
104
+ redirectUri: z.string()
1266
105
  });
1267
- /**
1268
- * Response payload from Google One Tap. Note the CSRF token is not included since it should be
1269
- * verified by the web server.
1270
- */
1271
- const googleOneTapDataGuard = z.object({
1272
- [GoogleConnector.oneTapParams.credential]: z.string(),
106
+ var googleOneTapDataGuard = z.object({
107
+ [GoogleConnector2.oneTapParams.credential]: z.string()
1273
108
  });
1274
109
 
1275
- /**
1276
- * The Implementation of OpenID Connect of Google Identity Platform.
1277
- * https://developers.google.com/identity/protocols/oauth2/openid-connect
1278
- */
1279
- const getAuthorizationUri = (getConfig) => async ({ state, redirectUri }) => {
1280
- const config = await getConfig(defaultMetadata.id);
1281
- validateConfig(config, GoogleConnector.configGuard);
1282
- const { clientId, scope: scope$1, prompts } = config;
1283
- const queryParameters = new URLSearchParams({
1284
- client_id: clientId,
1285
- redirect_uri: redirectUri,
1286
- response_type: 'code',
1287
- state,
1288
- scope: scope$1 ?? scope,
1289
- ...conditional(prompts && prompts.length > 0 && { prompt: prompts.join(' ') }),
1290
- });
1291
- return `${authorizationEndpoint}?${queryParameters.toString()}`;
1292
- };
1293
- const getAccessToken = async (config, codeObject) => {
1294
- const { code, redirectUri } = codeObject;
1295
- const { clientId, clientSecret } = config;
1296
- // Note:Need to decodeURIComponent on code
1297
- // https://stackoverflow.com/questions/51058256/google-api-node-js-invalid-grant-malformed-auth-code
1298
- const httpResponse = await got.post(accessTokenEndpoint, {
1299
- form: {
1300
- code: decodeURIComponent(code),
1301
- client_id: clientId,
1302
- client_secret: clientSecret,
1303
- redirect_uri: redirectUri,
1304
- grant_type: 'authorization_code',
1305
- },
1306
- timeout: { request: defaultTimeout },
1307
- });
1308
- const result = accessTokenResponseGuard.safeParse(parseJson(httpResponse.body));
1309
- if (!result.success) {
1310
- throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
1311
- }
1312
- const { access_token: accessToken } = result.data;
1313
- assert(accessToken, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));
1314
- return { accessToken };
1315
- };
1316
- /**
1317
- * Get user information JSON from Google Identity Platform. It will use the following order to
1318
- * retrieve user information:
1319
- *
1320
- * 1. Google One Tap: https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
1321
- * 2. Normal Google OAuth: https://developers.google.com/identity/protocols/oauth2/openid-connect
1322
- *
1323
- * @param data The data from the client.
1324
- * @param config The configuration of the connector.
1325
- * @returns A Promise that resolves to the user information JSON.
1326
- */
1327
- const getUserInfoJson = async (data, config) => {
1328
- // Google One Tap
1329
- const oneTapResult = googleOneTapDataGuard.safeParse(data);
1330
- if (oneTapResult.success) {
1331
- const { payload } = await jwtVerify(oneTapResult.data.credential, createRemoteJWKSet(new URL(jwksUri)), {
1332
- // https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
1333
- issuer: ['https://accounts.google.com', 'accounts.google.com'],
1334
- audience: config.clientId,
1335
- clockTolerance: 10,
1336
- });
1337
- return payload;
1338
- }
1339
- // Normal Google OAuth
1340
- const { code, redirectUri } = await authorizationCallbackHandler(data);
1341
- const { accessToken } = await getAccessToken(config, { code, redirectUri });
1342
- const httpResponse = await got.post(userInfoEndpoint, {
1343
- headers: {
1344
- authorization: `Bearer ${accessToken}`,
1345
- },
1346
- timeout: { request: defaultTimeout },
1347
- });
1348
- return parseJson(httpResponse.body);
1349
- };
1350
- const getUserInfo = (getConfig) => async (data) => {
1351
- const config = await getConfig(defaultMetadata.id);
1352
- validateConfig(config, GoogleConnector.configGuard);
1353
- try {
1354
- const rawData = await getUserInfoJson(data, config);
1355
- const result = userInfoResponseGuard.safeParse(rawData);
1356
- if (!result.success) {
1357
- throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
1358
- }
1359
- const { sub: id, picture: avatar, email, email_verified, name } = result.data;
1360
- return {
1361
- id,
1362
- avatar,
1363
- email: conditional(email_verified && email),
1364
- name,
1365
- rawData,
1366
- };
1367
- }
1368
- catch (error) {
1369
- return getUserInfoErrorHandler(error);
1370
- }
1371
- };
1372
- const authorizationCallbackHandler = async (parameterObject) => {
1373
- const result = authResponseGuard.safeParse(parameterObject);
110
+ // src/index.ts
111
+ var getAuthorizationUri = (getConfig) => async ({ state, redirectUri }) => {
112
+ const config = await getConfig(defaultMetadata.id);
113
+ validateConfig(config, GoogleConnector3.configGuard);
114
+ const { clientId, scope: scope2, prompts } = config;
115
+ const queryParameters = new URLSearchParams({
116
+ client_id: clientId,
117
+ redirect_uri: redirectUri,
118
+ response_type: "code",
119
+ state,
120
+ scope: scope2 ?? scope,
121
+ ...conditional(prompts && prompts.length > 0 && { prompt: prompts.join(" ") })
122
+ });
123
+ return `${authorizationEndpoint}?${queryParameters.toString()}`;
124
+ };
125
+ var getAccessToken = async (config, codeObject) => {
126
+ const { code, redirectUri } = codeObject;
127
+ const { clientId, clientSecret } = config;
128
+ const httpResponse = await got.post(accessTokenEndpoint, {
129
+ form: {
130
+ code: decodeURIComponent(code),
131
+ client_id: clientId,
132
+ client_secret: clientSecret,
133
+ redirect_uri: redirectUri,
134
+ grant_type: "authorization_code"
135
+ },
136
+ timeout: { request: defaultTimeout }
137
+ });
138
+ const result = accessTokenResponseGuard.safeParse(parseJson(httpResponse.body));
139
+ if (!result.success) {
140
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
141
+ }
142
+ const { access_token: accessToken } = result.data;
143
+ assert(accessToken, new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid));
144
+ return { accessToken };
145
+ };
146
+ var getUserInfoJson = async (data, config) => {
147
+ const oneTapResult = googleOneTapDataGuard.safeParse(data);
148
+ if (oneTapResult.success) {
149
+ const { payload } = await jwtVerify(
150
+ oneTapResult.data.credential,
151
+ createRemoteJWKSet(new URL(jwksUri)),
152
+ {
153
+ // https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
154
+ issuer: ["https://accounts.google.com", "accounts.google.com"],
155
+ audience: config.clientId,
156
+ clockTolerance: 10
157
+ }
158
+ );
159
+ return payload;
160
+ }
161
+ const { code, redirectUri } = await authorizationCallbackHandler(data);
162
+ const { accessToken } = await getAccessToken(config, { code, redirectUri });
163
+ const httpResponse = await got.post(userInfoEndpoint, {
164
+ headers: {
165
+ authorization: `Bearer ${accessToken}`
166
+ },
167
+ timeout: { request: defaultTimeout }
168
+ });
169
+ return parseJson(httpResponse.body);
170
+ };
171
+ var getUserInfo = (getConfig) => async (data) => {
172
+ const config = await getConfig(defaultMetadata.id);
173
+ validateConfig(config, GoogleConnector3.configGuard);
174
+ try {
175
+ const rawData = await getUserInfoJson(data, config);
176
+ const result = userInfoResponseGuard.safeParse(rawData);
1374
177
  if (!result.success) {
1375
- throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(parameterObject));
1376
- }
1377
- return result.data;
1378
- };
1379
- const getUserInfoErrorHandler = (error) => {
1380
- if (error instanceof HTTPError) {
1381
- const { statusCode, body: rawBody } = error.response;
1382
- if (statusCode === 401) {
1383
- throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);
1384
- }
1385
- throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));
178
+ throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error);
1386
179
  }
1387
- throw error;
1388
- };
1389
- const createGoogleConnector = async ({ getConfig }) => {
180
+ const { sub: id, picture: avatar, email, email_verified, name } = result.data;
1390
181
  return {
1391
- metadata: defaultMetadata,
1392
- type: ConnectorType.Social,
1393
- configGuard: GoogleConnector.configGuard,
1394
- getAuthorizationUri: getAuthorizationUri(getConfig),
1395
- getUserInfo: getUserInfo(getConfig),
182
+ id,
183
+ avatar,
184
+ email: conditional(email_verified && email),
185
+ name,
186
+ rawData
1396
187
  };
1397
- };
1398
-
1399
- export { createGoogleConnector as default, getAccessToken };
188
+ } catch (error) {
189
+ return getUserInfoErrorHandler(error);
190
+ }
191
+ };
192
+ var authorizationCallbackHandler = async (parameterObject) => {
193
+ const result = authResponseGuard.safeParse(parameterObject);
194
+ if (!result.success) {
195
+ throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(parameterObject));
196
+ }
197
+ return result.data;
198
+ };
199
+ var getUserInfoErrorHandler = (error) => {
200
+ if (error instanceof HTTPError) {
201
+ const { statusCode, body: rawBody } = error.response;
202
+ if (statusCode === 401) {
203
+ throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid);
204
+ }
205
+ throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(rawBody));
206
+ }
207
+ throw error;
208
+ };
209
+ var createGoogleConnector = async ({ getConfig }) => {
210
+ return {
211
+ metadata: defaultMetadata,
212
+ type: ConnectorType.Social,
213
+ configGuard: GoogleConnector3.configGuard,
214
+ getAuthorizationUri: getAuthorizationUri(getConfig),
215
+ getUserInfo: getUserInfo(getConfig)
216
+ };
217
+ };
218
+ var src_default = createGoogleConnector;
219
+ export {
220
+ src_default as default,
221
+ getAccessToken
222
+ };
223
+ //# sourceMappingURL=index.js.map