@dereekb/firebase-server 13.32.0 → 13.33.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.
Files changed (72) hide show
  1. package/calcom/index.cjs.default.js +1 -0
  2. package/calcom/index.cjs.js +1451 -0
  3. package/calcom/index.cjs.mjs +2 -0
  4. package/calcom/index.d.ts +1 -0
  5. package/calcom/index.esm.js +1437 -0
  6. package/calcom/package.json +29 -0
  7. package/calcom/src/index.d.ts +1 -0
  8. package/calcom/src/lib/calcom.oauth.connection.cache.d.ts +49 -0
  9. package/calcom/src/lib/calcom.oauth.connection.config.d.ts +75 -0
  10. package/calcom/src/lib/calcom.oauth.connection.context.d.ts +84 -0
  11. package/calcom/src/lib/calcom.oauth.connection.controller.d.ts +18 -0
  12. package/calcom/src/lib/calcom.oauth.connection.module.d.ts +55 -0
  13. package/calcom/src/lib/calcom.oauth.connection.service.d.ts +33 -0
  14. package/calcom/src/lib/index.d.ts +6 -0
  15. package/discord/index.cjs.default.js +1 -0
  16. package/discord/index.cjs.js +761 -0
  17. package/discord/index.cjs.mjs +2 -0
  18. package/discord/index.d.ts +1 -0
  19. package/discord/index.esm.js +753 -0
  20. package/discord/package.json +29 -0
  21. package/discord/src/index.d.ts +1 -0
  22. package/discord/src/lib/discord.oauth.connection.config.d.ts +69 -0
  23. package/discord/src/lib/discord.oauth.connection.controller.d.ts +18 -0
  24. package/discord/src/lib/discord.oauth.connection.module.d.ts +39 -0
  25. package/discord/src/lib/discord.oauth.connection.service.d.ts +43 -0
  26. package/discord/src/lib/index.d.ts +4 -0
  27. package/index.cjs.js +14 -3
  28. package/index.esm.js +14 -3
  29. package/mailgun/package.json +9 -9
  30. package/mcp/package.json +11 -11
  31. package/model/index.cjs.js +3986 -855
  32. package/model/index.esm.js +3934 -862
  33. package/model/package.json +10 -9
  34. package/model/src/lib/index.d.ts +1 -0
  35. package/model/src/lib/userexternalconnection/index.d.ts +8 -0
  36. package/model/src/lib/userexternalconnection/oauth/index.d.ts +7 -0
  37. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.config.d.ts +110 -0
  38. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.controller.d.ts +68 -0
  39. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.error.d.ts +29 -0
  40. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.refresh.d.ts +24 -0
  41. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.registry.d.ts +54 -0
  42. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.service.d.ts +216 -0
  43. package/model/src/lib/userexternalconnection/oauth/userexternalconnection.oauth.state.d.ts +114 -0
  44. package/model/src/lib/userexternalconnection/userexternalconnection.accessor.service.d.ts +111 -0
  45. package/model/src/lib/userexternalconnection/userexternalconnection.action.server.d.ts +172 -0
  46. package/model/src/lib/userexternalconnection/userexternalconnection.error.d.ts +44 -0
  47. package/model/src/lib/userexternalconnection/userexternalconnection.module.d.ts +129 -0
  48. package/model/src/lib/userexternalconnection/userexternalconnection.private.d.ts +192 -0
  49. package/model/src/lib/userexternalconnection/userexternalconnection.reader.service.d.ts +157 -0
  50. package/model/src/lib/userexternalconnection/userexternalconnection.refresh.service.d.ts +46 -0
  51. package/oidc/index.cjs.js +104 -78
  52. package/oidc/index.esm.js +104 -78
  53. package/oidc/package.json +10 -10
  54. package/package.json +24 -10
  55. package/src/lib/env/env.config.d.ts +15 -0
  56. package/src/lib/env/env.service.d.ts +7 -0
  57. package/src/lib/nest/env/env.service.d.ts +1 -0
  58. package/test/index.cjs.js +14 -2
  59. package/test/index.esm.js +15 -3
  60. package/test/package.json +11 -11
  61. package/test/src/lib/firebase/firebase.admin.auth.d.ts +1 -1
  62. package/twilio/package.json +8 -8
  63. package/zoho/README.md +8 -0
  64. package/zoho/index.cjs.js +1223 -33
  65. package/zoho/index.esm.js +1212 -36
  66. package/zoho/package.json +12 -9
  67. package/zoho/src/lib/index.d.ts +5 -0
  68. package/zoho/src/lib/zoho.oauth.connection.cache.d.ts +45 -0
  69. package/zoho/src/lib/zoho.oauth.connection.config.d.ts +80 -0
  70. package/zoho/src/lib/zoho.oauth.connection.controller.d.ts +18 -0
  71. package/zoho/src/lib/zoho.oauth.connection.module.d.ts +43 -0
  72. package/zoho/src/lib/zoho.oauth.connection.service.d.ts +107 -0
package/zoho/index.esm.js CHANGED
@@ -1,5 +1,12 @@
1
- import { firestoreSubObject, firestoreDate, firestoreNumber, firestoreString, firestoreObjectArray } from '@dereekb/firebase';
2
- import { isPast, filterUniqueFunction } from '@dereekb/util';
1
+ import { firestoreSubObject, firestoreDate, firestoreNumber, firestoreString, firestoreObjectArray, ZOHO_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE } from '@dereekb/firebase';
2
+ import { isPast, filterUniqueFunction, MS_IN_SECOND } from '@dereekb/util';
3
+ import { ZOHO_ACCOUNTS_PROFILE_READ_SCOPE, zohoAccountsConfigApiUrl, zohoAccountsAuthorizeUrlFactory, zohoOAuthScopesFromScopeString, zohoAccountsApiUrlKeyForApiUrl, ZOHO_ACCOUNTS_API_URLS, ZOHO_OAUTH_SCOPE_DELIMITER } from '@dereekb/zoho';
4
+ import { userExternalConnectionOAuthControllerPath, userExternalConnectionOAuthRoutesForGlobalRouteExclude, userExternalConnectionOAuthServiceConfigFactory, UserExternalConnectionOAuthServiceConfig, UserExternalConnectionStateCoder, UserExternalConnectionServerActions, UserExternalConnectionAccessor, AbstractUserExternalConnectionOAuthService, mergeRefreshedUserExternalConnectionCredentials, AbstractUserExternalConnectionOAuthController } from '@dereekb/firebase-server/model';
5
+ import { safeToJsDate } from '@dereekb/date';
6
+ import { Injectable, Inject, Controller } from '@nestjs/common';
7
+ import { ZohoAccountsOAuthApi } from '@dereekb/zoho/nestjs';
8
+ import { ConfigModule } from '@nestjs/config';
9
+ import { FirebaseServerEnvService } from '@dereekb/firebase-server';
3
10
 
