emailengine-app 2.88.0 → 2.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.ncurc.js +36 -45
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +77 -11
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/node-version.js +99 -12
  38. package/lib/oauth/gmail.js +39 -120
  39. package/lib/oauth/http-request.js +195 -0
  40. package/lib/oauth/mail-ru.js +24 -58
  41. package/lib/oauth/outlook.js +37 -137
  42. package/lib/oauth/pubsub/google.js +176 -117
  43. package/lib/oauth2-apps.js +440 -463
  44. package/lib/openapi/build-document.js +10 -10
  45. package/lib/read-env-value.js +1 -1
  46. package/lib/route-descriptors.js +78 -0
  47. package/lib/schemas.js +10 -1
  48. package/lib/sentry-integrations.js +299 -0
  49. package/lib/sentry.js +75 -27
  50. package/lib/settings.js +4 -1
  51. package/lib/sso-routes.js +249 -0
  52. package/lib/sso.js +29 -6
  53. package/lib/tools.js +5 -4
  54. package/lib/ui-routes/account-edit-form.js +198 -0
  55. package/lib/ui-routes/account-page.js +241 -0
  56. package/lib/ui-routes/account-routes.js +12 -318
  57. package/lib/ui-routes/auth-routes.js +10 -10
  58. package/lib/ui-routes/dashboard-routes.js +4 -0
  59. package/lib/ui-view-context.js +328 -0
  60. package/lib/utils/public-suffix.js +22 -101
  61. package/lib/web-safe-html.js +70 -13
  62. package/lib/worker-metrics.js +82 -0
  63. package/list-generate.js +57 -23
  64. package/package.json +34 -33
  65. package/sbom.json +380 -1612
  66. package/scripts/refresh-test-tokens.js +1 -1
  67. package/server.js +351 -707
  68. package/static/css/flyonui.css +1 -1
  69. package/static/css/src/app.tailwind.css +18 -0
  70. package/static/js/ee-client.js +2619 -645
  71. package/static/js/ui.js +12 -2
  72. package/static/licenses.html +1055 -969
  73. package/translations/messages.pot +71 -60
  74. package/views/accounts/browse.hbs +19 -1
  75. package/views/dashboard.hbs +9 -0
  76. package/views/upgrade.hbs +25 -0
  77. package/workers/api.js +20 -451
  78. package/data/public_suffix_list.dat +0 -16597
  79. package/lib/net-tos-guard.js +0 -42
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,24 +1,111 @@
1
1
  'use strict';
2
2
 
3
- // The oldest Node.js release the dependency tree supports, matching `engines.node` in package.json
4
- // (test/node-version-test.js keeps the two in step). Requires nothing but the dependency-free
5
- // lib/utils/version.js, because server.js checks it before it requires anything else.
6
-
7
- const MIN_SUPPORTED_NODE = '20.19.0';
3
+ // Which Node.js releases EmailEngine runs on. Requires nothing but the dependency-free
4
+ // lib/utils/version.js, because server.js asks before it requires anything else.
5
+ //
6
+ // Two thresholds, because the dependency tree has two:
7
+ //
8
+ // - MIN_NODE is the oldest release EmailEngine can start on at all. undici 8, which the main
9
+ // thread and every worker load at startup, throws when it is loaded on anything older than
10
+ // 22.19 (it calls a zlib API Node 20 does not have), so below it server.js exits with a message
11
+ // instead of letting the first worker die on a TypeError.
12
+ // - SUPPORTED_RANGES is what package.json `engines.node` declares, the range the bundled jsdom
13
+ // (inside @postalsys/email-text-tools) declares. A release between the two starts and runs, and
14
+ // the dashboard says it is outside the supported range. test/node-version-test.js keeps the
15
+ // ranges equal to the engines field.
8
16
 
9
17
  const { compareVersions } = require('./utils/version');
10
18
 
