emailengine-app 2.78.0 → 2.79.1

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 (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -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 +112 -36
  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 +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  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 +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. 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,237 @@ 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 last, after the app
422
+ // records and the account backfill, which is what makes the migration both idempotent and
423
+ // crash-safe: as long as any source key remains, the next startup re-enters and repeats
424
+ // whichever steps are missing (create() is guarded by an existence check and the backfill
425
+ // is an idempotent SADD). A Redis lock guards against parallel instances sharing one
426
+ // Redis. Returns the list of migrated app IDs.
427
+ async migrateLegacyApps() {
428
+ // Full per-app settings key suffixes ever used by the legacy configuration
429
+ const FIELDS = [
430
+ 'Enabled',
431
+ 'RedirectUrl',
432
+ 'Client',
433
+ 'ClientId',
434
+ 'ClientSecret',
435
+ 'Authority',
436
+ 'ExtraScopes',
437
+ 'SkipScopes',
438
+ 'Key',
439
+ 'AuthFlag',
440
+ 'AuthMethod',
441
+ 'ExternalAccount'
442
+ ];
443
+
444
+ // Even older generic service-account keys with no reader left anywhere; dropped without migration
445
+ const ORPHAN_KEYS = ['serviceClient', 'serviceKey', 'serviceExtraScopes'];
446
+
447
+ const candidateKeys = LEGACY_KEYS.flatMap(id => FIELDS.map(field => `${id}${field}`)).concat(ORPHAN_KEYS);
448
+
449
+ // One batched read for every legacy key; settings.getMulti() also decrypts stored secrets
450
+ const readLegacyValues = async () => await settings.getMulti(...candidateKeys);
451
+ const hasValues = values => Object.values(values).some(value => value !== null);
452
+
453
+ // cheap presence probe before taking the lock
454
+ if (!hasValues(await readLegacyValues())) {
455
+ return [];
446
456
  }
447
- extraScopes = extraScopes.filter(entry => entry);
448
457
 
449
- let skipScopes = await settings.get(`${id}SkipScopes`);
450
- if (!Array.isArray(skipScopes)) {
451
- skipScopes = (skipScopes || '').toString().split(/[\s,]+/);
458
+ let migrateLock = await lock.waitAcquireLock('oauth:legacy:migrate', 5 * 60 * 1000, 2 * 60 * 1000);
459
+ if (!migrateLock.success) {
460
+ throw new Error('Failed to get lock for the legacy OAuth2 app migration');
452
461
  }
453
- skipScopes = skipScopes.filter(entry => entry);
454
462
 
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;
463
+ let migrated = [];
464
+ try {
465
+ // re-read inside the lock: another instance may have finished the migration already
466
+ let values = await readLegacyValues();
467
+ if (!hasValues(values)) {
468
+ return [];
476
469
  }
477
470
 
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
- },
471
+ const normalizeScopes = value => {
472
+ if (!Array.isArray(value)) {
473
+ value = (value || '').toString().split(/[\s,]+/);
474
+ }
475
+ return value.filter(entry => entry);
476
+ };
498
477
 
499
- enabled: true
500
- };
501
- return appData;
502
- }
478
+ // A stored secret whose decryption failed (a rotated or missing service secret) reads
479
+ // back as null through settings.getMulti(), exactly like an absent key. Deleting the
480
+ // source keys in that state would destroy the only copy of the ciphertext, so probe
481
+ // the raw hash to tell the two apart and leave such an app entirely untouched - the
482
+ // migration retries on the next startup, and restoring the correct service secret
483
+ // makes it whole again.
484
+ const encryptedCandidates = candidateKeys.filter(key => settings.encryptedKeys.includes(key));
485
+ const rawEncryptedValues = await this.redis.hmget(this.getSettingsKey(), encryptedCandidates);
486
+ const undecryptable = new Set(encryptedCandidates.filter((key, i) => rawEncryptedValues[i] !== null && values[key] === null));
487
+
488
+ // Apps whose accounts should be (re-)linked, and apps whose source keys may be dropped
489
+ let backfillable = [];
490
+ let clearable = [];
491
+
492
+ for (let legacyKey of LEGACY_KEYS) {
493
+ const v = field => values[`${legacyKey}${field}`];
494
+
495
+ let failedKeys = FIELDS.map(field => `${legacyKey}${field}`).filter(key => undecryptable.has(key));
496
+ if (failedKeys.length) {
497
+ logger.error({
498
+ msg: 'Skipped legacy OAuth2 app migration: stored credentials could not be decrypted. Restore the original service secret and restart',
499
+ app: legacyKey,
500
+ keys: failedKeys
501
+ });
502
+ continue;
503
+ }
503
504
 
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`)
522
- }
523
- };
524
- return appData;
525
- }
505
+ // Same visibility rule the legacy listing applied: an app existed when it was
506
+ // enabled or had a client configured. Stray keys without either (e.g. only a
507
+ // redirect URL) never surfaced an app and are just cleaned up.
508
+ let visible = !!(v('Enabled') || v('Client') || v('ClientId'));
509
+
510
+ let exists = await this.redis.hexists(this.getDataKey(), `${legacyKey}:data`);
511
+
512
+ if (visible && !exists) {
513
+ let entry = {
514
+ provider: legacyKey,
515
+ // legacy apps never separated IMAP and API access; they always used IMAP scopes
516
+ baseScopes: 'imap',
517
+ description: 'Migrated from the deprecated settings-based OAuth2 configuration',
518
+ enabled: !!v('Enabled'),
519
+ extraScopes: normalizeScopes(v('ExtraScopes')),
520
+ skipScopes: normalizeScopes(v('SkipScopes'))
521
+ };
526
522
 
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`)
523
+ switch (legacyKey) {
524
+ case 'gmail':
525
+ entry.name = 'Gmail';
526
+ entry.clientId = v('ClientId');
527
+ entry.clientSecret = v('ClientSecret');
528
+ entry.redirectUrl = v('RedirectUrl');
529
+ break;
530
+
531
+ case 'gmailService':
532
+ entry.name = 'Gmail service';
533
+ entry.authMethod = v('AuthMethod') === 'externalAccount' ? 'externalAccount' : 'serviceKey';
534
+ entry.serviceClient = v('Client');
535
+ entry.serviceKey = v('Key');
536
+ entry.externalAccount = v('ExternalAccount');
537
+ // service apps are always treated as enabled
538
+ entry.enabled = true;
539
+ break;
540
+
541
+ case 'outlook':
542
+ entry.name = 'Outlook (delegated)';
543
+ entry.clientId = v('ClientId');
544
+ entry.clientSecret = v('ClientSecret');
545
+ entry.redirectUrl = v('RedirectUrl');
546
+ entry.authority = v('Authority');
547
+ // legacy config predates sovereign cloud support
548
+ entry.cloud = 'global';
549
+ break;
550
+
551
+ case 'mailRu':
552
+ entry.name = 'Mail.ru';
553
+ entry.clientId = v('ClientId');
554
+ entry.clientSecret = v('ClientSecret');
555
+ entry.redirectUrl = v('RedirectUrl');
556
+ break;
544
557
  }
545
- };
546
- return appData;
547
- }
548
-
549
- default:
550
- return false;
551
- }
552
- }
553
558
 