4
11
  /**
5
12
  * {@link SystemState} type identifier for storing Zoho access tokens in Firestore.
@@ -59,15 +66,15 @@ var zohoAccessTokenSystemStateEmbeddedTokenConverter = firestoreSubObject({
59
66
  return accessor.loadDocumentForId(ZOHO_ACCESS_TOKEN_SYSTEM_STATE_TYPE);
60
67
  }
61
68
 
62
- function _array_like_to_array(arr, len) {
69
+ function _array_like_to_array$1(arr, len) {
63
70
  if (len == null || len > arr.length) len = arr.length;
64
71
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
65
72
  return arr2;
66
73
  }
67
- function _array_without_holes(arr) {
68
- if (Array.isArray(arr)) return _array_like_to_array(arr);
74
+ function _array_without_holes$1(arr) {
75
+ if (Array.isArray(arr)) return _array_like_to_array$1(arr);
69
76
  }
70
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
77
+ function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
71
78
  try {
72
79
  var info = gen[key](arg);
73
80
  var value = info.value;
@@ -81,22 +88,22 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
81
88
  Promise.resolve(value).then(_next, _throw);
82
89
  }
83
90
  }
84
- function _async_to_generator(fn) {
91
+ function _async_to_generator$2(fn) {
85
92
  return function() {
86
93
  var self = this, args = arguments;
87
94
  return new Promise(function(resolve, reject) {
88
95
  var gen = fn.apply(self, args);
89
96
  function _next(value) {
90
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
97
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
91
98
  }
92
99
  function _throw(err) {
93
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
100
+ asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
94
101
  }
95
102
  _next(undefined);
96
103
  });
97
104
  };
98
105
  }
99
- function _define_property(obj, key, value) {
106
+ function _define_property$4(obj, key, value) {
100
107
  if (key in obj) {
101
108
  Object.defineProperty(obj, key, {
102
109
  value: value,
@@ -109,13 +116,13 @@ function _define_property(obj, key, value) {
109
116
  }
110
117
  return obj;
111
118
  }
112
- function _iterable_to_array(iter) {
119
+ function _iterable_to_array$1(iter) {
113
120
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
114
121
  }
115
- function _non_iterable_spread() {
122
+ function _non_iterable_spread$1() {
116
123
  throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
117
124
  }
118
- function _object_spread(target) {
125
+ function _object_spread$2(target) {
119
126
  for(var i = 1; i < arguments.length; i++){
120
127
  var source = arguments[i] != null ? arguments[i] : {};
121
128
  var ownKeys = Object.keys(source);
@@ -125,12 +132,12 @@ function _object_spread(target) {
125
132
  }));
126
133
  }
127
134
  ownKeys.forEach(function(key) {
128
- _define_property(target, key, source[key]);
135
+ _define_property$4(target, key, source[key]);
129
136
  });
130
137
  }
131
138
  return target;
132
139
  }
133
- function ownKeys(object, enumerableOnly) {
140
+ function ownKeys$2(object, enumerableOnly) {
134
141
  var keys = Object.keys(object);
135
142
  if (Object.getOwnPropertySymbols) {
136
143
  var symbols = Object.getOwnPropertySymbols(object);
@@ -138,29 +145,29 @@ function ownKeys(object, enumerableOnly) {
138
145
  }
139
146
  return keys;
140
147
  }
141
- function _object_spread_props(target, source) {
148
+ function _object_spread_props$2(target, source) {
142
149
  source = source != null ? source : {};
143
150
  if (Object.getOwnPropertyDescriptors) {
144
151
  Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
145
152
  } else {
146
- ownKeys(Object(source)).forEach(function(key) {
153
+ ownKeys$2(Object(source)).forEach(function(key) {
147
154
  Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
148
155
  });
149
156
  }
150
157
  return target;
151
158
  }
152
- function _to_consumable_array(arr) {
153
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
159
+ function _to_consumable_array$1(arr) {
160
+ return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
154
161
  }
155
- function _unsupported_iterable_to_array(o, minLen) {
162
+ function _unsupported_iterable_to_array$1(o, minLen) {
156
163
  if (!o) return;
157
- if (typeof o === "string") return _array_like_to_array(o, minLen);
164
+ if (typeof o === "string") return _array_like_to_array$1(o, minLen);
158
165
  var n = Object.prototype.toString.call(o).slice(8, -1);
159
166
  if (n === "Object" && o.constructor) n = o.constructor.name;
160
167
  if (n === "Map" || n === "Set") return Array.from(n);
161
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
168
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
162
169
  }
163
- function _ts_generator(thisArg, body) {
170
+ function _ts_generator$2(thisArg, body) {
164
171
  var f, y, t, _ = {
165
172
  label: 0,
166
173
  sent: function() {
@@ -281,9 +288,9 @@ function _ts_generator(thisArg, body) {
281
288
  loadZohoAccessTokenCache: function loadZohoAccessTokenCache(serviceKey) {
282
289
  var cache = {
283
290
  loadCachedToken: function loadCachedToken() {
284
- return _async_to_generator(function() {
291
+ return _async_to_generator$2(function() {
285
292
  var document, existingData, result, tokensArray;
286
- return _ts_generator(this, function(_state) {
293
+ return _ts_generator$2(this, function(_state) {
287
294
  switch(_state.label){
288
295
  case 0:
289
296
  document = loadZohoAccessTokenSystemState(systemStateDocumentAccessor);
@@ -309,17 +316,17 @@ function _ts_generator(thisArg, body) {
309
316
  })();
310
317
  },
311
318
  updateCachedToken: function updateCachedToken(accessToken) {
312
- return _async_to_generator(function() {
313
- return _ts_generator(this, function(_state) {
319
+ return _async_to_generator$2(function() {
320
+ return _ts_generator$2(this, function(_state) {
314
321
  switch(_state.label){
315
322
  case 0:
316
323
  // run in a transaction
317
324
  return [
318
325
  4,
319
326
  systemStateCollection.firestoreContext.runTransaction(function(transaction) {
320
- return _async_to_generator(function() {
327
+ return _async_to_generator$2(function() {
321
328
  var _ref, documentInTransaction, existingData, existingTokens, tokens, templateOrUpdate;
322
- return _ts_generator(this, function(_state) {
329
+ return _ts_generator$2(this, function(_state) {
323
330
  switch(_state.label){
324
331
  case 0:
325
332
  documentInTransaction = loadZohoAccessTokenSystemState(systemStateCollection.documentAccessorForTransaction(transaction));
@@ -331,11 +338,11 @@ function _ts_generator(thisArg, body) {
331
338
  existingData = _state.sent();
332
339
  existingTokens = (_ref = existingData === null || existingData === void 0 ? void 0 : existingData.data.tokens) !== null && _ref !== void 0 ? _ref : [];
333
340
  tokens = // filter any potential old token for this service key
334
- _to_consumable_array(existingTokens.filter(function(x) {
341
+ _to_consumable_array$1(existingTokens.filter(function(x) {
335
342
  return x.key !== serviceKey;
336
343
  })).concat([
337
344
  // add the new token
338
- _object_spread_props(_object_spread({}, accessToken), {
345
+ _object_spread_props$2(_object_spread$2({}, accessToken), {
339
346
  key: serviceKey
340
347
  })
341
348
  ]);
@@ -386,16 +393,16 @@ function _ts_generator(thisArg, body) {
386
393
  })();
387
394
  },
388
395
  clearCachedToken: function clearCachedToken() {
389
- return _async_to_generator(function() {
390
- return _ts_generator(this, function(_state) {
396
+ return _async_to_generator$2(function() {
397
+ return _ts_generator$2(this, function(_state) {
391
398
  switch(_state.label){
392
399
  case 0:
393
400
  return [
394
401
  4,
395
402
  systemStateCollection.firestoreContext.runTransaction(function(transaction) {
396
- return _async_to_generator(function() {
403
+ return _async_to_generator$2(function() {
397
404
  var documentInTransaction, existingData, templateOrUpdate;
398
- return _ts_generator(this, function(_state) {
405
+ return _ts_generator$2(this, function(_state) {
399
406
  switch(_state.label){
400
407
  case 0:
401
408
  documentInTransaction = loadZohoAccessTokenSystemState(systemStateCollection.documentAccessorForTransaction(transaction));
@@ -447,4 +454,1173 @@ function _ts_generator(thisArg, body) {
447
454
  return service;
448
455
  }
449
456
 
450
- export { ZOHO_ACCESS_TOKEN_SYSTEM_STATE_TYPE, firebaseZohoAccountsAccessTokenCacheService, loadZohoAccessTokenSystemState, zohoAccessTokenSystemStateDataConverter, zohoAccessTokenSystemStateEmbeddedTokenConverter };
457
+ function _type_of$3(obj) {
458
+ "@swc/helpers - typeof";
459
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
460
+ }
461
+ function __decorate(decorators, target, key, desc) {
462
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
463
+ if ((typeof Reflect === "undefined" ? "undefined" : _type_of$3(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
464
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
465
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
466
+ }
467
+ function __param(paramIndex, decorator) {
468
+ return function(target, key) {
469
+ decorator(target, key, paramIndex);
470
+ };
471
+ }
472
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
473
+ var e = new Error(message);
474
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
475
+ };
476
+
477
+ function _assert_this_initialized$2(self) {
478
+ if (self === void 0) {
479
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
480
+ }
481
+ return self;
482
+ }
483
+ function _call_super$2(_this, derived, args) {
484
+ derived = _get_prototype_of$2(derived);
485
+ return _possible_constructor_return$2(_this, _is_native_reflect_construct$2() ? Reflect.construct(derived, args || [], _get_prototype_of$2(_this).constructor) : derived.apply(_this, args));
486
+ }
487
+ function _class_call_check$2(instance, Constructor) {
488
+ if (!(instance instanceof Constructor)) {
489
+ throw new TypeError("Cannot call a class as a function");
490
+ }
491
+ }
492
+ function _define_property$3(obj, key, value) {
493
+ if (key in obj) {
494
+ Object.defineProperty(obj, key, {
495
+ value: value,
496
+ enumerable: true,
497
+ configurable: true,
498
+ writable: true
499
+ });
500
+ } else {
501
+ obj[key] = value;
502
+ }
503
+ return obj;
504
+ }
505
+ function _get_prototype_of$2(o) {
506
+ _get_prototype_of$2 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
507
+ return o.__proto__ || Object.getPrototypeOf(o);
508
+ };
509
+ return _get_prototype_of$2(o);
510
+ }
511
+ function _inherits$2(subClass, superClass) {
512
+ if (typeof superClass !== "function" && superClass !== null) {
513
+ throw new TypeError("Super expression must either be null or a function");
514
+ }
515
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
516
+ constructor: {
517
+ value: subClass,
518
+ writable: true,
519
+ configurable: true
520
+ }
521
+ });
522
+ if (superClass) _set_prototype_of$2(subClass, superClass);
523
+ }
524
+ function _object_spread$1(target) {
525
+ for(var i = 1; i < arguments.length; i++){
526
+ var source = arguments[i] != null ? arguments[i] : {};
527
+ var ownKeys = Object.keys(source);
528
+ if (typeof Object.getOwnPropertySymbols === "function") {
529
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
530
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
531
+ }));
532
+ }
533
+ ownKeys.forEach(function(key) {
534
+ _define_property$3(target, key, source[key]);
535
+ });
536
+ }
537
+ return target;
538
+ }
539
+ function ownKeys$1(object, enumerableOnly) {
540
+ var keys = Object.keys(object);
541
+ if (Object.getOwnPropertySymbols) {
542
+ var symbols = Object.getOwnPropertySymbols(object);
543
+ keys.push.apply(keys, symbols);
544
+ }
545
+ return keys;
546
+ }
547
+ function _object_spread_props$1(target, source) {
548
+ source = source != null ? source : {};
549
+ if (Object.getOwnPropertyDescriptors) {
550
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
551
+ } else {
552
+ ownKeys$1(Object(source)).forEach(function(key) {
553
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
554
+ });
555
+ }
556
+ return target;
557
+ }
558
+ function _possible_constructor_return$2(self, call) {
559
+ if (call && (_type_of$2(call) === "object" || typeof call === "function")) {
560
+ return call;
561
+ }
562
+ return _assert_this_initialized$2(self);
563
+ }
564
+ function _set_prototype_of$2(o, p) {
565
+ _set_prototype_of$2 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
566
+ o.__proto__ = p;
567
+ return o;
568
+ };
569
+ return _set_prototype_of$2(o, p);
570
+ }
571
+ function _type_of$2(obj) {
572
+ "@swc/helpers - typeof";
573
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
574
+ }
575
+ function _is_native_reflect_construct$2() {
576
+ try {
577
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
578
+ } catch (_) {}
579
+ return (_is_native_reflect_construct$2 = function() {
580
+ return !!result;
581
+ })();
582
+ }
583
+ /**
584
+ * Controller path the Zoho external-connection OAuth endpoints are mounted at.
585
+ *
586
+ * Derived from the framework's path factory, the same expression the redirect URI and the
587
+ * global-prefix exclusion are built from, so the three cannot drift apart.
588
+ */ var ZOHO_USER_EXTERNAL_CONNECTION_OAUTH_CONTROLLER_PATH = userExternalConnectionOAuthControllerPath(ZOHO_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE);
589
+ /**
590
+ * Routes to exclude from an app's global API route prefix so the Zoho callback controller stays
591
+ * mounted at `/oauth/zoho/*`.
592
+ *
593
+ * Spread this into the `exclude` list of the app's `globalApiRoutePrefix` config, alongside
594
+ * `FIREBASE_SERVER_OIDC_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE`.
595
+ */ var ZOHO_USER_EXTERNAL_CONNECTION_OAUTH_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE = userExternalConnectionOAuthRoutesForGlobalRouteExclude(ZOHO_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE);
596
+ /**
597
+ * The scopes requested when an app does not declare its own.
598
+ *
599
+ * Declared in code, deliberately NOT read from the environment: the set to request follows from what
600
+ * the integration actually does, so it belongs where it is reviewable.
601
+ *
602
+ * Least privilege for a connect that proves the handoff and labels the connection: read the
603
+ * authorizing user's Zoho identity, and nothing else. No `ZohoCRM.*` / `ZohoRecruit.*` scope is
604
+ * requested because the default integration makes no product API call — requesting one would be
605
+ * privilege the code never uses, which is the same error as under-requesting, in the other
606
+ * direction. An app that actually calls a Zoho product declares its own set on the module metadata,
607
+ * in code.
608
+ *
609
+ * Unlike Cal.com, Zoho does not pre-register scopes on the OAuth client, so nothing has to be
610
+ * registered in the API console to request this.
611
+ */ var DEFAULT_ZOHO_OAUTH_SCOPES = [
612
+ ZOHO_ACCOUNTS_PROFILE_READ_SCOPE
613
+ ];
614
+ /**
615
+ * Configuration for the {@link ZohoUserExternalConnectionOAuthService}.
616
+ *
617
+ * Extends the framework config with what is Zoho's own: which scopes to request, and which
618
+ * datacenter to authorize against.
619
+ */ var ZohoUserExternalConnectionOAuthServiceConfig = /*#__PURE__*/ function(UserExternalConnectionOAuthServiceConfig) {
620
+ _inherits$2(ZohoUserExternalConnectionOAuthServiceConfig, UserExternalConnectionOAuthServiceConfig);
621
+ function ZohoUserExternalConnectionOAuthServiceConfig() {
622
+ _class_call_check$2(this, ZohoUserExternalConnectionOAuthServiceConfig);
623
+ var _this;
624
+ _this = _call_super$2(this, ZohoUserExternalConnectionOAuthServiceConfig, arguments), _define_property$3(_this, "scopes", void 0), /**
625
+ * Datacenter to authorize against. Defaults to the api's configured one.
626
+ */ _define_property$3(_this, "accountsApiUrl", void 0);
627
+ return _this;
628
+ }
629
+ return ZohoUserExternalConnectionOAuthServiceConfig;
630
+ }(UserExternalConnectionOAuthServiceConfig);
631
+ /**
632
+ * Builds the Zoho connect flow's configuration from the app's configured origins.
633
+ *
634
+ * Nothing here is read from the environment as a value: the redirect URI is derived from the app's
635
+ * OAuth origin plus the mounted controller path, and the return URLs from the app URL plus
636
+ * code-declared paths. Registering Zoho therefore adds no deployment configuration beyond the client
637
+ * credentials the OAuth api already reads.
638
+ *
639
+ * @param config - The env service, the return paths, and the optional scope/datacenter overrides.
640
+ * @returns The validated service configuration.
641
+ */ function zohoUserExternalConnectionOAuthServiceConfigFactory(config) {
642
+ var envService = config.envService, successPath = config.successPath, failurePath = config.failurePath, scopes = config.scopes, accountsApiUrl = config.accountsApiUrl;
643
+ var baseConfig = userExternalConnectionOAuthServiceConfigFactory({
644
+ envService: envService,
645
+ providerType: ZOHO_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE,
646
+ successPath: successPath,
647
+ failurePath: failurePath
648
+ });
649
+ return _object_spread_props$1(_object_spread$1({}, baseConfig), {
650
+ scopes: scopes !== null && scopes !== void 0 ? scopes : DEFAULT_ZOHO_OAUTH_SCOPES,
651
+ accountsApiUrl: accountsApiUrl
652
+ });
653
+ }
654
+
655
+ function _assert_this_initialized$1(self) {
656
+ if (self === void 0) {
657
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
658
+ }
659
+ return self;
660
+ }
661
+ function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
662
+ try {
663
+ var info = gen[key](arg);
664
+ var value = info.value;
665
+ } catch (error) {
666
+ reject(error);
667
+ return;
668
+ }
669
+ if (info.done) {
670
+ resolve(value);
671
+ } else {
672
+ Promise.resolve(value).then(_next, _throw);
673
+ }
674
+ }
675
+ function _async_to_generator$1(fn) {
676
+ return function() {
677
+ var self = this, args = arguments;
678
+ return new Promise(function(resolve, reject) {
679
+ var gen = fn.apply(self, args);
680
+ function _next(value) {
681
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
682
+ }
683
+ function _throw(err) {
684
+ asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
685
+ }
686
+ _next(undefined);
687
+ });
688
+ };
689
+ }
690
+ function _call_super$1(_this, derived, args) {
691
+ derived = _get_prototype_of$1(derived);
692
+ return _possible_constructor_return$1(_this, _is_native_reflect_construct$1() ? Reflect.construct(derived, [], _get_prototype_of$1(_this).constructor) : derived.apply(_this, args));
693
+ }
694
+ function _class_call_check$1(instance, Constructor) {
695
+ if (!(instance instanceof Constructor)) {
696
+ throw new TypeError("Cannot call a class as a function");
697
+ }
698
+ }
699
+ function _defineProperties(target, props) {
700
+ for(var i = 0; i < props.length; i++){
701
+ var descriptor = props[i];
702
+ descriptor.enumerable = descriptor.enumerable || false;
703
+ descriptor.configurable = true;
704
+ if ("value" in descriptor) descriptor.writable = true;
705
+ Object.defineProperty(target, descriptor.key, descriptor);
706
+ }
707
+ }
708
+ function _create_class(Constructor, protoProps, staticProps) {
709
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
710
+ return Constructor;
711
+ }
712
+ function _define_property$2(obj, key, value) {
713
+ if (key in obj) {
714
+ Object.defineProperty(obj, key, {
715
+ value: value,
716
+ enumerable: true,
717
+ configurable: true,
718
+ writable: true
719
+ });
720
+ } else {
721
+ obj[key] = value;
722
+ }
723
+ return obj;
724
+ }
725
+ function _get_prototype_of$1(o) {
726
+ _get_prototype_of$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
727
+ return o.__proto__ || Object.getPrototypeOf(o);
728
+ };
729
+ return _get_prototype_of$1(o);
730
+ }
731
+ function _inherits$1(subClass, superClass) {
732
+ if (typeof superClass !== "function" && superClass !== null) {
733
+ throw new TypeError("Super expression must either be null or a function");
734
+ }
735
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
736
+ constructor: {
737
+ value: subClass,
738
+ writable: true,
739
+ configurable: true
740
+ }
741
+ });
742
+ if (superClass) _set_prototype_of$1(subClass, superClass);
743
+ }
744
+ function _possible_constructor_return$1(self, call) {
745
+ if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
746
+ return call;
747
+ }
748
+ return _assert_this_initialized$1(self);
749
+ }
750
+ function _set_prototype_of$1(o, p) {
751
+ _set_prototype_of$1 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
752
+ o.__proto__ = p;
753
+ return o;
754
+ };
755
+ return _set_prototype_of$1(o, p);
756
+ }
757
+ function _type_of$1(obj) {
758
+ "@swc/helpers - typeof";
759
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
760
+ }
761
+ function _is_native_reflect_construct$1() {
762
+ try {
763
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
764
+ } catch (_) {}
765
+ return (_is_native_reflect_construct$1 = function() {
766
+ return !!result;
767
+ })();
768
+ }
769
+ function _ts_generator$1(thisArg, body) {
770
+ var f, y, t, _ = {
771
+ label: 0,
772
+ sent: function() {
773
+ if (t[0] & 1) throw t[1];
774
+ return t[1];
775
+ },
776
+ trys: [],
777
+ ops: []
778
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
779
+ return d(g, "next", {
780
+ value: verb(0)
781
+ }), d(g, "throw", {
782
+ value: verb(1)
783
+ }), d(g, "return", {
784
+ value: verb(2)
785
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
786
+ value: function() {
787
+ return this;
788
+ }
789
+ }), g;
790
+ function verb(n) {
791
+ return function(v) {
792
+ return step([
793
+ n,
794
+ v
795
+ ]);
796
+ };
797
+ }
798
+ function step(op) {
799
+ if (f) throw new TypeError("Generator is already executing.");
800
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
801
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
802
+ if (y = 0, t) op = [
803
+ op[0] & 2,
804
+ t.value
805
+ ];
806
+ switch(op[0]){
807
+ case 0:
808
+ case 1:
809
+ t = op;
810
+ break;
811
+ case 4:
812
+ _.label++;
813
+ return {
814
+ value: op[1],
815
+ done: false
816
+ };
817
+ case 5:
818
+ _.label++;
819
+ y = op[1];
820
+ op = [
821
+ 0
822
+ ];
823
+ continue;
824
+ case 7:
825
+ op = _.ops.pop();
826
+ _.trys.pop();
827
+ continue;
828
+ default:
829
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
830
+ _ = 0;
831
+ continue;
832
+ }
833
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
834
+ _.label = op[1];
835
+ break;
836
+ }
837
+ if (op[0] === 6 && _.label < t[1]) {
838
+ _.label = t[1];
839
+ t = op;
840
+ break;
841
+ }
842
+ if (t && _.label < t[2]) {
843
+ _.label = t[2];
844
+ _.ops.push(op);
845
+ break;
846
+ }
847
+ if (t[2]) _.ops.pop();
848
+ _.trys.pop();
849
+ continue;
850
+ }
851
+ op = body.call(thisArg, _);
852
+ } catch (e) {
853
+ op = [
854
+ 6,
855
+ e
856
+ ];
857
+ y = 0;
858
+ } finally{
859
+ f = t = 0;
860
+ }
861
+ if (op[0] & 5) throw op[1];
862
+ return {
863
+ value: op[0] ? op[1] : void 0,
864
+ done: true
865
+ };
866
+ }
867
+ }
868
+ /**
869
+ * The callback parameter naming the datacenter whose accounts server issued the code.
870
+ */ var ZOHO_OAUTH_CALLBACK_ACCOUNTS_SERVER_PARAM = 'accounts-server';
871
+ /**
872
+ * The callback parameter naming the datacenter's short location code, e.g. `us`.
873
+ */ var ZOHO_OAUTH_CALLBACK_LOCATION_PARAM = 'location';
874
+ /**
875
+ * `extra` key holding the api domain a Zoho access token is usable against.
876
+ *
877
+ * Named constants because these keys are written on connect and read back on refresh — a literal in
878
+ * one place and a typo in the other would silently send the refresh to the wrong datacenter.
879
+ */ var ZOHO_EXTRA_API_DOMAIN_KEY = 'apiDomain';
880
+ /**
881
+ * `extra` key holding the accounts host a later refresh must be sent to.
882
+ */ var ZOHO_EXTRA_ACCOUNTS_SERVER_KEY = 'accountsServer';
883
+ /**
884
+ * `extra` key holding Zoho's short location code for the datacenter.
885
+ */ var ZOHO_EXTRA_LOCATION_KEY = 'location';
886
+ /**
887
+ * Maps an exchanged Zoho token response to the credentials stored on the private connection document.
888
+ *
889
+ * Two things differ from Cal.com's mapper. Zoho does not rotate its refresh token, so there is
890
+ * nothing to prefer over the token we already hold — and `refresh_token` can be ABSENT entirely on a
891
+ * re-consent, which is why it is passed through as `Maybe` rather than asserted (the framework's
892
+ * `credentialsRetainingStoredRefreshToken` is what keeps that from destroying a working token). And
893
+ * `api_domain` / `accountsServer` / `location` are retained in `extra`: a Zoho access token is only
894
+ * usable against the api domain it was issued for, and a later refresh must go back to the same
895
+ * datacenter's accounts server, so dropping them would leave the stored credentials unusable.
896
+ *
897
+ * @param input - The token response, the host it came from, and the identity when one was read.
898
+ * @returns The credentials to store.
899
+ */ function zohoUserExternalConnectionCredentials(input) {
900
+ var _ref, _ref1;
901
+ var response = input.response, accountsApiUrl = input.accountsApiUrl, location = input.location, userInfo = input.userInfo;
902
+ var access_token = response.access_token, refresh_token = response.refresh_token, expires_in = response.expires_in, scope = response.scope, api_domain = response.api_domain;
903
+ var now = Date.now();
904
+ var zuid = userInfo === null || userInfo === void 0 ? void 0 : userInfo.ZUID;
905
+ var _obj;
906
+ return {
907
+ accessToken: access_token,
908
+ // Maybe on purpose — absent on a re-consent that did not force the consent screen
909
+ refreshToken: refresh_token,
910
+ tokenType: 'Bearer',
911
+ issuedAt: new Date(now).toISOString(),
912
+ expiresAt: expires_in == null ? undefined : new Date(now + expires_in * MS_IN_SECOND).toISOString(),
913
+ scopes: zohoOAuthScopesFromScopeString(scope),
914
+ externalAccountId: zuid == null ? undefined : String(zuid),
915
+ label: (_ref = (_ref1 = userInfo === null || userInfo === void 0 ? void 0 : userInfo.Email) !== null && _ref1 !== void 0 ? _ref1 : userInfo === null || userInfo === void 0 ? void 0 : userInfo.Display_Name) !== null && _ref !== void 0 ? _ref : undefined,
916
+ extra: (_obj = {}, _define_property$2(_obj, ZOHO_EXTRA_API_DOMAIN_KEY, api_domain), _define_property$2(_obj, ZOHO_EXTRA_ACCOUNTS_SERVER_KEY, accountsApiUrl), _define_property$2(_obj, ZOHO_EXTRA_LOCATION_KEY, location), _obj)
917
+ };
918
+ }
919
+ /**
920
+ * Zoho's half of the external-connection authorization-code handoff.
921
+ *
922
+ * Everything else — resolving who is connecting, surfacing a refusal, retaining a refresh token the
923
+ * exchange did not return, persisting the credentials, choosing the redirect — is the framework's.
924
+ */ var ZohoUserExternalConnectionOAuthService = /*#__PURE__*/ function(AbstractUserExternalConnectionOAuthService) {
925
+ _inherits$1(ZohoUserExternalConnectionOAuthService, AbstractUserExternalConnectionOAuthService);
926
+ function ZohoUserExternalConnectionOAuthService(config, stateCoder, userExternalConnectionActions, userExternalConnectionAccessor, oauthApi) {
927
+ _class_call_check$1(this, ZohoUserExternalConnectionOAuthService);
928
+ var _this;
929
+ _this = _call_super$1(this, ZohoUserExternalConnectionOAuthService), _define_property$2(_this, "config", void 0), _define_property$2(_this, "stateCoder", void 0), _define_property$2(_this, "userExternalConnectionActions", void 0), _define_property$2(_this, "userExternalConnectionAccessor", void 0), _define_property$2(_this, "oauthApi", void 0), _define_property$2(_this, "authorizeUrlFactory", void 0), /**
930
+ * The accounts host this app authorizes against, and the fallback for an exchange whose callback
931
+ * named no usable one.
932
+ */ _define_property$2(_this, "accountsApiUrl", void 0);
933
+ _this.config = config;
934
+ _this.stateCoder = stateCoder;
935
+ _this.userExternalConnectionActions = userExternalConnectionActions;
936
+ _this.userExternalConnectionAccessor = userExternalConnectionAccessor;
937
+ _this.oauthApi = oauthApi;
938
+ var scopes = config.scopes, accountsApiUrl = config.accountsApiUrl, userExternalConnectionOAuth = config.userExternalConnectionOAuth;
939
+ // read through the api rather than injecting ZohoAccountsOAuthServiceConfig directly, which the
940
+ // OAuth module does not export to its dependents
941
+ _this.accountsApiUrl = accountsApiUrl == null ? oauthApi.apiUrl : zohoAccountsConfigApiUrl(accountsApiUrl);
942
+ _this.authorizeUrlFactory = zohoAccountsAuthorizeUrlFactory({
943
+ clientId: oauthApi.clientId,
944
+ redirectUri: userExternalConnectionOAuth.redirectUri,
945
+ scopes: scopes,
946
+ accountsApiUrl: _this.accountsApiUrl
947
+ });
948
+ return _this;
949
+ }
950
+ _create_class(ZohoUserExternalConnectionOAuthService, [
951
+ {
952
+ key: "authorizeUrlForState",
953
+ value: function authorizeUrlForState(state) {
954
+ return this.authorizeUrlFactory({
955
+ state: state
956
+ });
957
+ }
958
+ },
959
+ {
960
+ key: "credentialsForAuthorizationCode",
961
+ value: function credentialsForAuthorizationCode(input) {
962
+ return _async_to_generator$1(function() {
963
+ var _this_accountsApiUrlForCallbackQuery, code, redirectUri, query, accountsApiUrl, response, userInfo, e;
964
+ return _ts_generator$1(this, function(_state) {
965
+ switch(_state.label){
966
+ case 0:
967
+ code = input.code, redirectUri = input.redirectUri, query = input.query;
968
+ accountsApiUrl = (_this_accountsApiUrlForCallbackQuery = this.accountsApiUrlForCallbackQuery(query)) !== null && _this_accountsApiUrlForCallbackQuery !== void 0 ? _this_accountsApiUrlForCallbackQuery : this.accountsApiUrl;
969
+ return [
970
+ 4,
971
+ this.oauthApi.exchangeAuthorizationCode({
972
+ code: code,
973
+ redirectUri: redirectUri,
974
+ accountsApiUrl: accountsApiUrl
975
+ })
976
+ ];
977
+ case 1:
978
+ response = _state.sent();
979
+ _state.label = 2;
980
+ case 2:
981
+ _state.trys.push([
982
+ 2,
983
+ 4,
984
+ ,
985
+ 5
986
+ ]);
987
+ return [
988
+ 4,
989
+ this.oauthApi.userInfo({
990
+ accessToken: response.access_token,
991
+ accountsApiUrl: accountsApiUrl
992
+ })
993
+ ];
994
+ case 3:
995
+ userInfo = _state.sent();
996
+ return [
997
+ 3,
998
+ 5
999
+ ];
1000
+ case 4:
1001
+ e = _state.sent();
1002
+ this.logger.warn('Connected Zoho but could not read the identity to label the connection: ', e);
1003
+ return [
1004
+ 3,
1005
+ 5
1006
+ ];
1007
+ case 5:
1008
+ return [
1009
+ 2,
1010
+ zohoUserExternalConnectionCredentials({
1011
+ response: response,
1012
+ accountsApiUrl: accountsApiUrl,
1013
+ location: query === null || query === void 0 ? void 0 : query[ZOHO_OAUTH_CALLBACK_LOCATION_PARAM],
1014
+ userInfo: userInfo
1015
+ })
1016
+ ];
1017
+ }
1018
+ });
1019
+ }).call(this);
1020
+ }
1021
+ },
1022
+ {
1023
+ key: "refreshCredentials",
1024
+ value: function refreshCredentials(input) {
1025
+ return _async_to_generator$1(function() {
1026
+ var _this_allowlistedAccountsApiUrl, credentials, refreshToken, extra, storedAccountsServer, accountsApiUrl, response, location;
1027
+ return _ts_generator$1(this, function(_state) {
1028
+ switch(_state.label){
1029
+ case 0:
1030
+ credentials = input.credentials;
1031
+ refreshToken = credentials.refreshToken, extra = credentials.extra;
1032
+ if (!refreshToken) {
1033
+ throw new Error('ZohoUserExternalConnectionOAuthService.refreshCredentials: the stored credentials carry no refresh token.');
1034
+ }
1035
+ // the grant lives at ONE datacenter — a refresh token issued by `accounts.zoho.eu` is not honored
1036
+ // by `accounts.zoho.com` — so the stored accounts server is what the refresh must be sent to. It is
1037
+ // re-resolved through the allowlist rather than used verbatim: the value originally arrived on a
1038
+ // browser redirect, and it is the POST target the client secret travels to.
1039
+ storedAccountsServer = extra === null || extra === void 0 ? void 0 : extra[ZOHO_EXTRA_ACCOUNTS_SERVER_KEY];
1040
+ accountsApiUrl = (_this_allowlistedAccountsApiUrl = this.allowlistedAccountsApiUrl(storedAccountsServer == null ? undefined : String(storedAccountsServer))) !== null && _this_allowlistedAccountsApiUrl !== void 0 ? _this_allowlistedAccountsApiUrl : this.accountsApiUrl;
1041
+ return [
1042
+ 4,
1043
+ this.oauthApi.refreshUserAccessToken({
1044
+ refreshToken: refreshToken,
1045
+ accountsApiUrl: accountsApiUrl
1046
+ })
1047
+ ];
1048
+ case 1:
1049
+ response = _state.sent();
1050
+ // `location` is carried forward from the stored credentials rather than re-derived: it only ever
1051
+ // arrives on the callback, and the framework's merge would otherwise see an undefined value.
1052
+ location = extra === null || extra === void 0 ? void 0 : extra[ZOHO_EXTRA_LOCATION_KEY];
1053
+ // the response has no `refresh_token`, which the framework's merge retains — and `api_domain` may
1054
+ // legitimately differ from the one issued on connect, so it is taken from the response
1055
+ return [
1056
+ 2,
1057
+ zohoUserExternalConnectionCredentials({
1058
+ response: response,
1059
+ accountsApiUrl: accountsApiUrl,
1060
+ location: location == null ? undefined : String(location)
1061
+ })
1062
+ ];
1063
+ }
1064
+ });
1065
+ }).call(this);
1066
+ }
1067
+ },
1068
+ {
1069
+ /**
1070
+ * The accounts host to exchange against, taken from Zoho's `accounts-server` callback parameter.
1071
+ *
1072
+ * @param query - The raw callback query.
1073
+ * @returns The allowlisted accounts host the callback named, if any.
1074
+ */ key: "accountsApiUrlForCallbackQuery",
1075
+ value: function accountsApiUrlForCallbackQuery(query) {
1076
+ return this.allowlistedAccountsApiUrl(query === null || query === void 0 ? void 0 : query[ZOHO_OAUTH_CALLBACK_ACCOUNTS_SERVER_PARAM]);
1077
+ }
1078
+ },
1079
+ {
1080
+ /**
1081
+ * Resolves an untrusted accounts-host string back to one of the canonical Zoho hosts.
1082
+ *
1083
+ * Only an allowlisted Zoho host is honored. Every value passed here originated on a redirect an
1084
+ * attacker can compose — either the live callback query or a value persisted from an earlier one —
1085
+ * and it becomes the POST target the CLIENT SECRET is sent to, so an unchecked value would hand out
1086
+ * the secret. Resolving through the allowlist rather than comparing to it also guarantees the host
1087
+ * used is a canonical constant and never a caller-shaped variant of one. An unrecognized value is
1088
+ * dropped (and logged) rather than trusted.
1089
+ *
1090
+ * @param accountsServer - The untrusted host string, if any.
1091
+ * @returns The allowlisted accounts host, or null when there was none or it was not recognized.
1092
+ */ key: "allowlistedAccountsApiUrl",
1093
+ value: function allowlistedAccountsApiUrl(accountsServer) {
1094
+ var result;
1095
+ if (accountsServer) {
1096
+ var key = zohoAccountsApiUrlKeyForApiUrl(accountsServer);
1097
+ if (key == null) {
1098
+ this.logger.warn('Ignored an unrecognized Zoho accounts host of "'.concat(accountsServer, '"; using the configured host instead.'));
1099
+ } else {
1100
+ result = ZOHO_ACCOUNTS_API_URLS[key];
1101
+ }
1102
+ }
1103
+ return result;
1104
+ }
1105
+ }
1106
+ ]);
1107
+ return ZohoUserExternalConnectionOAuthService;
1108
+ }(AbstractUserExternalConnectionOAuthService);
1109
+ ZohoUserExternalConnectionOAuthService = __decorate([
1110
+ Injectable(),
1111
+ __param(0, Inject(ZohoUserExternalConnectionOAuthServiceConfig)),
1112
+ __param(1, Inject(UserExternalConnectionStateCoder)),
1113
+ __param(2, Inject(UserExternalConnectionServerActions)),
1114
+ __param(3, Inject(UserExternalConnectionAccessor)),
1115
+ __param(4, Inject(ZohoAccountsOAuthApi))
1116
+ ], ZohoUserExternalConnectionOAuthService);
1117
+
1118
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
1119
+ try {
1120
+ var info = gen[key](arg);
1121
+ var value = info.value;
1122
+ } catch (error) {
1123
+ reject(error);
1124
+ return;
1125
+ }
1126
+ if (info.done) {
1127
+ resolve(value);
1128
+ } else {
1129
+ Promise.resolve(value).then(_next, _throw);
1130
+ }
1131
+ }
1132
+ function _async_to_generator(fn) {
1133
+ return function() {
1134
+ var self = this, args = arguments;
1135
+ return new Promise(function(resolve, reject) {
1136
+ var gen = fn.apply(self, args);
1137
+ function _next(value) {
1138
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
1139
+ }
1140
+ function _throw(err) {
1141
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
1142
+ }
1143
+ _next(undefined);
1144
+ });
1145
+ };
1146
+ }
1147
+ function _define_property$1(obj, key, value) {
1148
+ if (key in obj) {
1149
+ Object.defineProperty(obj, key, {
1150
+ value: value,
1151
+ enumerable: true,
1152
+ configurable: true,
1153
+ writable: true
1154
+ });
1155
+ } else {
1156
+ obj[key] = value;
1157
+ }
1158
+ return obj;
1159
+ }
1160
+ function _object_spread(target) {
1161
+ for(var i = 1; i < arguments.length; i++){
1162
+ var source = arguments[i] != null ? arguments[i] : {};
1163
+ var ownKeys = Object.keys(source);
1164
+ if (typeof Object.getOwnPropertySymbols === "function") {
1165
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1166
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1167
+ }));
1168
+ }
1169
+ ownKeys.forEach(function(key) {
1170
+ _define_property$1(target, key, source[key]);
1171
+ });
1172
+ }
1173
+ return target;
1174
+ }
1175
+ function ownKeys(object, enumerableOnly) {
1176
+ var keys = Object.keys(object);
1177
+ if (Object.getOwnPropertySymbols) {
1178
+ var symbols = Object.getOwnPropertySymbols(object);
1179
+ keys.push.apply(keys, symbols);
1180
+ }
1181
+ return keys;
1182
+ }
1183
+ function _object_spread_props(target, source) {
1184
+ source = source != null ? source : {};
1185
+ if (Object.getOwnPropertyDescriptors) {
1186
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1187
+ } else {
1188
+ ownKeys(Object(source)).forEach(function(key) {
1189
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1190
+ });
1191
+ }
1192
+ return target;
1193
+ }
1194
+ function _ts_generator(thisArg, body) {
1195
+ var f, y, t, _ = {
1196
+ label: 0,
1197
+ sent: function() {
1198
+ if (t[0] & 1) throw t[1];
1199
+ return t[1];
1200
+ },
1201
+ trys: [],
1202
+ ops: []
1203
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1204
+ return d(g, "next", {
1205
+ value: verb(0)
1206
+ }), d(g, "throw", {
1207
+ value: verb(1)
1208
+ }), d(g, "return", {
1209
+ value: verb(2)
1210
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1211
+ value: function() {
1212
+ return this;
1213
+ }
1214
+ }), g;
1215
+ function verb(n) {
1216
+ return function(v) {
1217
+ return step([
1218
+ n,
1219
+ v
1220
+ ]);
1221
+ };
1222
+ }
1223
+ function step(op) {
1224
+ if (f) throw new TypeError("Generator is already executing.");
1225
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
1226
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1227
+ if (y = 0, t) op = [
1228
+ op[0] & 2,
1229
+ t.value
1230
+ ];
1231
+ switch(op[0]){
1232
+ case 0:
1233
+ case 1:
1234
+ t = op;
1235
+ break;
1236
+ case 4:
1237
+ _.label++;
1238
+ return {
1239
+ value: op[1],
1240
+ done: false
1241
+ };
1242
+ case 5:
1243
+ _.label++;
1244
+ y = op[1];
1245
+ op = [
1246
+ 0
1247
+ ];
1248
+ continue;
1249
+ case 7:
1250
+ op = _.ops.pop();
1251
+ _.trys.pop();
1252
+ continue;
1253
+ default:
1254
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1255
+ _ = 0;
1256
+ continue;
1257
+ }
1258
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1259
+ _.label = op[1];
1260
+ break;
1261
+ }
1262
+ if (op[0] === 6 && _.label < t[1]) {
1263
+ _.label = t[1];
1264
+ t = op;
1265
+ break;
1266
+ }
1267
+ if (t && _.label < t[2]) {
1268
+ _.label = t[2];
1269
+ _.ops.push(op);
1270
+ break;
1271
+ }
1272
+ if (t[2]) _.ops.pop();
1273
+ _.trys.pop();
1274
+ continue;
1275
+ }
1276
+ op = body.call(thisArg, _);
1277
+ } catch (e) {
1278
+ op = [
1279
+ 6,
1280
+ e
1281
+ ];
1282
+ y = 0;
1283
+ } finally{
1284
+ f = t = 0;
1285
+ }
1286
+ if (op[0] & 5) throw op[1];
1287
+ return {
1288
+ value: op[0] ? op[1] : void 0,
1289
+ done: true
1290
+ };
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Maps stored connection credentials to a {@link ZohoAccessToken}.
1295
+ *
1296
+ * @param credentials - The credentials stored for the `zoho` provider.
1297
+ * @returns The equivalent Zoho access token, or null when the credentials cannot form one.
1298
+ */ function zohoAccessTokenFromUserExternalConnectionCredentials(credentials) {
1299
+ var _credentials_extra;
1300
+ var expiresAt = safeToJsDate(credentials === null || credentials === void 0 ? void 0 : credentials.expiresAt);
1301
+ var apiDomain = credentials === null || credentials === void 0 ? void 0 : (_credentials_extra = credentials.extra) === null || _credentials_extra === void 0 ? void 0 : _credentials_extra[ZOHO_EXTRA_API_DOMAIN_KEY];
1302
+ var result;
1303
+ // the api domain is required, not incidental: a Zoho access token is only usable against the domain
1304
+ // it was issued for, so a token synthesized without one would be sent to the wrong host
1305
+ if (credentials != null && expiresAt != null && apiDomain != null) {
1306
+ var _ref, _credentials_scopes;
1307
+ var issuedAt = safeToJsDate(credentials.issuedAt);
1308
+ var expiresIn = Math.round((expiresAt.getTime() - ((_ref = issuedAt === null || issuedAt === void 0 ? void 0 : issuedAt.getTime()) !== null && _ref !== void 0 ? _ref : Date.now())) / MS_IN_SECOND);
1309
+ result = {
1310
+ accessToken: credentials.accessToken,
1311
+ // joined on the same delimiter `zohoOAuthScopesFromScopeString` split them with
1312
+ scope: ((_credentials_scopes = credentials.scopes) !== null && _credentials_scopes !== void 0 ? _credentials_scopes : []).join(ZOHO_OAUTH_SCOPE_DELIMITER),
1313
+ apiDomain: String(apiDomain),
1314
+ expiresIn: expiresIn,
1315
+ expiresAt: expiresAt
1316
+ };
1317
+ }
1318
+ return result;
1319
+ }
1320
+ /**
1321
+ * Creates a {@link ZohoAccessTokenCache} backed by a user's UserExternalConnection pair.
1322
+ *
1323
+ * The Zoho counterpart of `userExternalConnectionCalcomAccessTokenCache`, and the per-user counterpart
1324
+ * of `firebaseZohoAccountsAccessTokenCacheService` — which caches the APP's token in a `SystemState`
1325
+ * document and has no notion of a user.
1326
+ *
1327
+ * Zoho does not rotate refresh tokens, so unlike Cal.com there is no token here that is destroyed by
1328
+ * being used. What this buys instead is that a renewed access token is shared: without it every Cloud
1329
+ * Function instance holds its own in-memory token and refreshes independently, so a user's grant is
1330
+ * exercised once per instance per hour rather than once per hour.
1331
+ *
1332
+ * @param config - The accessor, the actions, and the user the cache is for.
1333
+ * @returns A ZohoAccessTokenCache reading and writing the user's connection pair.
1334
+ */ function userExternalConnectionZohoAccessTokenCache(config) {
1335
+ var accessor = config.accessor, actions = config.actions, uid = config.uid;
1336
+ var providerType = ZOHO_USER_EXTERNAL_CONNECTION_PROVIDER_TYPE;
1337
+ var connection = accessor.accessorForUser({
1338
+ uid: uid
1339
+ })(providerType);
1340
+ function loadCachedToken() {
1341
+ return _async_to_generator(function() {
1342
+ var credentials;
1343
+ return _ts_generator(this, function(_state) {
1344
+ switch(_state.label){
1345
+ case 0:
1346
+ return [
1347
+ 4,
1348
+ connection.readUserExternalConnectionCredentials()
1349
+ ];
1350
+ case 1:
1351
+ credentials = _state.sent();
1352
+ return [
1353
+ 2,
1354
+ zohoAccessTokenFromUserExternalConnectionCredentials(credentials)
1355
+ ];
1356
+ }
1357
+ });
1358
+ })();
1359
+ }
1360
+ function updateCachedToken(accessToken) {
1361
+ return _async_to_generator(function() {
1362
+ var previous, now, refreshed;
1363
+ return _ts_generator(this, function(_state) {
1364
+ switch(_state.label){
1365
+ case 0:
1366
+ return [
1367
+ 4,
1368
+ connection.readUserExternalConnectionCredentials()
1369
+ ];
1370
+ case 1:
1371
+ previous = _state.sent();
1372
+ if (previous == null) {
1373
+ // nothing to merge onto, and a Zoho access token carries no refresh token — writing it alone
1374
+ // would store credentials that can never be renewed
1375
+ return [
1376
+ 2
1377
+ ];
1378
+ }
1379
+ now = new Date();
1380
+ refreshed = _object_spread_props(_object_spread({}, previous), {
1381
+ accessToken: accessToken.accessToken,
1382
+ issuedAt: now.toISOString(),
1383
+ expiresAt: accessToken.expiresAt.toISOString(),
1384
+ extra: _object_spread_props(_object_spread({}, previous.extra), _define_property$1({}, ZOHO_EXTRA_API_DOMAIN_KEY, accessToken.apiDomain))
1385
+ });
1386
+ return [
1387
+ 4,
1388
+ actions.refreshUserExternalConnectionCredentials({
1389
+ uid: uid,
1390
+ providerType: providerType,
1391
+ credentials: mergeRefreshedUserExternalConnectionCredentials({
1392
+ previous: previous,
1393
+ refreshed: refreshed
1394
+ })
1395
+ })
1396
+ ];
1397
+ case 2:
1398
+ _state.sent();
1399
+ return [
1400
+ 2
1401
+ ];
1402
+ }
1403
+ });
1404
+ })();
1405
+ }
1406
+ function clearCachedToken() {
1407
+ return _async_to_generator(function() {
1408
+ var previous;
1409
+ return _ts_generator(this, function(_state) {
1410
+ switch(_state.label){
1411
+ case 0:
1412
+ return [
1413
+ 4,
1414
+ connection.readUserExternalConnectionCredentials()
1415
+ ];
1416
+ case 1:
1417
+ previous = _state.sent();
1418
+ if (previous == null) {
1419
+ return [
1420
+ 2
1421
+ ];
1422
+ }
1423
+ // deliberately NOT a disconnect. Zoho's factory clears the cache to force its next call to refresh,
1424
+ // which is a statement about the ACCESS token only — dropping the refresh token here would turn a
1425
+ // routine cache invalidation into a connection the user has to re-authorize.
1426
+ return [
1427
+ 4,
1428
+ actions.refreshUserExternalConnectionCredentials({
1429
+ uid: uid,
1430
+ providerType: providerType,
1431
+ credentials: _object_spread_props(_object_spread({}, previous), {
1432
+ accessToken: '',
1433
+ expiresAt: new Date(0).toISOString()
1434
+ })
1435
+ })
1436
+ ];
1437
+ case 2:
1438
+ _state.sent();
1439
+ return [
1440
+ 2
1441
+ ];
1442
+ }
1443
+ });
1444
+ })();
1445
+ }
1446
+ return {
1447
+ loadCachedToken: loadCachedToken,
1448
+ updateCachedToken: updateCachedToken,
1449
+ clearCachedToken: clearCachedToken
1450
+ };
1451
+ }
1452
+
1453
+ function _assert_this_initialized(self) {
1454
+ if (self === void 0) {
1455
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1456
+ }
1457
+ return self;
1458
+ }
1459
+ function _call_super(_this, derived, args) {
1460
+ derived = _get_prototype_of(derived);
1461
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
1462
+ }
1463
+ function _class_call_check(instance, Constructor) {
1464
+ if (!(instance instanceof Constructor)) {
1465
+ throw new TypeError("Cannot call a class as a function");
1466
+ }
1467
+ }
1468
+ function _define_property(obj, key, value) {
1469
+ if (key in obj) {
1470
+ Object.defineProperty(obj, key, {
1471
+ value: value,
1472
+ enumerable: true,
1473
+ configurable: true,
1474
+ writable: true
1475
+ });
1476
+ } else {
1477
+ obj[key] = value;
1478
+ }
1479
+ return obj;
1480
+ }
1481
+ function _get_prototype_of(o) {
1482
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
1483
+ return o.__proto__ || Object.getPrototypeOf(o);
1484
+ };
1485
+ return _get_prototype_of(o);
1486
+ }
1487
+ function _inherits(subClass, superClass) {
1488
+ if (typeof superClass !== "function" && superClass !== null) {
1489
+ throw new TypeError("Super expression must either be null or a function");
1490
+ }
1491
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
1492
+ constructor: {
1493
+ value: subClass,
1494
+ writable: true,
1495
+ configurable: true
1496
+ }
1497
+ });
1498
+ if (superClass) _set_prototype_of(subClass, superClass);
1499
+ }
1500
+ function _possible_constructor_return(self, call) {
1501
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
1502
+ return call;
1503
+ }
1504
+ return _assert_this_initialized(self);
1505
+ }
1506
+ function _set_prototype_of(o, p) {
1507
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
1508
+ o.__proto__ = p;
1509
+ return o;
1510
+ };
1511
+ return _set_prototype_of(o, p);
1512
+ }
1513
+ function _type_of(obj) {
1514
+ "@swc/helpers - typeof";
1515
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1516
+ }
1517
+ function _is_native_reflect_construct() {
1518
+ try {
1519
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
1520
+ } catch (_) {}
1521
+ return (_is_native_reflect_construct = function() {
1522
+ return !!result;
1523
+ })();
1524
+ }
1525
+ /**
1526
+ * Endpoints for the Zoho external-connection authorization-code handoff.
1527
+ *
1528
+ * Mounted at `/oauth/zoho`, matching the Angular registry's default authorize path of
1529
+ * `/oauth/<providerType>/authorize`. Hosting rewrites do not strip the path, so this prefix is the
1530
+ * public path — but an app with a global API route prefix must ALSO exclude these routes from it via
1531
+ * {@link ZOHO_USER_EXTERNAL_CONNECTION_OAUTH_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE}, or they land under
1532
+ * that prefix instead and no longer match the redirect URI registered with Zoho.
1533
+ *
1534
+ * The `authorize` and `callback` routes come from the base class, so this declares only where they
1535
+ * mount and which service serves them.
1536
+ */ var ZohoUserExternalConnectionOAuthController = /*#__PURE__*/ function(AbstractUserExternalConnectionOAuthController) {
1537
+ _inherits(ZohoUserExternalConnectionOAuthController, AbstractUserExternalConnectionOAuthController);
1538
+ function ZohoUserExternalConnectionOAuthController(oauthService) {
1539
+ _class_call_check(this, ZohoUserExternalConnectionOAuthController);
1540
+ var _this;
1541
+ _this = _call_super(this, ZohoUserExternalConnectionOAuthController), _define_property(_this, "oauthService", void 0);
1542
+ _this.oauthService = oauthService;
1543
+ return _this;
1544
+ }
1545
+ return ZohoUserExternalConnectionOAuthController;
1546
+ }(AbstractUserExternalConnectionOAuthController);
1547
+ ZohoUserExternalConnectionOAuthController = __decorate([
1548
+ Controller(ZOHO_USER_EXTERNAL_CONNECTION_OAUTH_CONTROLLER_PATH),
1549
+ __param(0, Inject(ZohoUserExternalConnectionOAuthService))
1550
+ ], ZohoUserExternalConnectionOAuthController);
1551
+
1552
+ function _array_like_to_array(arr, len) {
1553
+ if (len == null || len > arr.length) len = arr.length;
1554
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1555
+ return arr2;
1556
+ }
1557
+ function _array_without_holes(arr) {
1558
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
1559
+ }
1560
+ function _iterable_to_array(iter) {
1561
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1562
+ }
1563
+ function _non_iterable_spread() {
1564
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1565
+ }
1566
+ function _to_consumable_array(arr) {
1567
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
1568
+ }
1569
+ function _unsupported_iterable_to_array(o, minLen) {
1570
+ if (!o) return;
1571
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
1572
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1573
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1574
+ if (n === "Map" || n === "Set") return Array.from(n);
1575
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1576
+ }
1577
+ /**
1578
+ * Convenience function used to generate ModuleMetadata for an app's Zoho external-connection OAuth
1579
+ * module.
1580
+ *
1581
+ * Opt-in: importing the Zoho OAuth module alone never mounts HTTP routes, so an app that only makes
1582
+ * outbound Zoho calls exposes no endpoints.
1583
+ *
1584
+ * The importing module must also supply `UserExternalConnectionServerActions` and
1585
+ * `UserExternalConnectionStateCoder` — both exported by `appUserExternalConnectionModuleMetadata`,
1586
+ * so pass that module in `imports`.
1587
+ *
1588
+ * @param config - The module metadata configuration.
1589
+ * @returns NestJS ModuleMetadata mounting the Zoho connect endpoints.
1590
+ */ function appZohoUserExternalConnectionOAuthModuleMetadata(config) {
1591
+ var dependencyModule = config.dependencyModule, successPath = config.successPath, failurePath = config.failurePath, scopes = config.scopes, accountsApiUrl = config.accountsApiUrl, imports = config.imports, exports = config.exports, providers = config.providers;
1592
+ var dependencyModuleImport = dependencyModule ? [
1593
+ dependencyModule
1594
+ ] : [];
1595
+ return {
1596
+ imports: [
1597
+ ConfigModule
1598
+ ].concat(_to_consumable_array(dependencyModuleImport), _to_consumable_array(imports !== null && imports !== void 0 ? imports : [])),
1599
+ controllers: [
1600
+ ZohoUserExternalConnectionOAuthController
1601
+ ],
1602
+ exports: [
1603
+ ZohoUserExternalConnectionOAuthService
1604
+ ].concat(_to_consumable_array(exports !== null && exports !== void 0 ? exports : [])),
1605
+ providers: [
1606
+ {
1607
+ provide: ZohoUserExternalConnectionOAuthServiceConfig,
1608
+ inject: [
1609
+ FirebaseServerEnvService
1610
+ ],
1611
+ useFactory: function useFactory(envService) {
1612
+ return zohoUserExternalConnectionOAuthServiceConfigFactory({
1613
+ envService: envService,
1614
+ successPath: successPath,
1615
+ failurePath: failurePath,
1616
+ scopes: scopes,
1617
+ accountsApiUrl: accountsApiUrl
1618
+ });
1619
+ }
1620
+ },
1621
+ ZohoUserExternalConnectionOAuthService
1622
+ ].concat(_to_consumable_array(providers !== null && providers !== void 0 ? providers : []))
1623
+ };
1624
+ }
1625
+
1626
+ export { DEFAULT_ZOHO_OAUTH_SCOPES, ZOHO_ACCESS_TOKEN_SYSTEM_STATE_TYPE, ZOHO_EXTRA_ACCOUNTS_SERVER_KEY, ZOHO_EXTRA_API_DOMAIN_KEY, ZOHO_EXTRA_LOCATION_KEY, ZOHO_OAUTH_CALLBACK_ACCOUNTS_SERVER_PARAM, ZOHO_OAUTH_CALLBACK_LOCATION_PARAM, ZOHO_USER_EXTERNAL_CONNECTION_OAUTH_CONTROLLER_PATH, ZOHO_USER_EXTERNAL_CONNECTION_OAUTH_ROUTES_FOR_GLOBAL_ROUTE_EXCLUDE, ZohoUserExternalConnectionOAuthController, ZohoUserExternalConnectionOAuthService, ZohoUserExternalConnectionOAuthServiceConfig, appZohoUserExternalConnectionOAuthModuleMetadata, firebaseZohoAccountsAccessTokenCacheService, loadZohoAccessTokenSystemState, userExternalConnectionZohoAccessTokenCache, zohoAccessTokenFromUserExternalConnectionCredentials, zohoAccessTokenSystemStateDataConverter, zohoAccessTokenSystemStateEmbeddedTokenConverter, zohoUserExternalConnectionCredentials, zohoUserExternalConnectionOAuthServiceConfigFactory };