19
+ const MIN_NODE = '22.19.0';
20
+
21
+ // [major, minimum within that major], the last entry also admits every later major
22
+ const SUPPORTED_RANGES = [
23
+ [22, '22.22.2'],
24
+ [24, '24.15.0'],
25
+ [26, '26.0.0']
26
+ ];
27
+
28
+ // The engines.node form of SUPPORTED_RANGES
29
+ const SUPPORTED_RANGE_TEXT = SUPPORTED_RANGES.map(([, min], i) => (i === SUPPORTED_RANGES.length - 1 ? `>=${min}` : `^${min}`)).join(' || ');
30
+
31
+ // What an operator reads when the version is not supported
32
+ // ("22.x from 22.22.2, 24.x from 24.15.0, or 26 and newer")
33
+ const SUPPORTED_RANGE_LABEL = SUPPORTED_RANGES.map(([major, min], i) =>
34
+ i === SUPPORTED_RANGES.length - 1 ? `or ${major} and newer` : `${major}.x from ${min}`
35
+ ).join(', ');
36
+
37
+ function normalize(version) {
38
+ return String(version || '').replace(/^v/, '');
39
+ }
40
+
41
+ function inSupportedRange(version) {
42
+ const major = Number(version.split('.')[0]);
43
+ const last = SUPPORTED_RANGES[SUPPORTED_RANGES.length - 1];
44
+ if (major >= last[0]) {
45
+ return compareVersions(version, last[1]) >= 0;
46
+ }
47
+ const range = SUPPORTED_RANGES.find(([rangeMajor]) => rangeMajor === major);
48
+ return !!range && compareVersions(version, range[1]) >= 0;
49
+ }
50
+
11
51
  /**
12
- * Whether a Node.js version is older than MIN_SUPPORTED_NODE
13
- * @param {string} version - A version such as process.versions.node ("20.18.1")
14
- * @returns {boolean} True when the version is older, false for one that can not be read
52
+ * How well EmailEngine supports a Node.js version
53
+ * @param {string} version - A version such as process.versions.node ("22.19.0")
54
+ * @returns {'unsupported'|'outside-range'|'ok'} 'unsupported' below MIN_NODE, 'outside-range' for
55
+ * a release that runs but is not in SUPPORTED_RANGES, 'ok' otherwise. A version that can not be
56
+ * read is 'ok': nothing is gained by refusing to start over a string we do not understand
15
57
  */
16
- function isBelowSupportedNode(version) {
58
+ function nodeSupport(version) {
59
+ const normalized = normalize(version);
17
60
  try {
18
- return compareVersions(String(version || '').replace(/^v/, ''), MIN_SUPPORTED_NODE) < 0;
61
+ if (compareVersions(normalized, MIN_NODE) < 0) {
62
+ return 'unsupported';
63
+ }
64
+ return inSupportedRange(normalized) ? 'ok' : 'outside-range';
19
65
  } catch (err) {
20
- return false;
66
+ return 'ok';
21
67
  }
22
68
  }
23
69
 
24
- module.exports = { MIN_SUPPORTED_NODE, isBelowSupportedNode };
70
+ // What an operator on a Debian or Ubuntu server with Node.js from NodeSource (the DigitalOcean one-click
71
+ // image included) runs to move to a supported release. The startup error and /admin/upgrade show it
72
+ const NODESOURCE_UPGRADE_COMMANDS = [
73
+ 'curl -fsSL https://deb.nodesource.com/setup_24.x | sudo bash -',
74
+ 'sudo apt-get install -y nodejs',
75
+ 'sudo systemctl restart emailengine'
76
+ ];
77
+
78
+ /**
79
+ * The commands an operator runs to move to a supported Node.js release, for the startup error
80
+ * @returns {string}
81
+ */
82
+ function nodeUpgradeHint() {
83
+ return [
84
+ 'To upgrade Node.js on a Debian or Ubuntu server that installed it from NodeSource (this includes the',
85
+ 'DigitalOcean one-click image), run:',
86
+ '',
87
+ ...NODESOURCE_UPGRADE_COMMANDS.map(command => ` ${command}`),
88
+ '',
89
+ 'The EmailEngine binaries and the Docker image carry their own Node.js and are not affected.'
90
+ ].join('\n');
91
+ }
92
+
93
+ /**
94
+ * What the admin UI shows about the Node.js release it runs on
95
+ * @param {string} version - A version such as process.versions.node
96
+ * @param {boolean} [packaged] - A pkg binary, which carries its own Node.js: there is nothing for
97
+ * its operator to upgrade but EmailEngine, so it is never flagged
98
+ * @returns {{version: string, supported: string, upgradeCommands: string[], packaged: boolean, outsideRange: boolean}}
99
+ */
100
+ function nodeRuntimeView(version, packaged) {
101
+ return {
102
+ version: normalize(version),
103
+ supported: SUPPORTED_RANGE_LABEL,
104
+ upgradeCommands: NODESOURCE_UPGRADE_COMMANDS,
105
+ packaged: !!packaged,
106
+ // 'unsupported' never renders: the process would not have started
107
+ outsideRange: !packaged && nodeSupport(version) !== 'ok'
108
+ };
109
+ }
110
+
111
+ module.exports = { nodeRuntimeView, MIN_NODE, SUPPORTED_RANGE_TEXT, SUPPORTED_RANGE_LABEL, nodeSupport, nodeUpgradeHint };
@@ -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
  };