554
- async updateLegacyApp(id, updates) {
555
- updates = updates || {};
559
+ // Absent legacy keys read as nulls; drop them so the stored record looks like a
560
+ // regular app entry (joi does the equivalent stripping for created apps)
561
+ for (let key of Object.keys(entry)) {
562
+ if (entry[key] === null || typeof entry[key] === 'undefined' || entry[key] === '') {
563
+ delete entry[key];
564
+ }
565
+ }
556
566
 
557
- let data = {};
567
+ // create() owns the record shape: it encrypts secret fields and stamps `created`
568
+ await this.create(entry, { id: legacyKey });
558
569
 
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];
570
+ if (v('AuthFlag')) {
571
+ await this.setMeta(legacyKey, { authFlag: v('AuthFlag') });
564
572
  }
565
- }
566
- break;
567
573
 
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
- }
574
+ migrated.push(legacyKey);
575
+ logger.info({ msg: 'Migrated legacy OAuth2 app to the app registry', app: legacyKey, enabled: entry.enabled });
577
576
  }
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
- }
577
+
578
+ if (visible) {
579
+ // Whether the record was created now or by an earlier interrupted run: as long
580
+ // as the source keys are still around the backfill below has not been confirmed
581
+ // done, and repeating it is a no-op
582
+ backfillable.push(legacyKey);
599
583
  }
