emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
package/lib/metrics.js ADDED
@@ -0,0 +1,320 @@
1
+ 'use strict';
2
+
3
+ // The Prometheus metrics the main thread keeps, and the client library behind them. server.js
4
+ // creates them once; test/metrics-test.js pins their names, types, help texts and labels, which are
5
+ // what dashboards and alerts are written against.
6
+
7
+ const promClient = require('@prometheus-io/client');
8
+
9
+ /**
10
+ * Prometheus metrics definitions for monitoring. Each call registers them on the default registry,
11
+ * so it is called once per process.
12
+ *
13
+ * @returns {Object}
14
+ */
15
+ function createMetrics() {
16
+ return {
17
+ threadStarts: new promClient.Counter({
18
+ name: 'thread_starts',
19
+ help: 'Number of started threads'
20
+ }),
21
+
22
+ threadStops: new promClient.Counter({
23
+ name: 'thread_stops',
24
+ help: 'Number of stopped threads'
25
+ }),
26
+
27
+ apiCall: new promClient.Counter({
28
+ name: 'api_call',
29
+ help: 'Number of API calls',
30
+ labelNames: ['method', 'statusCode', 'route']
31
+ }),
32
+
33
+ // Labelled by route, not by status: the counter above already splits by status, and a latency
34
+ // series per status code would multiply the route count for little an operator can act on
35
+ apiCallDuration: new promClient.Histogram({
36
+ name: 'api_call_duration_seconds',
37
+ help: 'Duration of API calls, from receiving the request to sending the response',
38
+ labelNames: ['method', 'route'],
39
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60]
40
+ }),
41
+
42
+ imapConnections: new promClient.Gauge({
43
+ name: 'imap_connections',
44
+ help: 'Current IMAP connection state',
45
+ labelNames: ['status']
46
+ }),
47
+
48
+ imapResponses: new promClient.Counter({
49
+ name: 'imap_responses',
50
+ help: 'IMAP responses',
51
+ labelNames: ['response', 'code']
52
+ }),
53
+
54
+ imapBytesSent: new promClient.Counter({
55
+ name: 'imap_bytes_sent',
56
+ help: 'IMAP bytes sent'
57
+ }),
58
+
59
+ imapBytesReceived: new promClient.Counter({
60
+ name: 'imap_bytes_received',
61
+ help: 'IMAP bytes received'
62
+ }),
63
+
64
+ oauth2TokenRefresh: new promClient.Counter({
65
+ name: 'oauth2_token_refresh',
66
+ help: 'OAuth2 access token refresh attempts',
67
+ labelNames: ['status', 'provider', 'statusCode']
68
+ }),
69
+
70
+ oauth2ApiRequest: new promClient.Counter({
71
+ name: 'oauth2_api_request',
72
+ help: 'OAuth2 API requests (MS Graph, Gmail API)',
73
+ labelNames: ['status', 'provider', 'statusCode']
74
+ }),
75
+
76
+ outlookMissedRecovery: new promClient.Counter({
77
+ name: 'outlook_missed_recovery',
78
+ help: 'MS Graph missed-notification recovery passes, by what asked for them and whether they found unannounced messages',
79
+ labelNames: ['reason', 'outcome']
80
+ }),
81
+
82
+ outlookMissedRecoveredMessages: new promClient.Counter({
83
+ name: 'outlook_missed_recovered_messages',
84
+ help: 'New messages announced by MS Graph missed-notification recovery instead of by a change notification',
85
+ labelNames: ['reason']
86
+ }),
87
+
88
+ outlookSubscriptions: new promClient.Gauge({
89
+ name: 'outlook_subscriptions',
90
+ help: 'MS Graph webhook subscription states',
91
+ labelNames: ['status']
92
+ }),
93
+
94
+ webhooks: new promClient.Counter({
95
+ name: 'webhooks',
96
+ help: 'Webhooks sent',
97
+ labelNames: ['status', 'event']
98
+ }),
99
+
100
+ events: new promClient.Counter({
101
+ name: 'events',
102
+ help: 'Events fired',
103
+ labelNames: ['event']
104
+ }),
105
+
106
+ aiRequests: new promClient.Counter({
107
+ name: 'ai_requests',
108
+ help: 'AI summary requests',
109
+ labelNames: ['model', 'status']
110
+ }),
111
+
112
+ aiTokens: new promClient.Counter({
113
+ name: 'ai_tokens',
114
+ help: 'Tokens billed for AI summary requests',
115
+ labelNames: ['model', 'type']
116
+ }),
117
+
118
+ webhookReq: new promClient.Histogram({
119
+ name: 'webhook_req',
120
+ help: 'Duration of webhook requests',
121
+ buckets: [100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000, 60 * 1000]
122
+ }),
123
+
124
+ queues: new promClient.Gauge({
125
+ name: 'queue_size',
126
+ help: 'Queue size',
127
+ labelNames: ['queue', 'state']
128
+ }),
129
+
130
+ queueFailed: new promClient.Gauge({
131
+ name: 'queue_failed_jobs',
132
+ help: 'Failed jobs a queue still retains (deliveries that were given up on)',
133
+ labelNames: ['queue']
134
+ }),
135
+
136
+ queuesProcessed: new promClient.Counter({
137
+ name: 'queues_processed',
138
+ help: 'Processed job count',
139
+ labelNames: ['queue', 'status']
140
+ }),
141
+
142
+ threads: new promClient.Gauge({
143
+ name: 'threads',
144
+ help: 'Worker Threads',
145
+ labelNames: ['type', 'recent']
146
+ }),
147
+
148
+ unresponsiveWorkers: new promClient.Gauge({
149
+ name: 'unresponsive_workers',
150
+ help: 'Number of unresponsive worker threads'
151
+ }),
152
+
153
+ threadEventLoopDelayMax: new promClient.Gauge({
154
+ name: 'thread_event_loop_delay_max_seconds',
155
+ help: 'Longest event loop delay of a thread over the last collection window (15s)',
156
+ labelNames: ['type', 'thread']
157
+ }),
158
+
159
+ threadEventLoopDelayP99: new promClient.Gauge({
160
+ name: 'thread_event_loop_delay_p99_seconds',
161
+ help: '99th percentile event loop delay of a thread over the last collection window (15s)',
162
+ labelNames: ['type', 'thread']
163
+ }),
164
+
165
+ threadHeapUsed: new promClient.Gauge({
166
+ name: 'thread_heap_used_bytes',
167
+ help: 'V8 heap in use by a thread, as of the last collection (15s)',
168
+ labelNames: ['type', 'thread']
169
+ }),
170
+
171
+ threadHeapTotal: new promClient.Gauge({
172
+ name: 'thread_heap_total_bytes',
173
+ help: 'V8 heap allocated by a thread, as of the last collection (15s)',
174
+ labelNames: ['type', 'thread']
175
+ }),
176
+
177
+ licenseDaysRemaining: new promClient.Gauge({
178
+ name: 'license_days_remaining',
179
+ help: 'Days until license expires (-1 for lifetime, 0 for no license)'
180
+ }),
181
+
182
+ emailengineConfig: new promClient.Gauge({
183
+ name: 'emailengine_config',
184
+ help: 'Configuration values',
185
+ labelNames: ['version', 'config']
186
+ }),
187
+
188
+ redisVersion: new promClient.Gauge({
189
+ name: 'redis_version',
190
+ help: 'Redis version',
191
+ labelNames: ['version']
192
+ }),
193
+
194
+ redisUptimeInSeconds: new promClient.Gauge({
195
+ name: 'redis_uptime_in_seconds',
196
+ help: 'Redis uptime in seconds'
197
+ }),
198
+
199
+ redisPing: new promClient.Gauge({
200
+ name: 'redis_latency',
201
+ help: 'Redis latency in nanoseconds'
202
+ }),
203
+
204
+ redisRejectedConnectionsTotal: new promClient.Gauge({
205
+ name: 'redis_rejected_connections_total',
206
+ help: 'Number of connections rejected by Redis'
207
+ }),
208
+
209
+ redisConfigMaxclients: new promClient.Gauge({
210
+ name: 'redis_config_maxclients',
211
+ help: 'Maximum client number for Redis'
212
+ }),
213
+
214
+ redisConnectedClients: new promClient.Gauge({
215
+ name: 'redis_connected_clients',
216
+ help: 'Number of client connections for Redis'
217
+ }),
218
+
219
+ redisSlowlogLength: new promClient.Gauge({
220
+ name: 'redis_slowlog_length',
221
+ help: 'Number of of entries in the Redis slow log'
222
+ }),
223
+
224
+ redisCommandsDurationSecondsTotal: new promClient.Gauge({
225
+ name: 'redis_commands_duration_seconds_total',
226
+ help: 'How many seconds spend on processing Redis commands'
227
+ }),
228
+
229
+ redisCommandsProcessedTotal: new promClient.Gauge({
230
+ name: 'redis_commands_processed_total',
231
+ help: 'How many commands processed by Redis'
232
+ }),
233
+
234
+ redisKeyspaceHitsTotal: new promClient.Gauge({
235
+ name: 'redis_keyspace_hits_total',
236
+ help: 'Number of successful lookup of keys in Redis'
237
+ }),
238
+
239
+ redisKeyspaceMissesTotal: new promClient.Gauge({
240
+ name: 'redis_keyspace_misses_total',
241
+ help: 'Number of failed lookup of keys in Redis'
242
+ }),
243
+
244
+ redisEvictedKeysTotal: new promClient.Gauge({
245
+ name: 'redis_evicted_keys_total',
246
+ help: 'Number of evicted keys due to maxmemory limit in Redis'
247
+ }),
248
+
249
+ redisMemoryUsedBytes: new promClient.Gauge({
250
+ name: 'redis_memory_used_bytes',
251
+ help: 'Total number of bytes allocated by Redis using its allocator'
252
+ }),
253
+
254
+ redisMemoryMaxBytes: new promClient.Gauge({
255
+ name: 'redis_memory_max_bytes',
256
+ help: 'The value of the Redis maxmemory configuration directive'
257
+ }),
258
+
259
+ redisMemFragmentationRatio: new promClient.Gauge({
260
+ name: 'redis_mem_fragmentation_ratio',
261
+ help: 'Ratio between used_memory_rss and used_memory in Redis'
262
+ }),
263
+
264
+ redisKeyCount: new promClient.Gauge({
265
+ name: 'redis_key_count',
266
+ help: 'Redis key counts',
267
+ labelNames: ['db']
268
+ }),
269
+
270
+ redisLastSaveTime: new promClient.Gauge({
271
+ name: 'redis_last_save_time',
272
+ help: 'Unix timestamp of the last RDB save time'
273
+ }),
274
+
275
+ redisOpsPerSec: new promClient.Gauge({
276
+ name: 'redis_instantaneous_ops_per_sec',
277
+ help: 'Throughput operations per second'
278
+ }),
279
+
280
+ redisCommandRuns: new promClient.Gauge({
281
+ name: 'redis_command_runs',
282
+ help: 'Redis command counts',
283
+ labelNames: ['command']
284
+ }),
285
+
286
+ redisCommandRunsFailed: new promClient.Gauge({
287
+ name: 'redis_command_runs_fail',
288
+ help: 'Redis command counts',
289
+ labelNames: ['command', 'status']
290
+ })
291
+ };
292
+ }
293
+
294
+ /**
295
+ * Starts the default Node.js process metrics and creates the EmailEngine ones.
296
+ *
297
+ * @returns {Object} The metrics, as createMetrics() returns them
298
+ */
299
+ function setupMetrics() {
300
+ promClient.collectDefaultMetrics({});
301
+ return createMetrics();
302
+ }
303
+
304
+ /**
305
+ * The current IMAP connection counts by status, read through the gauge's public get().
306
+ *
307
+ * @param {Object} gauge metrics.imapConnections
308
+ * @returns {Promise<Object>} { [status]: count }
309
+ */
310
+ async function connectionCounts(gauge) {
311
+ let connections = {};
312
+ for (let { labels, value } of (await gauge.get()).values) {
313
+ if (labels && labels.status !== undefined) {
314
+ connections[labels.status] = value;
315
+ }
316
+ }
317
+ return connections;
318
+ }
319
+
320
+ module.exports = { promClient, setupMetrics, connectionCounts };
@@ -1,20 +1,11 @@
1
1
  'use strict';
