emailengine-app 2.78.0 → 2.79.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +70 -35
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
@@ -36,7 +36,7 @@ function recordTokenMetric(status, provider, statusCode) {
36
36
  try {
37
37
  parentPort.postMessage(metricData);
38
38
  } catch (err) {
39
- logger.error({ msg: 'Failed to post metrics to parent', err });
39
+ logger.warn({ msg: 'Failed to post metrics to parent', err });
40
40
  }
41
41
  }
42
42
  // If running in main thread, metrics will be handled by direct access
@@ -47,8 +47,9 @@ const { OutlookOauth, outlookScopes } = require('./oauth/outlook');
47
47
  const { GmailOauth, GMAIL_SCOPES } = require('./oauth/gmail');
48
48
  const { MailRuOauth, MAIL_RU_SCOPES } = require('./oauth/mail-ru');
49
49
 
50
+ // Historical app IDs of the retired settings-based OAuth2 configuration. Only used by
51
+ // migrateLegacyApps(); migrated apps keep these IDs, but are otherwise regular apps.
50
52
  const LEGACY_KEYS = ['gmail', 'gmailService', 'outlook', 'mailRu'];
51
- const LEGACY_KEYS_REV = JSON.parse(JSON.stringify(LEGACY_KEYS)).reverse();
52
53
 
53
54
  const PUBSUB_PERM_MANAGE = 'Service client does not have permission to manage Pub/Sub topics. Grant the service user the "Pub/Sub Admin" role.';
54
55
  const PUBSUB_PERM_VIEW = 'Service client does not have permission to view Pub/Sub topics. Grant the service user the "Pub/Sub Admin" role.';
@@ -334,18 +335,6 @@ class OAuth2AppsHandler {
334
335
  }
335
336
  idList = [].concat(idList || []).sort((a, b) => -a.localeCompare(b));
336
337
 
337
- if (!opts.pubsub) {
338
- for (let legacyKey of LEGACY_KEYS_REV) {
339
- if (await settings.get(`${legacyKey}Enabled`)) {
340
- idList.unshift(legacyKey);
341
- } else if (await settings.get(`${legacyKey}Client`)) {
342
- idList.unshift(legacyKey);
343
- } else if (await settings.get(`${legacyKey}ClientId`)) {
344
- idList.unshift(legacyKey);
345
- }
346
- }
347
- }
348
-
349
338
  let response = {
350
339
  total: idList.length,
351
340
  pages: Math.ceil(idList.length / pageSize),
@@ -356,19 +345,6 @@ class OAuth2AppsHandler {
356
345
  //let keys = idList.slice(startPos, startPos + pageSize);
357
346
  let keys = idList;
358
347
 
359
- let legacyKeys = keys.filter(key => LEGACY_KEYS.includes(key));
360
- keys = keys.filter(key => !LEGACY_KEYS.includes(key));
361
-
362
- for (let legacyKey of legacyKeys) {
363
- try {
364
- let data = await this.get(legacyKey);
365
- response.apps.push(data);
366
- } catch (err) {
367
- logger.error({ msg: 'Failed to process legacy app', legacyKey, err });
368
- continue;
369
- }
370
- }
371
-
372
348
  if (keys.length) {
373
349
  let bufKeys = keys.flatMap(id => [`${id}:data`, `${id}:meta`]);
374
350
  let list = await this.redis.hmgetBuffer(this.getDataKey(), bufKeys);
@@ -381,12 +357,12 @@ class OAuth2AppsHandler {
381
357
  try {
382
358
  data.meta = msgpack.decode(metaEntry);
383
359
  } catch (metaErr) {
384
- logger.error({ msg: 'Failed to process app meta', entryLength: metaEntry?.length || 0 });
360
+ logger.error({ msg: 'Failed to process app meta', app: keys[i / 2], entryLength: metaEntry?.length || 0, err: metaErr });
385
361
  }
386
362
  }
387
363
  response.apps.push(data);
388
364
  } catch (err) {
389
- logger.error({ msg: 'Failed to process app', entryLength: dataEntry?.length || 0 });
365
+ logger.error({ msg: 'Failed to process app', app: keys[i / 2], entryLength: dataEntry?.length || 0, err });
390
366
  }
391
367
  }
392
368
  }
