emailengine-app 2.88.0 → 2.90.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 (79) hide show
  1. package/.ncurc.js +36 -45
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +77 -11
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/node-version.js +99 -12
  38. package/lib/oauth/gmail.js +39 -120
  39. package/lib/oauth/http-request.js +195 -0
  40. package/lib/oauth/mail-ru.js +24 -58
  41. package/lib/oauth/outlook.js +37 -137
  42. package/lib/oauth/pubsub/google.js +176 -117
  43. package/lib/oauth2-apps.js +440 -463
  44. package/lib/openapi/build-document.js +10 -10
  45. package/lib/read-env-value.js +1 -1
  46. package/lib/route-descriptors.js +78 -0
  47. package/lib/schemas.js +10 -1
  48. package/lib/sentry-integrations.js +299 -0
  49. package/lib/sentry.js +75 -27
  50. package/lib/settings.js +4 -1
  51. package/lib/sso-routes.js +249 -0
  52. package/lib/sso.js +29 -6
  53. package/lib/tools.js +5 -4
  54. package/lib/ui-routes/account-edit-form.js +198 -0
  55. package/lib/ui-routes/account-page.js +241 -0
  56. package/lib/ui-routes/account-routes.js +12 -318
  57. package/lib/ui-routes/auth-routes.js +10 -10
  58. package/lib/ui-routes/dashboard-routes.js +4 -0
  59. package/lib/ui-view-context.js +328 -0
  60. package/lib/utils/public-suffix.js +22 -101
  61. package/lib/web-safe-html.js +70 -13
  62. package/lib/worker-metrics.js +82 -0
  63. package/list-generate.js +57 -23
  64. package/package.json +34 -33
  65. package/sbom.json +380 -1612
  66. package/scripts/refresh-test-tokens.js +1 -1
  67. package/server.js +351 -707
  68. package/static/css/flyonui.css +1 -1
  69. package/static/css/src/app.tailwind.css +18 -0
  70. package/static/js/ee-client.js +2619 -645
  71. package/static/js/ui.js +12 -2
  72. package/static/licenses.html +1055 -969
  73. package/translations/messages.pot +71 -60
  74. package/views/accounts/browse.hbs +19 -1
  75. package/views/dashboard.hbs +9 -0
  76. package/views/upgrade.hbs +25 -0
  77. package/workers/api.js +20 -451
  78. package/data/public_suffix_list.dat +0 -16597
  79. package/lib/net-tos-guard.js +0 -42