2
2
 
3
3
  const { isEmail } = require('../utils/is-email');
4
- const packageData = require('../../package.json');
5
- const {
6
- formatPartialSecretKey,
7
- formatSecretHint,
8
- formatOAuthRequestBody,
9
- formatOAuthResponse,
10
- httpAgent,
11
- formatTokenError,
12
- parseRetryAfter
13
- } = require('../tools');
4
+ const { formatPartialSecretKey, formatSecretHint, formatOAuthRequestBody, formatOAuthResponse, httpAgent, formatTokenError } = require('../tools');
14
5
  const crypto = require('crypto');
15
6
 
16
7
  const { fetch: fetchCmd } = require('undici');
17
- const { promoteCauseCode } = require('../network-errors');
8
+ const { USER_AGENT, encodeRequest, timedFetch, buildRequestFailure, handleFailedResponse } = require('./http-request');
18
9
 
19
10
  const { ExternalAccountSigner } = require('./external-account-signer');
20
11
  const { fetchTokenRequest } = require('./token-fetch');
@@ -408,7 +399,7 @@ class GmailOauth {
408
399
  method,
409
400
  headers: {
410
401
  'Content-Type': 'application/x-www-form-urlencoded',
411
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
402
+ 'User-Agent': USER_AGENT
412
403
  },
413
404
  body: tokenRequest.body
414
405
  };