@@ -439,240 +415,203 @@ class OAuth2AppsHandler {
439
415
  return idBuf.toString('base64url');
440
416
  }
441
417
 
442
- async getLegacyApp(id) {
443
- let extraScopes = await settings.get(`${id}ExtraScopes`);
444
- if (!Array.isArray(extraScopes)) {
445
- extraScopes = (extraScopes || '').toString().split(/[\s,]+/);
418
+ // One-time startup migration: converts settings-based OAuth2 configuration ("legacy apps")
419
+ // into regular app-store records. The historical app IDs (gmail, gmailService, outlook,
420
+ // mailRu) are kept, so account references (accountData.oauth2.provider) keep resolving
421
+ // without touching account data. The source settings keys are deleted after a successful
422
+ // copy, which is what makes the migration idempotent; a Redis lock guards against parallel
423
+ // instances sharing one Redis. Returns the list of migrated app IDs.
424
+ async migrateLegacyApps() {
425
+ // Full per-app settings key suffixes ever used by the legacy configuration
426
+ const FIELDS = [
427
+ 'Enabled',
428
+ 'RedirectUrl',
429
+ 'Client',
430
+ 'ClientId',
431
+ 'ClientSecret',
432
+ 'Authority',
433
+ 'ExtraScopes',
434
+ 'SkipScopes',
435
+ 'Key',
436
+ 'AuthFlag',
437
+ 'AuthMethod',
438
+ 'ExternalAccount'
439
+ ];
440
+
441
+ // Even older generic service-account keys with no reader left anywhere; dropped without migration
442
+ const ORPHAN_KEYS = ['serviceClient', 'serviceKey', 'serviceExtraScopes'];
443
+
444
+ const candidateKeys = LEGACY_KEYS.flatMap(id => FIELDS.map(field => `${id}${field}`)).concat(ORPHAN_KEYS);
445
+
446
+ // One batched read for every legacy key; settings.getMulti() also decrypts stored secrets
447
+ const readLegacyValues = async () => await settings.getMulti(...candidateKeys);
448
+ const hasValues = values => Object.values(values).some(value => value !== null);
449
+
450
+ // cheap presence probe before taking the lock
451
+ if (!hasValues(await readLegacyValues())) {
452
+ return [];
446
453
  }
447
- extraScopes = extraScopes.filter(entry => entry);
448
454
 
449
- let skipScopes = await settings.get(`${id}SkipScopes`);
450
- if (!Array.isArray(skipScopes)) {
451
- skipScopes = (skipScopes || '').toString().split(/[\s,]+/);
455
+ let migrateLock = await lock.waitAcquireLock('oauth:legacy:migrate', 5 * 60 * 1000, 2 * 60 * 1000);
456
+ if (!migrateLock.success) {
457
+ throw new Error('Failed to get lock for the legacy OAuth2 app migration');
452
458
  }
453
- skipScopes = skipScopes.filter(entry => entry);
454
459
 
455
- switch (id) {
456
- case 'gmail': {
457
- let appData = {
458
- id: 'gmail',
459
- provider: 'gmail',
460
- legacy: true,
461
- enabled: await settings.get(`${id}Enabled`),
462
- clientId: await settings.get(`${id}ClientId`),
463
- clientSecret: await settings.get(`${id}ClientSecret`),
464
- redirectUrl: await settings.get(`${id}RedirectUrl`),
465
- extraScopes,
466
- skipScopes,
467
-
468
- name: 'Gmail',
469
- description: 'Legacy OAuth2 app',
470
-
471
- meta: {
472
- authFlag: await settings.get(`${id}AuthFlag`)
473
- }
474
- };
475
- return appData;
460
+ let migrated = [];
461
+ try {
462
+ // re-read inside the lock: another instance may have finished the migration already
463
+ let values = await readLegacyValues();
464
+ if (!hasValues(values)) {
465
+ return [];
476
466
  }
477
467
 
478
- case 'gmailService': {
479
- let storedAuthMethod = await settings.get(`${id}AuthMethod`);
480
- let authMethod = storedAuthMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey';
481
- let appData = {
482
- id: 'gmailService',
483
- provider: 'gmailService',
484
- legacy: true,
485
- authMethod,
486
- serviceClient: await settings.get(`${id}Client`),
487
- serviceKey: await settings.get(`${id}Key`),
488
- externalAccount: await settings.get(`${id}ExternalAccount`),
489
- extraScopes,
490
- skipScopes,
491
-
492
- name: 'Gmail service',
493
- description: 'Legacy OAuth2 app',
494
-
495
- meta: {
496
- authFlag: await settings.get(`${id}AuthFlag`)
497
- },
468
+ const normalizeScopes = value => {
469
+ if (!Array.isArray(value)) {
470
+ value = (value || '').toString().split(/[\s,]+/);
471
+ }
472
+ return value.filter(entry => entry);
473
+ };
498
474
 
499
- enabled: true
500
- };
501
- return appData;
502
- }
475
+ for (let legacyKey of LEGACY_KEYS) {
476
+ const v = field => values[`${legacyKey}${field}`];
477
+
478
+ // Same visibility rule the legacy listing applied: an app existed when it was
479
+ // enabled or had a client configured. Stray keys without either (e.g. only a
480
+ // redirect URL) never surfaced an app and are just cleaned up.
481
+ let visible = !!(v('Enabled') || v('Client') || v('ClientId'));
482
+
483
+ let exists = await this.redis.hexists(this.getDataKey(), `${legacyKey}:data`);
484
+
485
+ if (visible && !exists) {
486
+ let entry = {
487
+ provider: legacyKey,
488
+ // legacy apps never separated IMAP and API access; they always used IMAP scopes
489
+ baseScopes: 'imap',
490
+ description: 'Migrated from the deprecated settings-based OAuth2 configuration',
491
+ enabled: !!v('Enabled'),
492
+ extraScopes: normalizeScopes(v('ExtraScopes')),
493
+ skipScopes: normalizeScopes(v('SkipScopes'))
494
+ };
503
495
 
504
- case 'outlook': {
505
- let appData = {
506
- id: 'outlook',
507
- provider: 'outlook',
508
- legacy: true,
509
- enabled: await settings.get(`${id}Enabled`),
510
- authority: await settings.get(`${id}Authority`),
511
- clientId: await settings.get(`${id}ClientId`),
512
- clientSecret: await settings.get(`${id}ClientSecret`),
513
- redirectUrl: await settings.get(`${id}RedirectUrl`),
514
- extraScopes,
515
- skipScopes,
516
-
517
- name: 'Outlook (delegated)',
518
- description: 'Legacy OAuth2 app',
519
-
520
- meta: {
521
- authFlag: await settings.get(`${id}AuthFlag`)
496
+ switch (legacyKey) {
497
+ case 'gmail':
498
+ entry.name = 'Gmail';
499
+ entry.clientId = v('ClientId');
500
+ entry.clientSecret = v('ClientSecret');
501
+ entry.redirectUrl = v('RedirectUrl');
502
+ break;
503
+
504
+ case 'gmailService':
505
+ entry.name = 'Gmail service';
506
+ entry.authMethod = v('AuthMethod') === 'externalAccount' ? 'externalAccount' : 'serviceKey';
507
+ entry.serviceClient = v('Client');
508
+ entry.serviceKey = v('Key');
509
+ entry.externalAccount = v('ExternalAccount');
510
+ // service apps are always treated as enabled
511
+ entry.enabled = true;
512
+ break;
513
+
514
+ case 'outlook':
515
+ entry.name = 'Outlook (delegated)';
516
+ entry.clientId = v('ClientId');
517
+ entry.clientSecret = v('ClientSecret');
518
+ entry.redirectUrl = v('RedirectUrl');
519
+ entry.authority = v('Authority');
520
+ // legacy config predates sovereign cloud support
521
+ entry.cloud = 'global';
522
+ break;
523
+
524
+ case 'mailRu':
525
+ entry.name = 'Mail.ru';
526
+ entry.clientId = v('ClientId');
527
+ entry.clientSecret = v('ClientSecret');
528
+ entry.redirectUrl = v('RedirectUrl');
529
+ break;
522
530
  }
523
- };
524
- return appData;
525
- }
526
531
 
527
- case 'mailRu': {
528
- let appData = {
529
- id: 'mailRu',
530
- provider: 'mailRu',
531
- legacy: true,
532
- enabled: await settings.get(`${id}Enabled`),
533
- clientId: await settings.get(`${id}ClientId`),
534
- clientSecret: await settings.get(`${id}ClientSecret`),
535
- redirectUrl: await settings.get(`${id}RedirectUrl`),
536
- extraScopes,
537
- skipScopes,
538
-
539
- name: 'Mail.ru',
540
- description: 'Legacy OAuth2 app',
541
-
542
- meta: {
543
- authFlag: await settings.get(`${id}AuthFlag`)
532
+ // Absent legacy keys read as nulls; drop them so the stored record looks like a
533
+ // regular app entry (joi does the equivalent stripping for created apps)
534
+ for (let key of Object.keys(entry)) {
535
+ if (entry[key] === null || typeof entry[key] === 'undefined' || entry[key] === '') {
536
+ delete entry[key];
537
+ }
544
538
  }
545
- };
546
- return appData;
547
- }
548
539
 
549
- default:
550
- return false;
551
- }
552
- }
553
-
554
- async updateLegacyApp(id, updates) {
555
- updates = updates || {};
556
-
557
- let data = {};
540
+ // create() owns the record shape: it encrypts secret fields and stamps `created`
541
+ await this.create(entry, { id: legacyKey });
558
542
 
559
- switch (id) {
560
- case 'gmail':
561
- for (let key of ['clientId', 'clientSecret', 'redirectUrl', 'extraScopes', 'skipScopes']) {
562
- if (typeof updates[key] !== 'undefined') {
563
- data[`${id}${key.replace(/^./, c => c.toUpperCase())}`] = updates[key];
543
+ if (v('AuthFlag')) {
544
+ await this.setMeta(legacyKey, { authFlag: v('AuthFlag') });
564
545
  }
565
- }
566
- break;
567
546
 
568
- case 'gmailService': {
569
- // The authentication method is fixed once a credential has been
570
- // stored - never allow switching between serviceKey and externalAccount.
571
- if (typeof updates.authMethod !== 'undefined') {
572
- let hasStoredCredential = (await settings.get(`${id}Key`)) || (await settings.get(`${id}ExternalAccount`));
573
- if (hasStoredCredential) {
574
- let storedAuthMethod = await settings.get(`${id}AuthMethod`);
575
- updates = Object.assign({}, updates, { authMethod: storedAuthMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey' });
576
- }
547
+ migrated.push(legacyKey);
548
+ logger.info({ msg: 'Migrated legacy OAuth2 app to the app registry', app: legacyKey, enabled: entry.enabled });
577
549
  }
578
- for (let key of ['serviceClient', 'serviceKey', 'externalAccount', 'authMethod', 'extraScopes', 'skipScopes']) {
579
- if (typeof updates[key] !== 'undefined') {
580
- let dataKey;
581
- switch (key) {
582
- case 'extraScopes':
583
- dataKey = 'gmailServiceExtraScopes';
584
- break;
585
- case 'skipScopes':
586
- dataKey = 'gmailServiceSkipScopes';
587
- break;
588
- case 'externalAccount':
589
- dataKey = 'gmailServiceExternalAccount';
590
- break;
591
- case 'authMethod':
592
- dataKey = 'gmailServiceAuthMethod';
593
- break;
594
- default:
595
- dataKey = `gmail${key.replace(/^./, c => c.toUpperCase())}`;
596
- }
597
- data[dataKey] = updates[key];
598
- }
550
+
551
+ // the copy (or cleanup) is complete, drop the source settings keys (no-op when unset)
552
+ let clearReq = this.redis.multi();
553
+ for (let field of FIELDS) {
554
+ clearReq = clearReq.hdel(this.getSettingsKey(), `${legacyKey}${field}`);
599
555
  }
600
- break;
556
+ await clearReq.exec();
601
557
  }
602
558
 
603
- case 'outlook':
604
- for (let key of ['clientId', 'clientSecret', 'redirectUrl', 'authority', 'extraScopes', 'skipScopes']) {
605
- if (typeof updates[key] !== 'undefined') {
606
- data[`${id}${key.replace(/^./, c => c.toUpperCase())}`] = updates[key];
607
- }
608
- }
559
+ let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...ORPHAN_KEYS);
560
+ if (removedOrphans) {
561
+ logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
562
+ }
609
563
 
610
- break;
564
+ // Backfill the per-app account membership sets that the legacy code never maintained,
565
+ // so account counts and app deletion safety checks see the existing accounts. The
566
+ // per-user binding hash (oapp:h:*) is left to repopulate on the next account update.
567
+ if (migrated.length) {
568
+ let migratedSet = new Set(migrated);
569
+ let accounts = await this.redis.smembers(`${REDIS_PREFIX}ia:accounts`);
570
+ let backfillReq = this.redis.multi();
571
+ let backfillCount = 0;
572
+
573
+ // read account data in pipelined chunks; large legacy installs can hold tens of
574
+ // thousands of accounts and sequential reads would stall startup
575
+ const CHUNK_SIZE = 500;
576
+ for (let i = 0; i < accounts.length; i += CHUNK_SIZE) {
577
+ let chunk = accounts.slice(i, i + CHUNK_SIZE);
578
+ let readReq = this.redis.pipeline();
579
+ for (let account of chunk) {
580
+ readReq = readReq.hget(`${REDIS_PREFIX}iad:${account}`, 'oauth2');
581
+ }
582
+ let rows = await readReq.exec();
611
583
 
612
- case 'mailRu':
613
- for (let key of ['clientId', 'clientSecret', 'redirectUrl', 'extraScopes', 'skipScopes']) {
614
- if (typeof updates[key] !== 'undefined') {
615
- data[`${id}${key.replace(/^./, c => c.toUpperCase())}`] = updates[key];
584
+ for (let j = 0; j < chunk.length; j++) {
585
+ let [err, oauth2Json] = rows[j];
586
+ if (err || !oauth2Json) {
587
+ continue;
588
+ }
589
+ let oauth2Data;
590
+ try {
591
+ oauth2Data = JSON.parse(oauth2Json);
592
+ } catch (parseErr) {
593
+ continue;
594
+ }
595
+ if (oauth2Data && oauth2Data.provider && migratedSet.has(oauth2Data.provider)) {
596
+ backfillReq = backfillReq.sadd(`${REDIS_PREFIX}oapp:a:${oauth2Data.provider}`, chunk[j]);
597
+ backfillCount++;
598
+ }
616
599
  }
617
600
  }
618
601
 
619
- break;
620
- }
621
-
622
- for (let key of Object.keys(data)) {
623
- await settings.set(key, data[key]);
624
- }
625
-
626
- // clear alert flag if set
627
- await settings.clear(`${id}AuthFlag`);
628
-
629
- return {
630
- id,
631
- updated: true,
632
- legacy: true
633
- };
634
- }
635
-
636
- async delLegacyApp(id) {
637
- let pipeline = redis.multi();
638
- for (let key of [
639
- 'Enabled',
640
- 'RedirectUrl',
641
- 'Client',
642
- 'ClientId',
643
- 'ClientSecret',
644
- 'Authority',
645
- 'ExtraScopes',
646
- 'SkipScopes',
647
- 'Key',
648
- 'AuthFlag',
649
- 'AuthMethod',
650
- 'ExternalAccount'
651
- ]) {
652
- pipeline = pipeline.hdel(`${REDIS_PREFIX}settings`, `${id}${key}`);
602
+ if (backfillCount) {
603
+ await backfillReq.exec();
604
+ logger.info({ msg: 'Linked existing accounts to migrated OAuth2 apps', accounts: backfillCount });
605
+ }
606
+ }
607
+ } finally {
608
+ await lock.releaseLock(migrateLock);
653
609
  }
654
- await pipeline.exec();
655
610
 
656
- return {
657
- id,
658
- deleted: true,
659
- legacy: true
660
- };
611
+ return migrated;
661
612
  }
662
613
 
663
614
  async get(id) {
664
- if (LEGACY_KEYS.includes(id)) {
665
- // legacy
666
- let data = await this.getLegacyApp(id);
667
- data.includeInListing = !!data.enabled;
668
- if (SERVICE_ACCOUNT_PROVIDERS.has(data.provider)) {
669
- // service account are always enabled
670
- data.enabled = true;
671
- data.includeInListing = false;
672
- }
673
- return data;
674
- }
675
-
676
615
  let [getDataBuf, getMetaBuf] = await this.redis.hmgetBuffer(this.getDataKey(), [`${id}:data`, `${id}:meta`]);
677
616
  if (!getDataBuf) {
678
617
  return false;
@@ -682,7 +621,7 @@ class OAuth2AppsHandler {
682
621
  try {
683
622
  data = msgpack.decode(getDataBuf);
684
623
  } catch (err) {
685
- logger.error({ msg: 'Failed to process app', app: id, entryLength: getDataBuf?.length || 0 });
624
+ logger.error({ msg: 'Failed to process app', app: id, entryLength: getDataBuf?.length || 0, err });
686
625
  throw err;
687
626
  }
688
627
 
@@ -690,7 +629,7 @@ class OAuth2AppsHandler {
690
629
  try {
691
630
  data.meta = msgpack.decode(getMetaBuf);
692
631
  } catch (err) {
693
- logger.error({ msg: 'Failed to process app meta', app: id, entryLength: getMetaBuf?.length || 0 });
632
+ logger.error({ msg: 'Failed to process app meta', app: id, entryLength: getMetaBuf?.length || 0, err });
694
633
  }
695
634
  }
696
635
 
@@ -706,8 +645,9 @@ class OAuth2AppsHandler {
706
645
  return data;
707
646
  }
708
647
 
709
- async create(data) {
710
- const id = await this.generateId();
648
+ async create(data, opts) {
649
+ // opts.id is internal-only: migrateLegacyApps() preserves the historical legacy app IDs
650
+ const id = (opts && opts.id) || (await this.generateId());
711
651
 
712
652
  let encryptedValues = {};
713
653
  for (let key of ENCRYPTED_APP_KEYS) {
@@ -766,11 +706,6 @@ class OAuth2AppsHandler {
766
706
  delete data.tenant;
767
707
  }
768
708
 
769
- if (LEGACY_KEYS.includes(id)) {
770
- // legacy
771
- return await this.updateLegacyApp(id, data);
772
- }
773
-
774
709
  let existingDataBuf = await this.redis.hgetBuffer(this.getDataKey(), `${id}:data`);
775
710
  if (!existingDataBuf) {
776
711
  let err = new Error('Document was not found');
@@ -851,11 +786,6 @@ class OAuth2AppsHandler {
851
786
  }
852
787
 
853
788
  async del(id) {
854
- if (LEGACY_KEYS.includes(id)) {
855
- // legacy
856
- return await this.delLegacyApp(id);
857
- }
858
-
859
789
  let appData = await this.get(id);
860
790
 
861
791
  if (!appData) {
@@ -989,9 +919,12 @@ class OAuth2AppsHandler {
989
919
 
990
920
  async _retryDeleteOnce(doDelete, appData, resourceType, resourceName, delay, reason) {
991
921
  logger.warn({
992
- msg: `${reason} deleting Pub/Sub ${resourceType}, retrying in ${delay}ms`,
922
+ msg: 'Failed to delete Pub/Sub resource, retrying',
993
923
  app: appData.id,
994
- [resourceType]: resourceName
924
+ resourceType,
925
+ resource: resourceName,
926
+ delay,
927
+ reason
995
928
  });
996
929
  await new Promise(resolve => setTimeout(resolve, delay));
997
930
  try {
@@ -999,17 +932,20 @@ class OAuth2AppsHandler {
999
932
  } catch (retryErr) {
1000
933
  if (retryErr?.oauthRequest?.response?.error?.code === 404) {
1001
934
  logger.info({
1002
- msg: `${resourceType} no longer exists after retry`,
935
+ msg: 'Pub/Sub resource no longer exists after retry',
1003
936
  app: appData.id,
1004
- [resourceType]: resourceName
937
+ resourceType,
938
+ resource: resourceName
1005
939
  });
1006
940
  return;
1007
941
  }
1008
- logger.error({
1009
- msg: `Retry failed deleting Pub/Sub ${resourceType}, resource may need manual cleanup`,
942
+ // warn only: the rethrown error is logged once at error level by the del() caller
943
+ logger.warn({
944
+ msg: 'Failed to delete Pub/Sub resource on retry, resource may need manual cleanup',
1010
945
  app: appData.id,
1011
- [resourceType]: resourceName,
1012
- code: retryErr.code || retryErr?.oauthRequest?.response?.error?.code
946
+ resourceType,
947
+ resource: resourceName,
948
+ err: retryErr
1013
949
  });
1014
950
  throw retryErr;
1015
951
  }
@@ -1026,14 +962,17 @@ class OAuth2AppsHandler {
1026
962
  } catch (err) {
1027
963
  switch (err?.oauthRequest?.response?.error?.code) {
1028
964
  case 403:
1029
- logger.error({
1030
- msg: `Service client does not have permissions to delete Pub/Sub ${resourceType}s. Make sure the role for the service user is "Pub/Sub Admin".`,
965
+ // warn only: the rethrown error is logged once at error level by the del() caller
966
+ logger.warn({
967
+ msg: 'Service client does not have permission to delete Pub/Sub resource',
1031
968
  app: appData.id,
1032
- [resourceType]: resourceName
969
+ resourceType,
970
+ resource: resourceName,
971
+ requiredRole: 'Pub/Sub Admin'
1033
972
  });
1034
973
  throw err;
1035
974
  case 404:
1036
- logger.info({ msg: `${resourceType} does not exist`, app: appData.id, [resourceType]: resourceName });
975
+ logger.info({ msg: 'Pub/Sub resource does not exist', app: appData.id, resourceType, resource: resourceName });
1037
976
  break;
1038
977
  case 429: {
1039
978
  let retryAfter = err.retryAfter || err.oauthRequest?.retryAfter;
@@ -1114,11 +1053,15 @@ class OAuth2AppsHandler {
1114
1053
  try {
1115
1054
  ensureLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 2 * 60 * 1000);
1116
1055
  if (!ensureLock.success) {
1117
- logger.error({ msg: 'Failed to get ensurePubsub lock', lockKey });
1056
+ // contention: timed out waiting for the current lock holder
1057
+ logger.warn({ msg: 'Failed to get ensurePubsub lock, timed out waiting for the current holder', app: appData.id, lockKey });
1118
1058
  throw new Error('Failed to get ensurePubsub lock');
1119
1059
  }
1120
1060
  } catch (err) {
1121
- logger.error({ msg: 'Failed to get ensurePubsub lock', lockKey, err });
1061
+ if (!ensureLock) {
1062
+ // unexpected lock-layer error; contention was already logged above
1063
+ logger.error({ msg: 'Failed to get ensurePubsub lock', app: appData.id, lockKey, err });
1064
+ }
1122
1065
  throw err;
1123
1066
  }
1124
1067
 
@@ -1553,14 +1496,10 @@ class OAuth2AppsHandler {
1553
1496
  workspaceAccounts,
1554
1497
  setFlag: async flag => {
1555
1498
  try {
1556
- if (appData.legacy) {
1557
- await settings.set('gmailAuthFlag', flag);
1558
- } else {
1559
- await this.setMeta(id, { authFlag: flag });
1560
- }
1499
+ await this.setMeta(id, { authFlag: flag });
1561
1500
  } catch (err) {
1562
1501
  // Log but don't throw - flag setting is non-critical
1563
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'gmail', err });
1502
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'gmail', err });
1564
1503
  }
1565
1504
  }
1566
1505
  },
@@ -1601,14 +1540,10 @@ class OAuth2AppsHandler {
1601
1540
  workspaceAccounts,
1602
1541
  setFlag: async flag => {
1603
1542
  try {
1604
- if (appData.legacy) {
1605
- await settings.set('gmailServiceAuthFlag', flag);
1606
- } else {
1607
- await this.setMeta(id, { authFlag: flag });
1608
- }
1543
+ await this.setMeta(id, { authFlag: flag });
1609
1544
  } catch (err) {
1610
1545
  // Log but don't throw - flag setting is non-critical
1611
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'gmailService', err });
1546
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'gmailService', err });
1612
1547
  }
1613
1548
  }
1614
1549
  },
@@ -1643,14 +1578,10 @@ class OAuth2AppsHandler {
1643
1578
  cloud,
1644
1579
  setFlag: async flag => {
1645
1580
  try {
1646
- if (appData.legacy) {
1647
- await settings.set('outlookAuthFlag', flag);
1648
- } else {
1649
- await this.setMeta(id, { authFlag: flag });
1650
- }
1581
+ await this.setMeta(id, { authFlag: flag });
1651
1582
  } catch (err) {
1652
1583
  // Log but don't throw - flag setting is non-critical
1653
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'outlook', err });
1584
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'outlook', err });
1654
1585
  }
1655
1586
  }
1656
1587
  },
@@ -1685,7 +1616,7 @@ class OAuth2AppsHandler {
1685
1616
  try {
1686
1617
  await this.setMeta(id, { authFlag: flag });
1687
1618
  } catch (err) {
1688
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'outlookService', err });
1619
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'outlookService', err });
1689
1620
  }
1690
1621
  }
1691
1622
  },
@@ -1714,14 +1645,10 @@ class OAuth2AppsHandler {
1714
1645
  scopes,
1715
1646
  setFlag: async flag => {
1716
1647
  try {
1717
- if (appData.legacy) {
1718
- await settings.set('mailRuAuthFlag', flag);
1719
- } else {
1720
- await this.setMeta(id, { authFlag: flag });
1721
- }
1648
+ await this.setMeta(id, { authFlag: flag });
1722
1649
  } catch (err) {
1723
1650
  // Log but don't throw - flag setting is non-critical
1724
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'mailRu', err });
1651
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'mailRu', err });
1725
1652
  }
1726
1653
  }
1727
1654
  },
@@ -1754,11 +1681,15 @@ class OAuth2AppsHandler {
1754
1681
  try {
1755
1682
  renewLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
1756
1683
  if (!renewLock.success) {
1757
- logger.error({ msg: 'Failed to get lock', lockKey });
1684
+ // contention: timed out waiting for the current lock holder
1685
+ logger.warn({ msg: 'Failed to get renewal lock, timed out waiting for the current holder', app: appData.id, lockKey });
1758
1686
  throw new Error('Failed to get renewal lock');
1759
1687
  }
1760
1688
  } catch (err) {
1761
- logger.error({ msg: 'Failed to get lock', lockKey, err });
1689
+ if (!renewLock) {
1690
+ // unexpected lock-layer error; contention was already logged above
1691
+ logger.error({ msg: 'Failed to get renewal lock', app: appData.id, lockKey, err });
1692
+ }
1762
1693
  let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
1763
1694
  if (err.code) {
1764
1695
  error.output.payload.code = err.code || 'LockFail';
@@ -1808,12 +1739,11 @@ class OAuth2AppsHandler {
1808
1739
  const statusCode = err.statusCode || err.tokenRequest?.status || 0;
1809
1740
  recordTokenMetric('failure', appData.provider || 'unknown', statusCode);
1810
1741
 
1811
- logger.info({
1742
+ logger.warn({
1812
1743
  msg: 'Failed to renew OAuth2 access token',
1813
1744
  action: 'getServiceAccessToken',
1814
- error: err,
1815
- response: err.tokenRequest && err.tokenRequest.response,
1816
- flag: err.tokenRequest && err.tokenRequest.flag
1745
+ app: appData.id,
1746
+ err
1817
1747
  });
1818
1748
  throw err;
1819
1749
  } finally {
@@ -1833,7 +1763,6 @@ module.exports = {
1833
1763
  oauth2Apps: new OAuth2AppsHandler({ redis }),
1834
1764
  OAUTH_PROVIDERS,
1835
1765
  SERVICE_ACCOUNT_PROVIDERS,
1836
- LEGACY_KEYS,
1837
1766
  oauth2ProviderData,
1838
1767
  formatExtraScopes,
1839
1768
  isApiBasedApp