600
- break;
584
+
585
+ clearable.push(legacyKey);
601
586
  }
602
587
 
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];
588
+ // Backfill the per-app account membership sets that the legacy code never maintained,
589
+ // so account counts and app deletion safety checks see the existing accounts. The
590
+ // per-user binding hash (oapp:h:*) is left to repopulate on the next account update.
591
+ if (backfillable.length) {
592
+ let backfillableSet = new Set(backfillable);
593
+ let accounts = await this.redis.smembers(`${REDIS_PREFIX}ia:accounts`);
594
+ let backfillReq = this.redis.multi();
595
+ let backfillCount = 0;
596
+
597
+ // read account data in pipelined chunks; large legacy installs can hold tens of
598
+ // thousands of accounts and sequential reads would stall startup
599
+ const CHUNK_SIZE = 500;
600
+ for (let i = 0; i < accounts.length; i += CHUNK_SIZE) {
601
+ let chunk = accounts.slice(i, i + CHUNK_SIZE);
602
+ let readReq = this.redis.pipeline();
603
+ for (let account of chunk) {
604
+ readReq = readReq.hget(`${REDIS_PREFIX}iad:${account}`, 'oauth2');
607
605
  }
608
- }
606
+ let rows = await readReq.exec();
609
607
 
610
- break;
611
-
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];
608
+ for (let j = 0; j < chunk.length; j++) {
609
+ let [err, oauth2Json] = rows[j];
610
+ if (err || !oauth2Json) {
611
+ continue;
612
+ }
613
+ let oauth2Data;
614
+ try {
615
+ oauth2Data = JSON.parse(oauth2Json);
616
+ } catch (parseErr) {
617
+ continue;
618
+ }
619
+ if (oauth2Data && oauth2Data.provider && backfillableSet.has(oauth2Data.provider)) {
620
+ backfillReq = backfillReq.sadd(`${REDIS_PREFIX}oapp:a:${oauth2Data.provider}`, chunk[j]);
621
+ backfillCount++;
622
+ }
616
623
  }
617
624
  }
618
625
 
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`);
626
+ if (backfillCount) {
627
+ await backfillReq.exec();
628
+ logger.info({ msg: 'Linked existing accounts to migrated OAuth2 apps', accounts: backfillCount });
629
+ }
630
+ }
628
631
 
629
- return {
630
- id,
631
- updated: true,
632
- legacy: true
633
- };
634
- }
632
+ // The copy is complete, drop the source settings keys (no-op when unset)
633
+ if (clearable.length) {
634
+ await this.redis.hdel(this.getSettingsKey(), ...clearable.flatMap(legacyKey => FIELDS.map(field => `${legacyKey}${field}`)));
635
+ }
635
636
 
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}`);
637
+ let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...ORPHAN_KEYS);
638
+ if (removedOrphans) {
639
+ logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
640
+ }
641
+ } finally {
642
+ await lock.releaseLock(migrateLock);
653
643
  }
654
- await pipeline.exec();
655
644
 
656
- return {
657
- id,
658
- deleted: true,
659
- legacy: true
660
- };
645
+ return migrated;
661
646
  }
662
647
 
663
648
  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
649
  let [getDataBuf, getMetaBuf] = await this.redis.hmgetBuffer(this.getDataKey(), [`${id}:data`, `${id}:meta`]);