@@ -533,7 +524,7 @@ class GmailOauth {
533
524
  method,
534
525
  headers: {
535
526
  'Content-Type': 'application/x-www-form-urlencoded',
536
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
527
+ 'User-Agent': USER_AGENT
537
528
  },
538
529
  body: bodyString
539
530
  };
@@ -684,6 +675,28 @@ class GmailOauth {
684
675
  return response;
685
676
  }
686
677
 
678
+ /**
679
+ * The fields that describe an API request in errors and log entries
680
+ * @param {string} url - Request URL
681
+ * @param {string} method - Request method
682
+ * @param {Response} res - The answer
683
+ * @param {string} contentType - Content type of the answer, without parameters
684
+ * @returns {Object}
685
+ */
686
+ logContext(url, method, res, contentType) {
687
+ return {
688
+ url,
689
+ method,
690
+ provider: this.provider,
691
+ status: res.status,
692
+ contentType,
693
+ clientId: this.clientId,
694
+ serviceClient: this.serviceClient,
695
+ googleProjectId: this.googleProjectId,
696
+ serviceClientEmail: this.serviceClientEmail
697
+ };
698
+ }
699
+
687
700
  async request(accessToken, url, method, payload, options) {
688
701
  options = options || {};
689
702
 
@@ -692,7 +705,7 @@ class GmailOauth {
692
705
  method,
693
706
  headers: {
694
707
  Authorization: `Bearer ${accessToken}`,
695
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
708
+ 'User-Agent': USER_AGENT
696
709
  },
697
710
  // Sent exactly once. Which failures are worth repeating depends on the method and on
698
711
  // what Gmail answered, and that is decided by the request layer above this one
@@ -702,107 +715,25 @@ class GmailOauth {
702
715
  signal: options.signal || undefined
703
716
  };
704
717
 
705
- if (payload && method !== 'get') {
706
- if (!Buffer.isBuffer(payload)) {
707
- reqData.headers.Accept = 'application/json';
708
- reqData.headers['Content-Type'] = options?.contentType || 'application/json';
709
- reqData.body = JSON.stringify(payload);
710
- } else {
711
- reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
712
- reqData.body = payload;
713
- }
714
- } else if (payload && method === 'get') {
715
- let parsedUrl = new URL(url);
716
- for (let key of Object.keys(payload)) {
717
- if (typeof payload[key] === 'undefined' || payload[key] === null) {
718
- continue;
719
- }
720
- parsedUrl.searchParams.append(key, payload[key].toString());
721
- }
722
- url = parsedUrl.href;
723
- }
718
+ url = encodeRequest(reqData, url, method, payload, options);
724
719
 
725
- let startTime = Date.now();
726
-
727
- let res = await fetchCmd(url, reqData).catch(err => {
728
- // undici puts the network code on err.cause; callers read err.code
729
- throw promoteCauseCode(err);
730
- });
731
-
732
- let reqTime = Date.now() - startTime;
720
+ let { res, reqTime } = await timedFetch(url, reqData);
733
721
 
734
722
  let contentType = (res.headers?.get('content-type') || '').toString().split(';').shift().trim().toLowerCase();
735
723
 
736
724
  if (!res.ok) {
737
- let err = new Error('OAuth2 request failed');
738
- err.statusCode = res.status;
739
- err.oauthRequest = {
740
- url,
741
- method,
742
- provider: this.provider,
743
- status: res.status,
744
- contentType,
745
- clientId: this.clientId,
746
- serviceClient: this.serviceClient,
747
- googleProjectId: this.googleProjectId,
748
- serviceClientEmail: this.serviceClientEmail,
749
- scopes: this.scopes,
750
- reqTime
751
- };
752
-
753
- // Capture Retry-After (sent with 429, and with rate-limit 403s and 503s) so the
754
- // retry layer can honour it
755
- let retryAfter = parseRetryAfter(res.headers);
756
- if (retryAfter !== null) {
757
- err.retryAfter = retryAfter;
758
- err.oauthRequest.retryAfter = retryAfter;
759
- }
760
-
761
- try {
762
- err.oauthRequest.response = await res.json();
763
-
764
- if (this.clientSecret && EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.oauthRequest.response.error_description)) {
765
- // key might have been invalidated or renewed
766
- err.oauthRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
767
- }
768
-
769
- let flag = checkForFlags(err.oauthRequest.response);
770
- if (flag) {
771
- await this.setFlag(flag);
772
- err.oauthRequest.flag = flag;
773
- if (flag.code && !err.code) {
774
- err.code = flag.code;
775
- }
776
- }
777
- } catch (E) {
778
- // ignore
779
- } finally {
780
- if (this.logger) {
781
- this.logger.warn(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
782
- }
783
- }
784
-
725
+ let err = buildRequestFailure(res, Object.assign(this.logContext(url, method, res, contentType), { scopes: this.scopes, reqTime }));
726
+ await handleFailedResponse(this, res, err, {
727
+ checkForFlags,
728
+ exposeSecret: response => EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(response.error_description),
729
+ recordFlag: true,
730
+ logger: this.logger
731
+ });
785
732
  throw err;
786
733
  }
787
734
 
788
735
  if (this.logger) {
789
- this.logger.debug(
790
- Object.assign(
791
- { msg: 'External API request completed' },
792
- {
793
- url,
794
- method,
795
- provider: this.provider,
796
- status: res.status,
797
- contentType,
798
- clientId: this.clientId,
799
- serviceClient: this.serviceClient,
800
- googleProjectId: this.googleProjectId,
801
- serviceClientEmail: this.serviceClientEmail,
802
- reqTime
803
- }
804
- )
805
- );
736
+ this.logger.debug(Object.assign({ msg: 'External API request completed' }, this.logContext(url, method, res, contentType), { reqTime }));
806
737
  }
807
738
 
808
739
  // clear potential auth flag
@@ -814,19 +745,7 @@ class GmailOauth {
814
745
 
815
746
  if (!['application/json', 'text/json'].includes(contentType)) {
816
747
  let error = new Error('Expected JSON response for OAuth2 request');
817
- error.oauthRequest = {
818
- url,
819
- method,
820
- provider: this.provider,
821
- status: res.status,
822
- contentType,
823
- clientId: this.clientId,
824
- serviceClient: this.serviceClient,
825
- googleProjectId: this.googleProjectId,
826
- serviceClientEmail: this.serviceClientEmail,
827
- scopes: this.scopes,
828
- reqTime
829
- };
748
+ error.oauthRequest = Object.assign(this.logContext(url, method, res, contentType), { scopes: this.scopes, reqTime });
830
749
 
831
750
  let responseText;
832
751
  try {
@@ -907,7 +826,7 @@ class GmailOauth {
907
826
  method: 'post',
908
827
  headers: {
909
828
  'Content-Type': 'application/x-www-form-urlencoded',
910
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
829
+ 'User-Agent': USER_AGENT
911
830
  },
912
831
  body: new URLSearchParams({ token }).toString()
913
832
  };