@@ -155,6 +155,31 @@ function getExternalAccountSigner(id, externalAccount) {
155
155
  const PUBSUB_PERM_MANAGE = 'Service client does not have permission to manage Pub/Sub topics. Grant the service user the "Pub/Sub Admin" role.';
156
156
  const PUBSUB_PERM_VIEW = 'Service client does not have permission to view Pub/Sub topics. Grant the service user the "Pub/Sub Admin" role.';
157
157
 
158
+ // The binding Gmail push needs on the topic: Gmail's own service account as a publisher
159
+ const GMAIL_PUSH_MEMBER = 'serviceAccount:gmail-api-push@system.gserviceaccount.com';
160
+ const GMAIL_PUBLISHER_ROLE = 'roles/pubsub.publisher';
161
+
162
+ // A new object every time: the binding is sent to Google, stored on the app and returned
163
+ const gmailPublisherBinding = () => ({ members: [GMAIL_PUSH_MEMBER], role: GMAIL_PUBLISHER_ROLE });
164
+
165
+ // A Pub/Sub duration such as "2678400s" in seconds, null when absent or unparseable
166
+ function ttlSeconds(ttl) {
167
+ let n = ttl ? parseInt(ttl, 10) : NaN;
168
+ return Number.isFinite(n) ? n : null;
169
+ }
170
+
171
+ // The auth flag for a 403 on the topic lookup, the first request a new project sees: a project
172
+ // that never enabled the Pub/Sub API gets told so, with Google's own explanation
173
+ function topicLookupAuthFlag(err) {
174
+ if (/Cloud Pub\/Sub API has not been used in project/.test(err?.oauthRequest?.response?.error?.message)) {
175
+ return {
176
+ message: 'Enable the Cloud Pub/Sub API for your project before using the service client. Check the server response below for details.',
177
+ description: err?.oauthRequest?.response?.error?.message
178
+ };
179
+ }
180
+ return { message: PUBSUB_PERM_MANAGE };
181
+ }
182
+
158
183
  const OAUTH_PROVIDERS = {
159
184
  gmail: 'Gmail',
160
185
  gmailService: 'Gmail Service Accounts',
@@ -288,6 +313,116 @@ function oauth2ProviderData(provider, selector) {
288
313
  return providerData;
289
314
  }
290
315
 
316
+ // Refuses to build a client from an app whose credentials are not set up
317
+ function assertCredentials(ready, providerLabel) {
318
+ if (!ready) {
319
+ let error = Boom.boomify(new Error(`OAuth2 credentials not set up for ${providerLabel}`), { statusCode: 400 });
320
+ throw error;
321
+ }
322
+ }
323
+
324
+ // How getClient() builds the client of each provider from its app record: the client class and
325
+ // the options read from the record. getClient() adds the flag setter and the caller's options,
326
+ // which win the merge.
327
+ const CLIENT_BUILDERS = {
328
+ async gmail(apps, appData) {
329
+ let clientId = appData.clientId;
330
+ let clientSecret = appData.clientSecret ? await apps.decrypt(appData.clientSecret) : null;
331
+ let redirectUrl = appData.redirectUrl;
332
+ let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, GMAIL_SCOPES, appData.skipScopes);
333
+
334
+ assertCredentials(clientId && clientSecret && redirectUrl, 'Gmail');
335
+
336
+ return {
337
+ Client: GmailOauth,
338
+ opts: {
339
+ clientId,
340
+ clientSecret,
341
+ redirectUrl,
342
+ scopes,
343
+ googleProjectId: appData.googleProjectId,
344
+ workspaceAccounts: appData.googleWorkspaceAccounts
345
+ }
346
+ };
347
+ },
348
+
349
+ async gmailService(apps, appData, id) {
350
+ let serviceClient = appData.serviceClient;
351
+ let authMethod = normalizeAuthMethod(appData.authMethod);
352
+ let serviceKey = appData.serviceKey ? await apps.decrypt(appData.serviceKey) : null;
353
+ let externalAccount = appData.externalAccount ? await apps.decrypt(appData.externalAccount) : null;
354
+
355
+ let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, GMAIL_SCOPES, appData.skipScopes);
356
+
357
+ // A method with no stored credential (the attached service account) is always ready
358
+ let credential = SERVICE_AUTH_CREDENTIALS[authMethod];
359
+ assertCredentials(!credential || (serviceClient && !!{ serviceKey, externalAccount }[credential]), 'Gmail');
360
+
361
+ return {
362
+ Client: GmailOauth,
363
+ opts: {
364
+ serviceClient,
365
+ authMethod,
366
+ serviceKey,
367
+ externalAccount,
368
+ externalAccountSigner: authMethod === 'externalAccount' ? getExternalAccountSigner(id, externalAccount) : undefined,
369
+ googleProjectId: appData.googleProjectId,
370
+ serviceClientEmail: appData.serviceClientEmail,
371
+ scopes,
372
+ workspaceAccounts: appData.googleWorkspaceAccounts
373
+ }
374
+ };
375
+ },
376
+
377
+ async outlook(apps, appData) {
378
+ let authority = await appData.authority;
379
+ let clientId = appData.clientId;
380
+ let clientSecret = appData.clientSecret ? await apps.decrypt(appData.clientSecret) : null;
381
+ let redirectUrl = appData.redirectUrl;
382
+
383
+ let cloud = appData.cloud || 'global';
384
+
385
+ let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, outlookScopes(cloud), appData.skipScopes);
386
+
387
+ assertCredentials(clientId && clientSecret && authority && redirectUrl, 'Outlook (delegated)');
388
+
389
+ return {
390
+ Client: OutlookOauth,
391
+ opts: { authority, clientId, clientSecret, redirectUrl, scopes, cloud }
392
+ };
393
+ },
394
+
395
+ async outlookService(apps, appData) {
396
+ let authority = appData.authority;
397
+ let clientId = appData.clientId;
398
+ let clientSecret = appData.clientSecret ? await apps.decrypt(appData.clientSecret) : null;
399
+
400
+ let cloud = appData.cloud || 'global';
401
+
402
+ assertCredentials(clientId && clientSecret && authority, 'Outlook (application)');
403
+
404
+ // Client credentials use {apiBase}/.default scope; per-scope config is not applicable
405
+ return {
406
+ Client: OutlookOauth,
407
+ opts: { authority, clientId, clientSecret, cloud, provider: 'outlookService', useClientCredentials: true }
408
+ };
409
+ },
410
+
411
+ async mailRu(apps, appData) {
412
+ let clientId = appData.clientId;
413
+ let clientSecret = appData.clientSecret ? await apps.decrypt(appData.clientSecret) : null;
414
+ let redirectUrl = appData.redirectUrl;
415
+ let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, MAIL_RU_SCOPES, appData.skipScopes);
416
+
417
+ assertCredentials(clientId && clientSecret && redirectUrl, 'Mail.ru');
418
+
419
+ return {
420
+ Client: MailRuOauth,
421
+ opts: { clientId, clientSecret, redirectUrl, scopes }
422
+ };
423
+ }
424
+ };
425
+
291
426
  class OAuth2AppsHandler {
292
427
  constructor(options) {
293
428
  this.options = options || {};
@@ -1251,41 +1386,102 @@ class OAuth2AppsHandler {
1251
1386
 
1252
1387
  // ensurePubsub() under the per-app Pub/Sub lock
1253
1388
  async ensurePubsubLocked({ appData, topicName, subscriptionName, desiredExpirationPolicy }) {
1254
- const topicUrl = `https://pubsub.googleapis.com/v1/${topicName}`;
1255
- const subscriptionUrl = `https://pubsub.googleapis.com/v1/${subscriptionName}`;
1256
-
1257
- const member = 'serviceAccount:gmail-api-push@system.gserviceaccount.com';
1258
- const role = 'roles/pubsub.publisher';
1259
-
1260
- let results = {};
1261
- let ttlPatchFailed = null;
1389
+ // The state of one run, shared by its steps
1390
+ const run = {
1391
+ appData,
1392
+ topicName,
1393
+ subscriptionName,
1394
+ desiredExpirationPolicy,
1395
+ topicUrl: `https://pubsub.googleapis.com/v1/${topicName}`,
1396
+ subscriptionUrl: `https://pubsub.googleapis.com/v1/${subscriptionName}`,
1397
+ results: {},
1398
+ ttlPatchFailed: null
1399
+ };
1262
1400
 
1263
1401
  // Re-read inside the lock so the "persist only if absent" guards below act on the
1264
1402
  // current state, not the caller's pre-lock snapshot (which can be stale after a
1265
1403
  // concurrent ensurePubsub run). Falls back to the passed-in data if the app was
1266
1404
  // deleted while waiting for the lock (preserves the prior proceed-anyway behavior).
1267
- let current = (await this.get(appData.id)) || appData;
1268
-
1269
- // Record a marker for a Pub/Sub resource that already existed in GCP (adopted, not
1270
- // created by us): mark it unmanaged so deletion never removes it, and surface it in
1271
- // results on first adoption so the create/update route restarts the pull worker. The
1272
- // !current guard keeps re-runs no-ops (no redundant writes or restarts).
1273
- const adoptExistingResource = async (key, value) => {
1274
- if (!current[key]) {
1275
- await this.update(appData.id, { [key]: value, [`${key}Managed`]: false }, { partial: true });
1276
- results[key] = value;
1277
- }
1278
- };
1405
+ // Read once, before any adoption: a resource adopted in this same run still counts as
1406
+ // unmanaged further down.
1407
+ run.current = (await this.get(appData.id)) || appData;
1279
1408
 
1280
- let client = await this.getClient(appData.id);
1409
+ run.client = await this.getClient(appData.id);
1281
1410
 
1282
1411
  // Step 1. Get access token for service client
1283
- let accessToken = await this.getServiceAccessToken(appData, client);
1284
- if (!accessToken) {
1412
+ run.accessToken = await this.getServiceAccessToken(appData, run.client);
1413
+ if (!run.accessToken) {
1285
1414
  throw new Error('Failed to get access token');
1286
1415
  }
1287
1416
 
1288
1417
  // Step 2. Ensure topic
1418
+ await this.ensurePubsubTopic(run);
1419
+
1420
+ // Step 3. Set up subscriber
1421
+ await this.ensurePubsubSubscription(run);
1422
+
1423
+ // Step 4. Grant access to Gmail publisher
1424
+ await this.ensurePublisherBinding(run);
1425
+
1426
+ await this.finalizePubsubMeta(run);
1427
+
1428
+ return run.results;
1429
+ }
1430
+
1431
+ /**
1432
+ * The one classification of a failed Pub/Sub request every step of ensurePubsub() shares. A
1433
+ * transient network error is logged with the step's own message and rethrown, a 403 records
1434
+ * the step's auth flag (fire-and-forget, so the original error flow is unchanged) and is
1435
+ * rethrown, and a 404 or 409 is handed to the step when it has a way to continue. Anything
1436
+ * else is rethrown.
1437
+ *
1438
+ * @param {Object} appData
1439
+ * @param {Error} err - the failed request
1440
+ * @param {Object} opts
1441
+ * @param {String} opts.networkMsg - log message for a transient network error
1442
+ * @param {Object} opts.authFlag - auth flag to record on a 403
1443
+ * @param {Function} [opts.onNotFound] - async continuation for a 404
1444
+ * @param {Function} [opts.onConflict] - async continuation for a 409
1445
+ */
1446
+ async handlePubsubError(appData, err, { networkMsg, authFlag, onNotFound, onConflict }) {
1447
+ if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1448
+ logger.warn({ msg: networkMsg, app: appData.id, code: err.code });
1449
+ throw err;
1450
+ }
1451
+
1452
+ switch (err?.oauthRequest?.response?.error?.code) {
1453
+ case 403:
1454
+ // no permissions
1455
+ this.setMetaFireAndForget(appData.id, { authFlag, ttlWarning: null });
1456
+ throw err;
1457
+ case 404:
1458
+ if (onNotFound) {
1459
+ return await onNotFound();
1460
+ }
1461
+ throw err;
1462
+ case 409:
1463
+ if (onConflict) {
1464
+ return await onConflict();
1465
+ }
1466
+ throw err;
1467
+ default:
1468
+ throw err;
1469
+ }
1470
+ }
1471
+
1472
+ // Record a marker for a Pub/Sub resource that already existed in GCP (adopted, not
1473
+ // created by us): mark it unmanaged so deletion never removes it, and surface it in
1474
+ // results on first adoption so the create/update route restarts the pull worker. The
1475
+ // !current guard keeps re-runs no-ops (no redundant writes or restarts).
1476
+ async adoptPubsubResource(run, key, value) {
1477
+ if (!run.current[key]) {
1478
+ await this.update(run.appData.id, { [key]: value, [`${key}Managed`]: false }, { partial: true });
1479
+ run.results[key] = value;
1480
+ }
1481
+ }
1482
+
1483
+ async ensurePubsubTopic(run) {
1484
+ const { appData, client, accessToken, topicUrl, topicName } = run;
1289
1485
  try {
1290
1486
  // fails if topic does not exist
1291
1487
  await client.request(accessToken, topicUrl, 'GET');
@@ -1295,86 +1491,56 @@ class OAuth2AppsHandler {
1295
1491
  */
1296
1492
 
1297
1493
  // Adopt a pre-existing topic so the Gmail watch can arm (kept unmanaged - we did not create it).
1298
- await adoptExistingResource('pubSubTopic', topicName);
1494
+ await this.adoptPubsubResource(run, 'pubSubTopic', topicName);
1299
1495
  } catch (err) {
1300
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1301
- logger.warn({ msg: 'Network error checking Pub/Sub topic', app: appData.id, code: err.code });
1302
- throw err;
1496
+ await this.handlePubsubError(appData, err, {
1497
+ networkMsg: 'Network error checking Pub/Sub topic',
1498
+ authFlag: topicLookupAuthFlag(err),
1499
+ onNotFound: () => this.createPubsubTopic(run, err)
1500
+ });
1501
+ }
1502
+ }
1503
+
1504
+ async createPubsubTopic(run, lookupErr) {
1505
+ const { appData, client, accessToken, topicUrl, topicName } = run;
1506
+
1507
+ // does not exist
1508
+ logger.info({ msg: 'Topic does not exist', app: appData.id, topic: topicName });
1509
+ try {
1510
+ let topicCreateRes = await client.request(accessToken, topicUrl, 'PUT', Buffer.alloc(0));
1511
+ /*
1512
+ {name: 'projects/...'}
1513
+ */
1514
+ if (!topicCreateRes?.name) {
1515
+ throw new Error('Topic was not created', { cause: lookupErr });
1303
1516
  }
1304
- switch (err?.oauthRequest?.response?.error?.code) {
1305
- case 403:
1306
- // no permissions
1307
- if (/Cloud Pub\/Sub API has not been used in project/.test(err?.oauthRequest?.response?.error?.message)) {
1308
- this.setMetaFireAndForget(appData.id, {
1309
- authFlag: {
1310
- message:
1311
- 'Enable the Cloud Pub/Sub API for your project before using the service client. Check the server response below for details.',
1312
- description: err?.oauthRequest?.response?.error?.message
1313
- },
1314
- ttlWarning: null
1315
- });
1316
- } else {
1317
- this.setMetaFireAndForget(appData.id, {
1318
- authFlag: { message: PUBSUB_PERM_MANAGE },
1319
- ttlWarning: null
1320
- });
1321
- }
1322
1517
 
1323
- throw err;
1324
- case 404: {
1325
- // does not exist
1326
- logger.info({ msg: 'Topic does not exist', app: appData.id, topic: topicName });
1327
- try {
1328
- let topicCreateRes = await client.request(accessToken, topicUrl, 'PUT', Buffer.alloc(0));
1329
- /*
1330
- {name: 'projects/...'}
1331
- */
1332
- if (!topicCreateRes?.name) {
1333
- throw new Error('Topic was not created', { cause: err });
1334
- }
1518
+ await this.update(
1519
+ appData.id,
1520
+ {
1521
+ pubSubTopic: topicName,
1522
+ // EmailEngine created this topic, so it may delete it on app removal.
1523
+ pubSubTopicManaged: true
1524
+ },
1525
+ { partial: true }
1526
+ );
1335
1527
 
1336
- await this.update(
1337
- appData.id,
1338
- {
1339
- pubSubTopic: topicName,
1340
- // EmailEngine created this topic, so it may delete it on app removal.
1341
- pubSubTopicManaged: true
1342
- },
1343
- { partial: true }
1344
- );
1345
-
1346
- results.pubSubTopic = topicName;
1347
- } catch (err) {
1348
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1349
- logger.warn({ msg: 'Network error creating Pub/Sub topic', app: appData.id, code: err.code });
1350
- throw err;
1351
- }
1352
- switch (err?.oauthRequest?.response?.error?.code) {
1353
- case 403:
1354
- // no permissions
1355
- this.setMetaFireAndForget(appData.id, {
1356
- authFlag: { message: PUBSUB_PERM_MANAGE },
1357
- ttlWarning: null
1358
- });
1359
- throw err;
1360
- case 409:
1361
- // already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
1362
- logger.info({ msg: 'Topic already exists', app: appData.id, topic: topicName });
1363
- await adoptExistingResource('pubSubTopic', topicName);
1364
- break;
1365
- default:
1366
- throw err;
1367
- }
1368
- }
1369
- break;
1528
+ run.results.pubSubTopic = topicName;
1529
+ } catch (err) {
1530
+ await this.handlePubsubError(appData, err, {
1531
+ networkMsg: 'Network error creating Pub/Sub topic',
1532
+ authFlag: { message: PUBSUB_PERM_MANAGE },
1533
+ onConflict: async () => {
1534
+ // already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
1535
+ logger.info({ msg: 'Topic already exists', app: appData.id, topic: topicName });
1536
+ await this.adoptPubsubResource(run, 'pubSubTopic', topicName);
1370
1537
  }
1371
- default:
1372
- throw err;
1373
- }
1538
+ });
1374
1539
  }
1540
+ }
1375
1541
 
1376
- // Step 3. Set up subscriber
1377
-
1542
+ async ensurePubsubSubscription(run) {
1543
+ const { appData, client, accessToken, subscriptionUrl, subscriptionName } = run;
1378
1544
  try {
1379
1545
  // fails if topic does not exist
1380
1546
  let subscriptionData = await client.request(accessToken, subscriptionUrl, 'GET');
@@ -1385,164 +1551,157 @@ class OAuth2AppsHandler {
1385
1551
 
1386
1552
  // Adopt a pre-existing subscription so the pull worker recognizes it (also stops the
1387
1553
  // recovery loop in lib/oauth/pubsub/google.js); kept unmanaged - we did not create it.
1388
- await adoptExistingResource('pubSubSubscription', subscriptionName);
1389
-
1390
- // Patch existing subscription's expiration policy if it differs from desired
1391
- // When no explicit TTL is configured, use Google's default (31 days) for comparison
1392
- let effectivePolicy = desiredExpirationPolicy ?? { ttl: GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL };
1393
- let currentTtl = subscriptionData?.expirationPolicy?.ttl || null;
1394
- let desiredTtl = effectivePolicy.ttl || null;
1395
-
1396
- // Adopted (pre-existing, unmanaged) subscriptions belong to the customer - never
1397
- // rewrite their lifecycle policy. A subscription is ours to manage only when it is
1398
- // already recorded as managed (true) or predates ownership tracking (undefined);
1399
- // a freshly adopted one (marker absent in the pre-lock snapshot) or an explicit
1400
- // `false` flag is hands-off.
1401
- let subscriptionManagedByUs = !!current.pubSubSubscription && current.pubSubSubscriptionManaged !== false;
1402
-
1403
- if (!subscriptionManagedByUs && desiredExpirationPolicy !== null) {
1404
- // Do not mutate the customer's subscription, but warn when an explicitly
1405
- // configured expiration is longer than theirs: the subscription may expire on
1406
- // its own and silently disable Gmail push.
1407
- let toSeconds = ttl => {
1408
- let n = ttl ? parseInt(ttl, 10) : NaN;
1409
- return Number.isFinite(n) ? n : null;
1410
- };
1411
- let currentSeconds = toSeconds(currentTtl);
1412
- let desiredSeconds = toSeconds(desiredTtl);
1413
- // desiredSeconds === null means EmailEngine wants an indefinite subscription
1414
- if (currentSeconds !== null && (desiredSeconds === null || currentSeconds < desiredSeconds)) {
1415
- logger.warn({
1416
- msg: 'Adopted Pub/Sub subscription expires sooner than the configured expiration; leaving it unchanged',
1417
- app: appData.id,
1418
- subscription: subscriptionName,
1419
- currentTtl,
1420
- desiredTtl
1421
- });
1422
- }
1423
- } else if (subscriptionManagedByUs && currentTtl !== desiredTtl) {
1424
- try {
1425
- await client.request(accessToken, subscriptionUrl, 'PATCH', {
1426
- subscription: { expirationPolicy: effectivePolicy },
1427
- updateMask: 'expirationPolicy'
1428
- });
1429
- logger.info({
1430
- msg: 'Updated expiration policy on subscription',
1431
- app: appData.id,
1432
- subscription: subscriptionName,
1433
- desiredTtl
1434
- });
1435
- // Update stored TTL after successful patch
1436
- subscriptionData.expirationPolicy = effectivePolicy;
1437
- } catch (patchErr) {
1438
- ttlPatchFailed = patchErr;
1439
- logger.warn({
1440
- msg: 'Failed to update expiration policy on subscription',
1441
- app: appData.id,
1442
- subscription: subscriptionName,
1443
- err: patchErr
1444
- });
1445
- }
1446
- }
1554
+ await this.adoptPubsubResource(run, 'pubSubSubscription', subscriptionName);
1555
+
1556
+ await this.reconcileSubscriptionTtl(run, subscriptionData);
1447
1557
 
1448
1558
  // Store current expiration info in meta
1449
1559
  await this.setMeta(appData.id, {
1450
1560
  subscriptionExpiration: subscriptionData?.expirationPolicy?.ttl || null
1451
1561
  });
1452
1562
  } catch (err) {
1453
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1454
- logger.warn({ msg: 'Network error checking Pub/Sub subscription', app: appData.id, code: err.code });
1455
- throw err;
1563
+ await this.handlePubsubError(appData, err, {
1564
+ networkMsg: 'Network error checking Pub/Sub subscription',
1565
+ authFlag: { message: PUBSUB_PERM_VIEW },
1566
+ onNotFound: () => this.createPubsubSubscription(run, err)
1567
+ });
1568
+ }
1569
+ }
1570
+
1571
+ // Patch an existing subscription's expiration policy if it differs from desired. A failed
1572
+ // PATCH does not fail the run, it is kept on run.ttlPatchFailed for finalizePubsubMeta().
1573
+ async reconcileSubscriptionTtl(run, subscriptionData) {
1574
+ const { appData, client, accessToken, subscriptionUrl, subscriptionName, desiredExpirationPolicy, current } = run;
1575
+
1576
+ // When no explicit TTL is configured, use Google's default (31 days) for comparison
1577
+ let effectivePolicy = desiredExpirationPolicy ?? { ttl: GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL };
1578
+ let currentTtl = subscriptionData?.expirationPolicy?.ttl || null;
1579
+ let desiredTtl = effectivePolicy.ttl || null;
1580
+
1581
+ // Adopted (pre-existing, unmanaged) subscriptions belong to the customer - never
1582
+ // rewrite their lifecycle policy. A subscription is ours to manage only when it is
1583
+ // already recorded as managed (true) or predates ownership tracking (undefined);
1584
+ // a freshly adopted one (marker absent in the pre-lock snapshot) or an explicit
1585
+ // `false` flag is hands-off.
1586
+ let subscriptionManagedByUs = !!current.pubSubSubscription && current.pubSubSubscriptionManaged !== false;
1587
+
1588
+ if (!subscriptionManagedByUs && desiredExpirationPolicy !== null) {
1589
+ // Do not mutate the customer's subscription, but warn when an explicitly
1590
+ // configured expiration is longer than theirs: the subscription may expire on
1591
+ // its own and silently disable Gmail push.
1592
+ let currentSeconds = ttlSeconds(currentTtl);
1593
+ let desiredSeconds = ttlSeconds(desiredTtl);
1594
+ // desiredSeconds === null means EmailEngine wants an indefinite subscription
1595
+ if (currentSeconds !== null && (desiredSeconds === null || currentSeconds < desiredSeconds)) {
1596
+ logger.warn({
1597
+ msg: 'Adopted Pub/Sub subscription expires sooner than the configured expiration; leaving it unchanged',
1598
+ app: appData.id,
1599
+ subscription: subscriptionName,
1600
+ currentTtl,
1601
+ desiredTtl
1602
+ });
1456
1603
  }
1457
- switch (err?.oauthRequest?.response?.error?.code) {
1458
- case 403:
1459
- // no permissions
1460
- this.setMetaFireAndForget(appData.id, {
1461
- authFlag: { message: PUBSUB_PERM_VIEW },
1462
- ttlWarning: null
1463
- });
1464
- throw err;
1465
- case 404: {
1466
- // does not exist
1467
- logger.info({ msg: 'Subscription does not exist', app: appData.id, subscription: subscriptionName });
1468
- try {
1469
- let createPayload = {
1470
- topic: topicName,
1471
- ackDeadlineSeconds: GMAIL_PUBSUB_ACK_DEADLINE_SECONDS
1472
- };
1473
- if (desiredExpirationPolicy !== null) {
1474
- createPayload.expirationPolicy = desiredExpirationPolicy;
1475
- }
1476
- let subscriptionCreateRes = await client.request(accessToken, subscriptionUrl, 'PUT', createPayload);
1477
- /*
1478
- {
1479
- name: 'projects/webhooks-425411/subscriptions/ee-sub-AAABkE9_uNMAAAAH',
1480
- topic: 'projects/webhooks-425411/topics/ee-pub-AAABkE9_uNMAAAAH',
1481
- pushConfig: {},
1482
- ackDeadlineSeconds: 10,
1483
- messageRetentionDuration: '604800s',
1484
- expirationPolicy: { ttl: '2678400s' },
1485
- state: 'ACTIVE'
1486
- }
1487
- */
1604
+ return;
1605
+ }
1488
1606
 
1489
- if (!subscriptionCreateRes?.name) {
1490
- throw new Error('Subscription was not created', { cause: err });
1491
- }
1607
+ if (!subscriptionManagedByUs || currentTtl === desiredTtl) {
1608
+ return;
1609
+ }
1492
1610
 
1493
- await this.update(
1494
- appData.id,
1495
- {
1496
- pubSubSubscription: subscriptionName,
1497
- // EmailEngine created this subscription, so it may delete it on app removal.
1498
- pubSubSubscriptionManaged: true
1499
- },
1500
- { partial: true }
1501
- );
1502
-
1503
- results.pubSubSubscription = subscriptionName;
1504
-
1505
- // Store expiration info from the created subscription
1506
- await this.setMeta(appData.id, {
1507
- subscriptionExpiration: subscriptionCreateRes?.expirationPolicy?.ttl || null
1508
- });
1509
- } catch (err) {
1510
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1511
- logger.warn({ msg: 'Network error creating Pub/Sub subscription', app: appData.id, code: err.code });
1512
- throw err;
1513
- }
1514
- switch (err?.oauthRequest?.response?.error?.code) {
1515
- case 403:
1516
- // no permissions
1517
- this.setMetaFireAndForget(appData.id, {
1518
- authFlag: { message: PUBSUB_PERM_MANAGE },
1519
- ttlWarning: null
1520
- });
1521
- throw err;
1522
- case 409:
1523
- // already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
1524
- logger.info({ msg: 'Subscription already exists', app: appData.id, subscription: subscriptionName });
1525
- await adoptExistingResource('pubSubSubscription', subscriptionName);
1526
- break;
1527
- default:
1528
- throw err;
1529
- }
1530
- }
1531
- break;
1532
- }
1533
- default:
1534
- throw err;
1611
+ try {
1612
+ await client.request(accessToken, subscriptionUrl, 'PATCH', {
1613
+ subscription: { expirationPolicy: effectivePolicy },
1614
+ updateMask: 'expirationPolicy'
1615
+ });
1616
+ logger.info({
1617
+ msg: 'Updated expiration policy on subscription',
1618
+ app: appData.id,
1619
+ subscription: subscriptionName,
1620
+ desiredTtl
1621
+ });
1622
+ // Update stored TTL after successful patch
1623
+ subscriptionData.expirationPolicy = effectivePolicy;
1624
+ } catch (patchErr) {
1625
+ run.ttlPatchFailed = patchErr;
1626
+ logger.warn({
1627
+ msg: 'Failed to update expiration policy on subscription',
1628
+ app: appData.id,
1629
+ subscription: subscriptionName,
1630
+ err: patchErr
1631
+ });
1632
+ }
1633
+ }
1634
+
1635
+ async createPubsubSubscription(run, lookupErr) {
1636
+ const { appData, client, accessToken, subscriptionUrl, subscriptionName, topicName, desiredExpirationPolicy } = run;
1637
+
1638
+ // does not exist
1639
+ logger.info({ msg: 'Subscription does not exist', app: appData.id, subscription: subscriptionName });
1640
+ try {
1641
+ let createPayload = {
1642
+ topic: topicName,
1643
+ ackDeadlineSeconds: GMAIL_PUBSUB_ACK_DEADLINE_SECONDS
1644
+ };
1645
+ if (desiredExpirationPolicy !== null) {
1646
+ createPayload.expirationPolicy = desiredExpirationPolicy;
1535
1647
  }
1648
+ let subscriptionCreateRes = await client.request(accessToken, subscriptionUrl, 'PUT', createPayload);
1649
+ /*
1650
+ {
1651
+ name: 'projects/webhooks-425411/subscriptions/ee-sub-AAABkE9_uNMAAAAH',
1652
+ topic: 'projects/webhooks-425411/topics/ee-pub-AAABkE9_uNMAAAAH',
1653
+ pushConfig: {},
1654
+ ackDeadlineSeconds: 10,
1655
+ messageRetentionDuration: '604800s',
1656
+ expirationPolicy: { ttl: '2678400s' },
1657
+ state: 'ACTIVE'
1536
1658
  }
1659
+ */
1537
1660
 
1538
- // Step 4. Grant access to Gmail publisher
1661
+ if (!subscriptionCreateRes?.name) {
1662
+ throw new Error('Subscription was not created', { cause: lookupErr });
1663
+ }
1664
+
1665
+ await this.update(
1666
+ appData.id,
1667
+ {
1668
+ pubSubSubscription: subscriptionName,
1669
+ // EmailEngine created this subscription, so it may delete it on app removal.
1670
+ pubSubSubscriptionManaged: true
1671
+ },
1672
+ { partial: true }
1673
+ );
1674
+
1675
+ run.results.pubSubSubscription = subscriptionName;
1676
+
1677
+ // Store expiration info from the created subscription
1678
+ await this.setMeta(appData.id, {
1679
+ subscriptionExpiration: subscriptionCreateRes?.expirationPolicy?.ttl || null
1680
+ });
1681
+ } catch (err) {
1682
+ await this.handlePubsubError(appData, err, {
1683
+ networkMsg: 'Network error creating Pub/Sub subscription',
1684
+ authFlag: { message: PUBSUB_PERM_MANAGE },
1685
+ onConflict: async () => {
1686
+ // already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
1687
+ logger.info({ msg: 'Subscription already exists', app: appData.id, subscription: subscriptionName });
1688
+ await this.adoptPubsubResource(run, 'pubSubSubscription', subscriptionName);
1689
+ }
1690
+ });
1691
+ }
1692
+ }
1693
+
1694
+ async ensurePublisherBinding(run) {
1695
+ const { appData, client, accessToken, topicUrl, topicName, current } = run;
1539
1696
 
1540
1697
  let existingPolicy;
1541
1698
  let getIamPolicyRes;
1542
1699
  try {
1543
1700
  // Check for an existing policy grant
1544
1701
  getIamPolicyRes = await client.request(accessToken, `${topicUrl}:getIamPolicy`, 'GET');
1545
- existingPolicy = getIamPolicyRes?.bindings?.find(binding => binding?.role === role && binding?.members?.includes(member));
1702
+ existingPolicy = getIamPolicyRes?.bindings?.find(
1703
+ binding => binding?.role === GMAIL_PUBLISHER_ROLE && binding?.members?.includes(GMAIL_PUSH_MEMBER)
1704
+ );
1546
1705
  /*
1547
1706
  {
1548
1707
  version: 1,
@@ -1556,21 +1715,10 @@ class OAuth2AppsHandler {
1556
1715
  }
1557
1716
  */
1558
1717
  } catch (err) {
1559
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1560
- logger.warn({ msg: 'Network error checking Pub/Sub IAM policy', app: appData.id, code: err.code });
1561
- throw err;
1562
- }
1563
- switch (err?.oauthRequest?.response?.error?.code) {
1564
- case 403:
1565
- // no permissions
1566
- this.setMetaFireAndForget(appData.id, {
1567
- authFlag: { message: PUBSUB_PERM_VIEW },
1568
- ttlWarning: null
1569
- });
1570
- throw err;
1571
- default:
1572
- throw err;
1573
- }
1718
+ await this.handlePubsubError(appData, err, {
1719
+ networkMsg: 'Network error checking Pub/Sub IAM policy',
1720
+ authFlag: { message: PUBSUB_PERM_VIEW }
1721
+ });
1574
1722
  }
1575
1723
 
1576
1724
  if (existingPolicy) {
@@ -1583,71 +1731,53 @@ class OAuth2AppsHandler {
1583
1731
  // gate). Only populate results (and write) on first adoption, so a re-run is a no-op
1584
1732
  // and does not trigger a redundant pull-worker restart.
1585
1733
  if (!current.pubSubIamPolicy) {
1586
- results.iamPolicy = { members: [member], role };
1587
- await this.update(appData.id, { pubSubIamPolicy: results.iamPolicy }, { partial: true });
1588
- }
1589
- } else {
1590
- logger.debug({ msg: 'Granting access to Gmail publisher', app: appData.id, topic: topicName });
1591
- let existingBindings = (getIamPolicyRes && getIamPolicyRes.bindings) || [];
1592
- const policyPayload = {
1593
- policy: {
1594
- bindings: existingBindings.concat([
1595
- {
1596
- members: [member],
1597
- role
1598
- }
1599
- ])
1600
- }
1601
- };
1602
- if (getIamPolicyRes && getIamPolicyRes.etag) {
1603
- policyPayload.policy.etag = getIamPolicyRes.etag;
1734
+ run.results.iamPolicy = gmailPublisherBinding();
1735
+ await this.update(appData.id, { pubSubIamPolicy: run.results.iamPolicy }, { partial: true });
1604
1736
  }
1605
- try {
1606
- await client.request(accessToken, `${topicUrl}:setIamPolicy`, 'POST', policyPayload);
1607
- results.iamPolicy = {
1608
- members: [member],
1609
- role
1610
- };
1737
+ return;
1738
+ }
1611
1739
 
1612
- await this.update(
1613
- appData.id,
1614
- {
1615
- pubSubIamPolicy: results.iamPolicy
1616
- },
1617
- { partial: true }
1618
- );
1619
- } catch (err) {
1620
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1621
- logger.warn({ msg: 'Network error setting Pub/Sub IAM policy', app: appData.id, code: err.code });
1622
- throw err;
1623
- }
1624
- switch (err?.oauthRequest?.response?.error?.code) {
1625
- case 403:
1626
- // no permissions
1627
- this.setMetaFireAndForget(appData.id, {
1628
- authFlag: { message: PUBSUB_PERM_MANAGE },
1629
- ttlWarning: null
1630
- });
1631
- throw err;
1632
- default:
1633
- throw err;
1634
- }
1740
+ logger.debug({ msg: 'Granting access to Gmail publisher', app: appData.id, topic: topicName });
1741
+ let existingBindings = (getIamPolicyRes && getIamPolicyRes.bindings) || [];
1742
+ const policyPayload = {
1743
+ policy: {
1744
+ bindings: existingBindings.concat([gmailPublisherBinding()])
1635
1745
  }
1746
+ };
1747
+ if (getIamPolicyRes && getIamPolicyRes.etag) {
1748
+ policyPayload.policy.etag = getIamPolicyRes.etag;
1749
+ }
1750
+ try {
1751
+ await client.request(accessToken, `${topicUrl}:setIamPolicy`, 'POST', policyPayload);
1752
+ run.results.iamPolicy = gmailPublisherBinding();
1753
+
1754
+ await this.update(
1755
+ appData.id,
1756
+ {
1757
+ pubSubIamPolicy: run.results.iamPolicy
1758
+ },
1759
+ { partial: true }
1760
+ );
1761
+ } catch (err) {
1762
+ await this.handlePubsubError(appData, err, {
1763
+ networkMsg: 'Network error setting Pub/Sub IAM policy',
1764
+ authFlag: { message: PUBSUB_PERM_MANAGE }
1765
+ });
1636
1766
  }
1767
+ }
1637
1768
 
1638
- // clear auth flag if everything worked; set or clear TTL warning
1769
+ // clear auth flag if everything worked; set or clear TTL warning
1770
+ async finalizePubsubMeta(run) {
1639
1771
  let metaUpdate = { authFlag: null };
1640
- if (ttlPatchFailed) {
1772
+ if (run.ttlPatchFailed) {
1641
1773
  metaUpdate.ttlWarning = {
1642
1774
  message: 'Failed to update expiration policy on subscription',
1643
- description: [ttlPatchFailed.message, ttlPatchFailed.code].filter(Boolean).join('; ')
1775
+ description: [run.ttlPatchFailed.message, run.ttlPatchFailed.code].filter(Boolean).join('; ')
1644
1776
  };
1645
1777
  } else {
1646
1778
  metaUpdate.ttlWarning = null;
1647
1779
  }
1648
- await this.setMeta(appData.id, metaUpdate);
1649
-
1650
- return results;
1780
+ await this.setMeta(run.appData.id, metaUpdate);
1651
1781
  }
1652
1782
 
1653
1783
  async getClient(id, extraOpts) {
@@ -1659,167 +1789,14 @@ class OAuth2AppsHandler {
1659
1789
  throw error;
1660
1790
  }
1661
1791
 
1662
- switch (appData.provider) {
1663
- case 'gmail': {
1664
- let clientId = appData.clientId;
1665
- let clientSecret = appData.clientSecret ? await this.decrypt(appData.clientSecret) : null;
1666
- let redirectUrl = appData.redirectUrl;
1667
- let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, GMAIL_SCOPES, appData.skipScopes);
1668
-
1669
- let googleProjectId = appData.googleProjectId;
1670
- let workspaceAccounts = appData.googleWorkspaceAccounts;
1671
-
1672
- if (!clientId || !clientSecret || !redirectUrl) {
1673
- let error = Boom.boomify(new Error('OAuth2 credentials not set up for Gmail'), { statusCode: 400 });
1674
- throw error;
1675
- }
1676
-
1677
- return new GmailOauth(
1678
- Object.assign(
1679
- {
1680
- clientId,
1681
- clientSecret,
1682
- redirectUrl,
1683
- scopes,
1684
- googleProjectId,
1685
- workspaceAccounts,
1686
- setFlag: this.createFlagSetter(id, 'gmail')
1687
- },
1688
- extraOpts
1689
- )
1690
- );
1691
- }
1692
-
1693
- case 'gmailService': {
1694
- let serviceClient = appData.serviceClient;
1695
-
1696
- let serviceClientEmail = appData.serviceClientEmail;
1697
- let authMethod = normalizeAuthMethod(appData.authMethod);
1698
- let serviceKey = appData.serviceKey ? await this.decrypt(appData.serviceKey) : null;
1699
- let externalAccount = appData.externalAccount ? await this.decrypt(appData.externalAccount) : null;
1700
-
1701
- let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, GMAIL_SCOPES, appData.skipScopes);
1702
-
1703
- let googleProjectId = appData.googleProjectId;
1704
- let workspaceAccounts = appData.googleWorkspaceAccounts;
1705
-
1706
- // A method with no stored credential (the attached service account) is always ready
1707
- let credential = SERVICE_AUTH_CREDENTIALS[authMethod];
1708
- let credentialsReady = !credential || (serviceClient && !!{ serviceKey, externalAccount }[credential]);
1709
- if (!credentialsReady) {
1710
- let error = Boom.boomify(new Error('OAuth2 credentials not set up for Gmail'), { statusCode: 400 });
1711
- throw error;
1712
- }
1713
-
1714
- return new GmailOauth(
1715
- Object.assign(
1716
- {
1717
- serviceClient,
1718
- authMethod,
1719
- serviceKey,
1720
- externalAccount,
1721
- externalAccountSigner: authMethod === 'externalAccount' ? getExternalAccountSigner(id, externalAccount) : undefined,
1722
- googleProjectId,
1723
- serviceClientEmail,
1724
- scopes,
1725
- workspaceAccounts,
1726
- setFlag: this.createFlagSetter(id, 'gmailService')
1727
- },
1728
- extraOpts
1729
- )
1730
- );
1731
- }
1732
-
1733
- case 'outlook': {
1734
- let authority = await appData.authority;
1735
- let clientId = appData.clientId;
1736
- let clientSecret = appData.clientSecret ? await this.decrypt(appData.clientSecret) : null;
1737
- let redirectUrl = appData.redirectUrl;
1738
-
1739
- let cloud = appData.cloud || 'global';
1740
-
1741
- let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, outlookScopes(cloud), appData.skipScopes);
1742
-
1743
- if (!clientId || !clientSecret || !authority || !redirectUrl) {
1744
- let error = Boom.boomify(new Error('OAuth2 credentials not set up for Outlook (delegated)'), { statusCode: 400 });
1745
- throw error;
1746
- }
1747
-
1748
- return new OutlookOauth(
1749
- Object.assign(
1750
- {
1751
- authority,
1752
- clientId,
1753
- clientSecret,
1754
- redirectUrl,
1755
- scopes,
1756
- cloud,
1757
- setFlag: this.createFlagSetter(id, 'outlook')
1758
- },
1759
- extraOpts
1760
- )
1761
- );
1762
- }
1763
-
1764
- case 'outlookService': {
1765
- let authority = appData.authority;
1766
- let clientId = appData.clientId;
1767
- let clientSecret = appData.clientSecret ? await this.decrypt(appData.clientSecret) : null;
1768
-
1769
- let cloud = appData.cloud || 'global';
1770
-
1771
- if (!clientId || !clientSecret || !authority) {
1772
- let error = Boom.boomify(new Error('OAuth2 credentials not set up for Outlook (application)'), { statusCode: 400 });
1773
- throw error;
1774
- }
1775
-
1776
- // Client credentials use {apiBase}/.default scope; per-scope config is not applicable
1777
- return new OutlookOauth(
1778
- Object.assign(
1779
- {
1780
- authority,
1781
- clientId,
1782
- clientSecret,
1783
- cloud,
1784
- provider: 'outlookService',
1785
- useClientCredentials: true,
1786
- setFlag: this.createFlagSetter(id, 'outlookService')
1787
- },
1788
- extraOpts
1789
- )
1790
- );
1791
- }
1792
-
1793
- case 'mailRu': {
1794
- let clientId = appData.clientId;
1795
- let clientSecret = appData.clientSecret ? await this.decrypt(appData.clientSecret) : null;
1796
- let redirectUrl = appData.redirectUrl;
1797
- let scopes = formatExtraScopes(appData.extraScopes, appData.baseScopes, MAIL_RU_SCOPES, appData.skipScopes);
1798
-
1799
- if (!clientId || !clientSecret || !redirectUrl) {
1800
- let error = Boom.boomify(new Error('OAuth2 credentials not set up for Mail.ru'), { statusCode: 400 });
1801
- throw error;
1802
- }
1792
+ if (!Object.prototype.hasOwnProperty.call(CLIENT_BUILDERS, appData.provider)) {
1793
+ let error = Boom.boomify(new Error('Unknown OAuth provider'), { statusCode: 400 });
1794
+ throw error;
1795
+ }
1803
1796
 
1804
- return new MailRuOauth(
1805
- Object.assign(
1806
- {
1807
- clientId,
1808
- clientSecret,
1809
- redirectUrl,
1810
- scopes,
1811
- setFlag: this.createFlagSetter(id, 'mailRu')
1812
- },
1813
- extraOpts
1814
- )
1815
- );
1816
- }
1797
+ let { Client, opts } = await CLIENT_BUILDERS[appData.provider](this, appData, id);
1817
1798
 
1818
- default: {
1819
- let error = Boom.boomify(new Error('Unknown OAuth provider'), { statusCode: 400 });
1820
- throw error;
1821
- }
1822
- }
1799
+ return new Client(Object.assign(opts, { setFlag: this.createFlagSetter(id, appData.provider) }, extraOpts));
1823
1800
  }
1824
1801
 
1825
1802
  async getServiceAccessToken(appData, client) {