677
650
  if (!getDataBuf) {
678
651
  return false;
@@ -682,7 +655,7 @@ class OAuth2AppsHandler {
682
655
  try {
683
656
  data = msgpack.decode(getDataBuf);
684
657
  } catch (err) {
685
- logger.error({ msg: 'Failed to process app', app: id, entryLength: getDataBuf?.length || 0 });
658
+ logger.error({ msg: 'Failed to process app', app: id, entryLength: getDataBuf?.length || 0, err });
686
659
  throw err;
687
660
  }
688
661
 
@@ -690,7 +663,7 @@ class OAuth2AppsHandler {
690
663
  try {
691
664
  data.meta = msgpack.decode(getMetaBuf);
692
665
  } catch (err) {
693
- logger.error({ msg: 'Failed to process app meta', app: id, entryLength: getMetaBuf?.length || 0 });
666
+ logger.error({ msg: 'Failed to process app meta', app: id, entryLength: getMetaBuf?.length || 0, err });
694
667
  }
695
668
  }
696
669
 
@@ -706,8 +679,9 @@ class OAuth2AppsHandler {
706
679
  return data;
707
680
  }
708
681
 
709
- async create(data) {
710
- const id = await this.generateId();
682
+ async create(data, opts) {
683
+ // opts.id is internal-only: migrateLegacyApps() preserves the historical legacy app IDs
684
+ const id = (opts && opts.id) || (await this.generateId());
711
685
 
712
686
  let encryptedValues = {};
713
687
  for (let key of ENCRYPTED_APP_KEYS) {
@@ -766,11 +740,6 @@ class OAuth2AppsHandler {
766
740
  delete data.tenant;
767
741
  }
768
742
 
769
- if (LEGACY_KEYS.includes(id)) {
770
- // legacy
771
- return await this.updateLegacyApp(id, data);
772
- }
773
-
774
743
  let existingDataBuf = await this.redis.hgetBuffer(this.getDataKey(), `${id}:data`);
775
744
  if (!existingDataBuf) {
776
745
  let err = new Error('Document was not found');
@@ -851,11 +820,6 @@ class OAuth2AppsHandler {
851
820
  }
852
821
 
853
822
  async del(id) {
854
- if (LEGACY_KEYS.includes(id)) {
855
- // legacy
856
- return await this.delLegacyApp(id);
857
- }
858
-
859
823
  let appData = await this.get(id);
860
824
 
861
825
  if (!appData) {
@@ -945,6 +909,41 @@ class OAuth2AppsHandler {
945
909
  }
946
910
  }
947
911
 
912
+ // Auth-failure flags of every registered app, for the site-wide admin alert (see the view
913
+ // context in workers/api.js). Reads only the meta entries - one SMEMBERS plus one HMGET
914
+ // however many apps exist - because it runs on every admin page render.
915
+ async listAuthFlags() {
916
+ // sorted only so the alert order is stable across renders
917
+ let idList = (await this.redis.smembers(this.getIndexKey())).sort();
918
+ if (!idList.length) {
919
+ return [];
920
+ }
921
+
922
+ let metaEntries = await this.redis.hmgetBuffer(
923
+ this.getDataKey(),
924
+ idList.map(id => `${id}:meta`)
925
+ );
926
+
927
+ let flags = [];
928
+ for (let i = 0; i < idList.length; i++) {
929
+ if (!metaEntries[i]) {
930
+ continue;
931
+ }
932
+ let meta;
933
+ try {
934
+ meta = msgpack.decode(metaEntries[i]);
935
+ } catch (err) {
936
+ logger.error({ msg: 'Failed to process app meta', app: idList[i], entryLength: metaEntries[i].length, err });
937
+ continue;
938
+ }
939
+ if (meta && meta.authFlag && meta.authFlag.message) {
940
+ flags.push({ app: idList[i], authFlag: meta.authFlag });
941
+ }
942
+ }
943
+
944
+ return flags;
945
+ }
946
+
948
947
  // Note: not atomic (read-modify-write). Concurrent callers use last-write-wins,
949
948
  // which is acceptable for self-correcting informational metadata.
950
949
  async setMeta(id, meta) {
@@ -989,9 +988,12 @@ class OAuth2AppsHandler {
989
988
 
990
989
  async _retryDeleteOnce(doDelete, appData, resourceType, resourceName, delay, reason) {
991
990
  logger.warn({
992
- msg: `${reason} deleting Pub/Sub ${resourceType}, retrying in ${delay}ms`,
991
+ msg: 'Failed to delete Pub/Sub resource, retrying',
993
992
  app: appData.id,
994
- [resourceType]: resourceName
993
+ resourceType,
994
+ resource: resourceName,
995
+ delay,
996
+ reason
995
997
  });
996
998
  await new Promise(resolve => setTimeout(resolve, delay));
997
999
  try {
@@ -999,17 +1001,20 @@ class OAuth2AppsHandler {
999
1001
  } catch (retryErr) {
1000
1002
  if (retryErr?.oauthRequest?.response?.error?.code === 404) {
1001
1003
  logger.info({
1002
- msg: `${resourceType} no longer exists after retry`,
1004
+ msg: 'Pub/Sub resource no longer exists after retry',
1003
1005
  app: appData.id,
1004
- [resourceType]: resourceName
1006
+ resourceType,
1007
+ resource: resourceName
1005
1008
  });
1006
1009
  return;
1007
1010
  }
1008
- logger.error({
1009
- msg: `Retry failed deleting Pub/Sub ${resourceType}, resource may need manual cleanup`,
1011
+ // warn only: the rethrown error is logged once at error level by the del() caller
1012
+ logger.warn({
1013
+ msg: 'Failed to delete Pub/Sub resource on retry, resource may need manual cleanup',
1010
1014
  app: appData.id,
1011
- [resourceType]: resourceName,
1012
- code: retryErr.code || retryErr?.oauthRequest?.response?.error?.code
1015
+ resourceType,
1016
+ resource: resourceName,
1017
+ err: retryErr
1013
1018
  });
1014
1019
  throw retryErr;
1015
1020
  }
@@ -1026,14 +1031,17 @@ class OAuth2AppsHandler {
1026
1031
  } catch (err) {
1027
1032
  switch (err?.oauthRequest?.response?.error?.code) {
1028
1033
  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".`,
1034
+ // warn only: the rethrown error is logged once at error level by the del() caller
1035
+ logger.warn({
1036
+ msg: 'Service client does not have permission to delete Pub/Sub resource',
1031
1037
  app: appData.id,
1032
- [resourceType]: resourceName
1038
+ resourceType,
1039
+ resource: resourceName,
1040
+ requiredRole: 'Pub/Sub Admin'
1033
1041
  });
1034
1042
  throw err;
1035
1043
  case 404:
1036
- logger.info({ msg: `${resourceType} does not exist`, app: appData.id, [resourceType]: resourceName });
1044
+ logger.info({ msg: 'Pub/Sub resource does not exist', app: appData.id, resourceType, resource: resourceName });
1037
1045
  break;
1038
1046
  case 429: {
1039
1047
  let retryAfter = err.retryAfter || err.oauthRequest?.retryAfter;
@@ -1114,11 +1122,15 @@ class OAuth2AppsHandler {
1114
1122
  try {
1115
1123
  ensureLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 2 * 60 * 1000);
1116
1124
  if (!ensureLock.success) {
1117
- logger.error({ msg: 'Failed to get ensurePubsub lock', lockKey });
1125
+ // contention: timed out waiting for the current lock holder
1126
+ logger.warn({ msg: 'Failed to get ensurePubsub lock, timed out waiting for the current holder', app: appData.id, lockKey });
1118
1127
  throw new Error('Failed to get ensurePubsub lock');
1119
1128
  }
1120
1129
  } catch (err) {
1121
- logger.error({ msg: 'Failed to get ensurePubsub lock', lockKey, err });
1130
+ if (!ensureLock) {
1131
+ // unexpected lock-layer error; contention was already logged above
1132
+ logger.error({ msg: 'Failed to get ensurePubsub lock', app: appData.id, lockKey, err });
1133
+ }
1122
1134
  throw err;
1123
1135
  }
1124
1136
 
@@ -1553,14 +1565,10 @@ class OAuth2AppsHandler {
1553
1565
  workspaceAccounts,
1554
1566
  setFlag: async flag => {
1555
1567
  try {
1556
- if (appData.legacy) {
1557
- await settings.set('gmailAuthFlag', flag);
1558
- } else {
1559
- await this.setMeta(id, { authFlag: flag });
1560
- }
1568
+ await this.setMeta(id, { authFlag: flag });
1561
1569
  } catch (err) {
1562
1570
  // Log but don't throw - flag setting is non-critical
1563
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'gmail', err });
1571
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'gmail', err });
1564
1572
  }
1565
1573
  }
1566
1574
  },
@@ -1601,14 +1609,10 @@ class OAuth2AppsHandler {
1601
1609
  workspaceAccounts,
1602
1610
  setFlag: async flag => {
1603
1611
  try {
1604
- if (appData.legacy) {
1605
- await settings.set('gmailServiceAuthFlag', flag);
1606
- } else {
1607
- await this.setMeta(id, { authFlag: flag });
1608
- }
1612
+ await this.setMeta(id, { authFlag: flag });
1609
1613
  } catch (err) {
1610
1614
  // Log but don't throw - flag setting is non-critical
1611
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'gmailService', err });
1615
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'gmailService', err });
1612
1616
  }
1613
1617
  }
1614
1618
  },
@@ -1643,14 +1647,10 @@ class OAuth2AppsHandler {
1643
1647
  cloud,
1644
1648
  setFlag: async flag => {
1645
1649
  try {
1646
- if (appData.legacy) {
1647
- await settings.set('outlookAuthFlag', flag);
1648
- } else {
1649
- await this.setMeta(id, { authFlag: flag });
1650
- }
1650
+ await this.setMeta(id, { authFlag: flag });
1651
1651
  } catch (err) {
1652
1652
  // Log but don't throw - flag setting is non-critical
1653
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'outlook', err });
1653
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'outlook', err });
1654
1654
  }
1655
1655
  }
1656
1656
  },
@@ -1685,7 +1685,7 @@ class OAuth2AppsHandler {
1685
1685
  try {
1686
1686
  await this.setMeta(id, { authFlag: flag });
1687
1687
  } catch (err) {
1688
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'outlookService', err });
1688
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'outlookService', err });
1689
1689
  }
1690
1690
  }
1691
1691
  },
@@ -1714,14 +1714,10 @@ class OAuth2AppsHandler {
1714
1714
  scopes,
1715
1715
  setFlag: async flag => {
1716
1716
  try {
1717
- if (appData.legacy) {
1718
- await settings.set('mailRuAuthFlag', flag);
1719
- } else {
1720
- await this.setMeta(id, { authFlag: flag });
1721
- }
1717
+ await this.setMeta(id, { authFlag: flag });
1722
1718
  } catch (err) {
1723
1719
  // Log but don't throw - flag setting is non-critical
1724
- logger.error({ msg: 'Failed to set OAuth flag', provider: 'mailRu', err });
1720
+ logger.error({ msg: 'Failed to set OAuth flag', app: id, provider: 'mailRu', err });
1725
1721
  }
1726
1722
  }
1727
1723
  },
@@ -1754,11 +1750,15 @@ class OAuth2AppsHandler {
1754
1750
  try {
1755
1751
  renewLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
1756
1752
  if (!renewLock.success) {
1757
- logger.error({ msg: 'Failed to get lock', lockKey });
1753
+ // contention: timed out waiting for the current lock holder
1754
+ logger.warn({ msg: 'Failed to get renewal lock, timed out waiting for the current holder', app: appData.id, lockKey });
1758
1755
  throw new Error('Failed to get renewal lock');
1759
1756
  }
1760
1757
  } catch (err) {
1761
- logger.error({ msg: 'Failed to get lock', lockKey, err });
1758
+ if (!renewLock) {
1759
+ // unexpected lock-layer error; contention was already logged above
1760
+ logger.error({ msg: 'Failed to get renewal lock', app: appData.id, lockKey, err });
1761
+ }
1762
1762
  let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
1763
1763
  if (err.code) {
1764
1764
  error.output.payload.code = err.code || 'LockFail';
@@ -1808,12 +1808,11 @@ class OAuth2AppsHandler {
1808
1808
  const statusCode = err.statusCode || err.tokenRequest?.status || 0;
1809
1809
  recordTokenMetric('failure', appData.provider || 'unknown', statusCode);
1810
1810
 
1811
- logger.info({
1811
+ logger.warn({
1812
1812
  msg: 'Failed to renew OAuth2 access token',
1813
1813
  action: 'getServiceAccessToken',
1814
- error: err,
1815
- response: err.tokenRequest && err.tokenRequest.response,
1816
- flag: err.tokenRequest && err.tokenRequest.flag
1814
+ app: appData.id,
1815
+ err
1817
1816
  });
1818
1817
  throw err;
1819
1818
  } finally {
@@ -1833,7 +1832,6 @@ module.exports = {
1833
1832
  oauth2Apps: new OAuth2AppsHandler({ redis }),
1834
1833
  OAUTH_PROVIDERS,
1835
1834
  SERVICE_ACCOUNT_PROVIDERS,
1836
- LEGACY_KEYS,
1837
1835
  oauth2ProviderData,
1838
1836
  formatExtraScopes,
1839
1837
  isApiBasedApp