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.
- package/.ncurc.js +36 -45
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +58 -0
- package/Dockerfile +5 -1
- package/bin/healthcheck.js +1 -1
- package/copy-static-files.sh +0 -8
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +1 -4
- package/lib/account/field-codec.js +396 -0
- package/lib/account.js +158 -453
- package/lib/api-routes/account-routes.js +42 -6
- package/lib/api-routes/route-metadata.js +5 -2
- package/lib/api-routes/submit-routes.js +15 -2
- package/lib/api-token-auth.js +342 -274
- package/lib/arf-detect.js +174 -149
- package/lib/attachment-size.js +29 -0
- package/lib/autodetect-imap-settings.js +83 -234
- package/lib/consts.js +1 -5
- package/lib/db.js +1 -4
- package/lib/email-client/base-client.js +907 -780
- package/lib/email-client/gmail-client.js +557 -450
- package/lib/email-client/imap/cid-parts.js +61 -0
- package/lib/email-client/imap/mailbox.js +376 -422
- package/lib/email-client/imap/sync-operations.js +239 -178
- package/lib/email-client/new-message-steps.js +168 -2
- package/lib/email-client/outlook/graph-message.js +266 -0
- package/lib/email-client/outlook/subscription-expiry.js +30 -0
- package/lib/email-client/outlook-client.js +652 -808
- package/lib/get-raw-email.js +338 -232
- package/lib/get-secret.js +1 -4
- package/lib/license-subscription.js +77 -11
- package/lib/load-env.js +48 -0
- package/lib/logger.js +1 -4
- package/lib/mcp/tools.js +244 -207
- package/lib/metric-values.js +76 -0
- package/lib/metrics.js +320 -0
- package/lib/node-version.js +99 -12
- package/lib/oauth/gmail.js +39 -120
- package/lib/oauth/http-request.js +195 -0
- package/lib/oauth/mail-ru.js +24 -58
- package/lib/oauth/outlook.js +37 -137
- package/lib/oauth/pubsub/google.js +176 -117
- package/lib/oauth2-apps.js +440 -463
- package/lib/openapi/build-document.js +10 -10
- package/lib/read-env-value.js +1 -1
- package/lib/route-descriptors.js +78 -0
- package/lib/schemas.js +10 -1
- package/lib/sentry-integrations.js +299 -0
- package/lib/sentry.js +75 -27
- package/lib/settings.js +4 -1
- package/lib/sso-routes.js +249 -0
- package/lib/sso.js +29 -6
- package/lib/tools.js +5 -4
- package/lib/ui-routes/account-edit-form.js +198 -0
- package/lib/ui-routes/account-page.js +241 -0
- package/lib/ui-routes/account-routes.js +12 -318
- package/lib/ui-routes/auth-routes.js +10 -10
- package/lib/ui-routes/dashboard-routes.js +4 -0
- package/lib/ui-view-context.js +328 -0
- package/lib/utils/public-suffix.js +22 -101
- package/lib/web-safe-html.js +70 -13
- package/lib/worker-metrics.js +82 -0
- package/list-generate.js +57 -23
- package/package.json +34 -33
- package/sbom.json +380 -1612
- package/scripts/refresh-test-tokens.js +1 -1
- package/server.js +351 -707
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +18 -0
- package/static/js/ee-client.js +2619 -645
- package/static/js/ui.js +12 -2
- package/static/licenses.html +1055 -969
- package/translations/messages.pot +71 -60
- package/views/accounts/browse.hbs +19 -1
- package/views/dashboard.hbs +9 -0
- package/views/upgrade.hbs +25 -0
- package/workers/api.js +20 -451
- package/data/public_suffix_list.dat +0 -16597
- package/lib/net-tos-guard.js +0 -42
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The parts of a provider API request that the OAuth2 clients (Gmail, Outlook, Mail.ru) share. Each
|
|
4
|
+
// client keeps what differs: how it spells the method, where the access token goes, which fields
|
|
5
|
+
// describe a request in its errors and logs, and how it reads a successful answer.
|
|
6
|
+
|
|
7
|
+
const packageData = require('../../package.json');
|
|
8
|
+
const { fetch: fetchCmd } = require('undici');
|
|
9
|
+
const { promoteCauseCode } = require('../network-errors');
|
|
10
|
+
const { formatPartialSecretKey, parseRetryAfter } = require('../tools');
|
|
11
|
+
|
|
12
|
+
const USER_AGENT = `${packageData.name}/${packageData.version} (+${packageData.homepage})`;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Sets the request body: a Buffer is sent as is, anything else as JSON
|
|
16
|
+
* @param {Object} reqData - fetch() options, updated in place
|
|
17
|
+
* @param {Object|Buffer} payload - Request body
|
|
18
|
+
* @param {string} [contentType] - Content type that overrides the default
|
|
19
|
+
*/
|
|
20
|
+
function encodeBody(reqData, payload, contentType) {
|
|
21
|
+
if (!Buffer.isBuffer(payload)) {
|
|
22
|
+
reqData.headers.Accept = 'application/json';
|
|
23
|
+
reqData.headers['Content-Type'] = contentType || 'application/json';
|
|
24
|
+
reqData.body = JSON.stringify(payload);
|
|
25
|
+
} else {
|
|
26
|
+
reqData.headers['Content-Type'] = contentType || 'application/x-www-form-urlencoded';
|
|
27
|
+
reqData.body = payload;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Places the payload of a request: in the query string of a GET (values that are null or
|
|
33
|
+
* undefined left out), in the body otherwise
|
|
34
|
+
* @param {Object} reqData - fetch() options, updated in place
|
|
35
|
+
* @param {string} url - Request URL
|
|
36
|
+
* @param {string} method - Method as the client spells it, in any case
|
|
37
|
+
* @param {Object|Buffer} [payload] - Request payload
|
|
38
|
+
* @param {Object} [options] - Request options, `contentType` overrides the body content type
|
|
39
|
+
* @returns {string} The URL to request
|
|
40
|
+
*/
|
|
41
|
+
function encodeRequest(reqData, url, method, payload, options) {
|
|
42
|
+
if (!payload) {
|
|
43
|
+
return url;
|
|
44
|
+
}
|
|
45
|
+
if (String(method).toLowerCase() !== 'get') {
|
|
46
|
+
encodeBody(reqData, payload, options?.contentType);
|
|
47
|
+
} else {
|
|
48
|
+
let parsedUrl = new URL(url);
|
|
49
|
+
for (let key of Object.keys(payload)) {
|
|
50
|
+
if (typeof payload[key] === 'undefined' || payload[key] === null) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
parsedUrl.searchParams.append(key, payload[key].toString());
|
|
54
|
+
}
|
|
55
|
+
url = parsedUrl.href;
|
|
56
|
+
}
|
|
57
|
+
return url;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Sends the request once and measures how long the answer took
|
|
62
|
+
* @param {string} url - Request URL
|
|
63
|
+
* @param {Object} reqData - fetch() options
|
|
64
|
+
* @returns {Promise<{res: Response, reqTime: number}>}
|
|
65
|
+
*/
|
|
66
|
+
async function timedFetch(url, reqData) {
|
|
67
|
+
let startTime = Date.now();
|
|
68
|
+
let res = await fetchCmd(url, reqData).catch(err => {
|
|
69
|
+
// undici puts the network code on err.cause; callers read err.code
|
|
70
|
+
throw promoteCauseCode(err);
|
|
71
|
+
});
|
|
72
|
+
return { res, reqTime: Date.now() - startTime };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The error for an answer that is not 2xx. Carries the HTTP status, and the Retry-After the
|
|
77
|
+
* provider sent (with 429, and with rate-limit 403s and 503s) so the retry layer can honour it
|
|
78
|
+
* @param {Response} res - The answer
|
|
79
|
+
* @param {Object} oauthRequest - Description of the request, becomes err.oauthRequest
|
|
80
|
+
* @returns {Error}
|
|
81
|
+
*/
|
|
82
|
+
function buildRequestFailure(res, oauthRequest) {
|
|
83
|
+
let err = new Error('OAuth2 request failed');
|
|
84
|
+
err.statusCode = res.status;
|
|
85
|
+
err.oauthRequest = oauthRequest;
|
|
86
|
+
|
|
87
|
+
let retryAfter = parseRetryAfter(res.headers);
|
|
88
|
+
if (retryAfter !== null) {
|
|
89
|
+
err.retryAfter = retryAfter;
|
|
90
|
+
err.oauthRequest.retryAfter = retryAfter;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return err;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Reads the provider's error body onto a failed request and raises the flag it maps to. A body
|
|
98
|
+
* that is not JSON, or any failure on the way, leaves the error as it is
|
|
99
|
+
* @param {Object} client - The OAuth2 client (its setFlag() and clientSecret are used)
|
|
100
|
+
* @param {Response} res - The failed answer
|
|
101
|
+
* @param {Error} err - The error to complete, with err.oauthRequest set
|
|
102
|
+
* @param {Object} opts
|
|
103
|
+
* @param {Function} opts.checkForFlags - Maps an error body to a flag, or false
|
|
104
|
+
* @param {Function} [opts.exposeSecret] - Whether the error body blames the client secret, so err.oauthRequest shows part of it
|
|
105
|
+
* @param {boolean} [opts.recordFlag] - Also keep the flag on err.oauthRequest.flag
|
|
106
|
+
* @param {Object} [opts.logger] - Logs err.oauthRequest at warn level once done
|
|
107
|
+
* @returns {Promise<Error>} The same error
|
|
108
|
+
*/
|
|
109
|
+
async function handleFailedResponse(client, res, err, opts) {
|
|
110
|
+
try {
|
|
111
|
+
err.oauthRequest.response = await res.json();
|
|
112
|
+
|
|
113
|
+
// Without a configured secret there is nothing to show, and the flag below must still be raised
|
|
114
|
+
if (client.clientSecret && opts.exposeSecret && opts.exposeSecret(err.oauthRequest.response)) {
|
|
115
|
+
// key might have been invalidated or renewed
|
|
116
|
+
err.oauthRequest.clientSecret = formatPartialSecretKey(client.clientSecret);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let flag = opts.checkForFlags(err.oauthRequest.response);
|
|
120
|
+
if (flag) {
|
|
121
|
+
await client.setFlag(flag);
|
|
122
|
+
if (opts.recordFlag) {
|
|
123
|
+
err.oauthRequest.flag = flag;
|
|
124
|
+
}
|
|
125
|
+
if (flag.code && !err.code) {
|
|
126
|
+
err.code = flag.code;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch (E) {
|
|
130
|
+
// ignore
|
|
131
|
+
} finally {
|
|
132
|
+
if (opts.logger) {
|
|
133
|
+
opts.logger.warn(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return err;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Parses a JSON answer read as text. An empty body (Graph sometimes answers 200 with nothing) is
|
|
142
|
+
* EmptyResponse and one that does not parse is InvalidJSON, each describing the request through
|
|
143
|
+
* `describe(extra)` and logged at error level when a logger is given
|
|
144
|
+
* @param {string} responseText - The body of the answer
|
|
145
|
+
* @param {Function} describe - Returns the err.oauthRequest fields, with the extra fields given appended
|
|
146
|
+
* @param {Object} [opts]
|
|
147
|
+
* @param {number} [opts.statusCode] - Set on the error when given
|
|
148
|
+
* @param {Object} [opts.logger] - Logs the failure
|
|
149
|
+
* @returns {*} The parsed body
|
|
150
|
+
*/
|
|
151
|
+
function parseJsonResponse(responseText, describe, opts) {
|
|
152
|
+
opts = opts || {};
|
|
153
|
+
|
|
154
|
+
if (!responseText || !responseText.trim()) {
|
|
155
|
+
let err = new Error('Empty response from API');
|
|
156
|
+
err.code = 'EmptyResponse';
|
|
157
|
+
if (typeof opts.statusCode === 'number') {
|
|
158
|
+
err.statusCode = opts.statusCode;
|
|
159
|
+
}
|
|
160
|
+
err.oauthRequest = describe();
|
|
161
|
+
if (opts.logger) {
|
|
162
|
+
opts.logger.error(Object.assign({ msg: 'API returned empty response' }, err.oauthRequest));
|
|
163
|
+
}
|
|
164
|
+
throw err;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
try {
|
|
168
|
+
return JSON.parse(responseText);
|
|
169
|
+
} catch (parseErr) {
|
|
170
|
+
let err = new Error('Invalid JSON response from API');
|
|
171
|
+
err.code = 'InvalidJSON';
|
|
172
|
+
if (typeof opts.statusCode === 'number') {
|
|
173
|
+
err.statusCode = opts.statusCode;
|
|
174
|
+
}
|
|
175
|
+
err.oauthRequest = describe({
|
|
176
|
+
responseLength: responseText.length,
|
|
177
|
+
responseStart: responseText.slice(0, 200),
|
|
178
|
+
responseEnd: responseText.length > 200 ? responseText.slice(-200) : undefined
|
|
179
|
+
});
|
|
180
|
+
if (opts.logger) {
|
|
181
|
+
opts.logger.error(Object.assign({ msg: 'API returned invalid JSON' }, err.oauthRequest, { err: parseErr }));
|
|
182
|
+
}
|
|
183
|
+
throw err;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
module.exports = {
|
|
188
|
+
USER_AGENT,
|
|
189
|
+
encodeBody,
|
|
190
|
+
encodeRequest,
|
|
191
|
+
timedFetch,
|
|
192
|
+
buildRequestFailure,
|
|
193
|
+
handleFailedResponse,
|
|
194
|
+
parseJsonResponse
|
|
195
|
+
};
|
package/lib/oauth/mail-ru.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
const { fetch: fetchCmd } = require('undici');
|
|
5
|
-
const { promoteCauseCode } = require('../network-errors');
|
|
3
|
+
const { USER_AGENT, encodeBody, timedFetch, handleFailedResponse, parseJsonResponse } = require('./http-request');
|
|
6
4
|
const { fetchTokenRequest } = require('./token-fetch');
|
|
7
5
|
const { formatPartialSecretKey, formatOAuthRequestBody, formatOAuthResponse, httpAgent, formatTokenError } = require('../tools');
|
|
8
6
|
|
|
@@ -88,7 +86,7 @@ class MailRuOauth {
|
|
|
88
86
|
method,
|
|
89
87
|
headers: {
|
|
90
88
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
91
|
-
'User-Agent':
|
|
89
|
+
'User-Agent': USER_AGENT,
|
|
92
90
|
Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
|
|
93
91
|
},
|
|
94
92
|
body: tokenRequest.body
|
|
@@ -177,7 +175,7 @@ class MailRuOauth {
|
|
|
177
175
|
method,
|
|
178
176
|
headers: {
|
|
179
177
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
180
|
-
'User-Agent':
|
|
178
|
+
'User-Agent': USER_AGENT
|
|
181
179
|
},
|
|
182
180
|
body: bodyString
|
|
183
181
|
},
|
|
@@ -243,54 +241,45 @@ class MailRuOauth {
|
|
|
243
241
|
return responseJson;
|
|
244
242
|
}
|
|
245
243
|
|
|
244
|
+
/**
|
|
245
|
+
* The fields that describe an API request in errors
|
|
246
|
+
* @param {string} url - Request URL, without the access token
|
|
247
|
+
* @param {string} method - Request method
|
|
248
|
+
* @param {Response} res - The answer
|
|
249
|
+
* @returns {Object}
|
|
250
|
+
*/
|
|
251
|
+
logContext(url, method, res) {
|
|
252
|
+
return { url, method, provider: this.provider, status: res.status, clientId: this.clientId };
|
|
253
|
+
}
|
|
254
|
+
|
|
246
255
|
async request(accessToken, url, method, payload, options) {
|
|
247
256
|
method = method || 'get';
|
|
248
257
|
let reqData = {
|
|
249
258
|
method,
|
|
250
259
|
headers: {
|
|
251
|
-
'User-Agent':
|
|
260
|
+
'User-Agent': USER_AGENT
|
|
252
261
|
},
|
|
253
262
|
dispatcher: httpAgent.forRoute(this.route).retry
|
|
254
263
|
};
|
|
255
264
|
|
|
256
265
|
if (payload) {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
//
|
|
261
|
-
reqData.
|
|
262
|
-
} else {
|
|
263
|
-
reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
|
|
264
|
-
reqData.body = payload;
|
|
265
|
-
if (payload.length > 0) {
|
|
266
|
-
// Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
|
|
267
|
-
reqData.dispatcher = httpAgent.forRoute(this.route).fetch;
|
|
268
|
-
}
|
|
266
|
+
// A JSON body is a string rather than a Buffer, so a retry does not meet a detached ArrayBuffer
|
|
267
|
+
encodeBody(reqData, payload, options?.contentType);
|
|
268
|
+
if (Buffer.isBuffer(payload) && payload.length > 0) {
|
|
269
|
+
// Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
|
|
270
|
+
reqData.dispatcher = httpAgent.forRoute(this.route).fetch;
|
|
269
271
|
}
|
|
270
272
|
}
|
|
271
273
|
|
|
272
274
|
const requestUrl = new URL(url);
|
|
273
275
|
requestUrl.searchParams.set('access_token', accessToken);
|
|
274
276
|
|
|
275
|
-
let res = await
|
|
276
|
-
// undici puts the network code on err.cause; callers read err.code
|
|
277
|
-
throw promoteCauseCode(err);
|
|
278
|
-
});
|
|
277
|
+
let { res } = await timedFetch(requestUrl.href, reqData);
|
|
279
278
|
|
|
280
279
|
if (!res.ok) {
|
|
281
280
|
let err = new Error('OAuth2 request failed');
|
|
282
|
-
err.oauthRequest =
|
|
283
|
-
|
|
284
|
-
err.oauthRequest.response = await res.json();
|
|
285
|
-
|
|
286
|
-
let flag = checkForFlags(err.oauthRequest.response);
|
|
287
|
-
if (flag) {
|
|
288
|
-
await this.setFlag(flag);
|
|
289
|
-
err.oauthRequest.flag = flag;
|
|
290
|
-
}
|
|
291
|
-
} catch (e) {
|
|
292
|
-
// ignore
|
|
293
|
-
}
|
|
281
|
+
err.oauthRequest = Object.assign(this.logContext(url, method, res), { scopes: this.scopes });
|
|
282
|
+
await handleFailedResponse(this, res, err, { checkForFlags, recordFlag: true });
|
|
294
283
|
throw err;
|
|
295
284
|
}
|
|
296
285
|
|
|
@@ -299,30 +288,7 @@ class MailRuOauth {
|
|
|
299
288
|
|
|
300
289
|
// Parse JSON response with handling for empty or invalid responses
|
|
301
290
|
let responseText = await res.text();
|
|
302
|
-
|
|
303
|
-
let err = new Error('Empty response from API');
|
|
304
|
-
err.code = 'EmptyResponse';
|
|
305
|
-
err.oauthRequest = { url, method, provider: this.provider, status: res.status, clientId: this.clientId };
|
|
306
|
-
throw err;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
try {
|
|
310
|
-
return JSON.parse(responseText);
|
|
311
|
-
} catch (parseErr) {
|
|
312
|
-
let err = new Error('Invalid JSON response from API');
|
|
313
|
-
err.code = 'InvalidJSON';
|
|
314
|
-
err.oauthRequest = {
|
|
315
|
-
url,
|
|
316
|
-
method,
|
|
317
|
-
provider: this.provider,
|
|
318
|
-
status: res.status,
|
|
319
|
-
clientId: this.clientId,
|
|
320
|
-
responseLength: responseText.length,
|
|
321
|
-
responseStart: responseText.slice(0, 200),
|
|
322
|
-
responseEnd: responseText.length > 200 ? responseText.slice(-200) : undefined
|
|
323
|
-
};
|
|
324
|
-
throw err;
|
|
325
|
-
}
|
|
291
|
+
return parseJsonResponse(responseText, extra => Object.assign(this.logContext(url, method, res), extra));
|
|
326
292
|
}
|
|
327
293
|
}
|
|
328
294
|
|
package/lib/oauth/outlook.js
CHANGED
|
@@ -1,18 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
formatSecretHint,
|
|
7
|
-
formatOAuthRequestBody,
|
|
8
|
-
formatOAuthResponse,
|
|
9
|
-
httpAgent,
|
|
10
|
-
formatTokenError,
|
|
11
|
-
parseRetryAfter
|
|
12
|
-
} = require('../tools');
|
|
13
|
-
|
|
14
|
-
const { fetch: fetchCmd } = require('undici');
|
|
15
|
-
const { promoteCauseCode } = require('../network-errors');
|
|
3
|
+
const { formatPartialSecretKey, formatSecretHint, formatOAuthRequestBody, formatOAuthResponse, httpAgent, formatTokenError } = require('../tools');
|
|
4
|
+
|
|
5
|
+
const { USER_AGENT, encodeRequest, timedFetch, buildRequestFailure, handleFailedResponse, parseJsonResponse } = require('./http-request');
|
|
16
6
|
const { fetchTokenRequest } = require('./token-fetch');
|
|
17
7
|
|
|
18
8
|
// Individual MS Graph API scope names for detection
|
|
@@ -260,7 +250,7 @@ class OutlookOauth {
|
|
|
260
250
|
method,
|
|
261
251
|
headers: {
|
|
262
252
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
263
|
-
'User-Agent':
|
|
253
|
+
'User-Agent': USER_AGENT
|
|
264
254
|
},
|
|
265
255
|
body: tokenRequest.body
|
|
266
256
|
},
|
|
@@ -366,7 +356,7 @@ class OutlookOauth {
|
|
|
366
356
|
method,
|
|
367
357
|
headers: {
|
|
368
358
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
369
|
-
'User-Agent':
|
|
359
|
+
'User-Agent': USER_AGENT
|
|
370
360
|
},
|
|
371
361
|
body: bodyString
|
|
372
362
|
},
|
|
@@ -462,7 +452,7 @@ class OutlookOauth {
|
|
|
462
452
|
method,
|
|
463
453
|
headers: {
|
|
464
454
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
465
|
-
'User-Agent':
|
|
455
|
+
'User-Agent': USER_AGENT
|
|
466
456
|
},
|
|
467
457
|
body: bodyString
|
|
468
458
|
},
|
|
@@ -533,6 +523,23 @@ class OutlookOauth {
|
|
|
533
523
|
return responseJson;
|
|
534
524
|
}
|
|
535
525
|
|
|
526
|
+
/**
|
|
527
|
+
* The fields that describe an API request in errors and log entries
|
|
528
|
+
* @param {string} url - Request URL
|
|
529
|
+
* @param {string} method - Request method
|
|
530
|
+
* @param {Response} res - The answer
|
|
531
|
+
* @returns {Object}
|
|
532
|
+
*/
|
|
533
|
+
logContext(url, method, res) {
|
|
534
|
+
return {
|
|
535
|
+
url,
|
|
536
|
+
method,
|
|
537
|
+
provider: this.provider,
|
|
538
|
+
status: res.status,
|
|
539
|
+
clientId: this.clientId
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
536
543
|
async request(accessToken, url, method, payload, options) {
|
|
537
544
|
options = options || {};
|
|
538
545
|
|
|
@@ -542,7 +549,7 @@ class OutlookOauth {
|
|
|
542
549
|
method: method.toUpperCase(),
|
|
543
550
|
headers: {
|
|
544
551
|
Authorization: `Bearer ${accessToken}`,
|
|
545
|
-
'User-Agent':
|
|
552
|
+
'User-Agent': USER_AGENT
|
|
546
553
|
},
|
|
547
554
|
// Sent exactly once. Which failures are worth repeating depends on the method and on
|
|
548
555
|
// what Graph answered, and that is decided by the request layer above this one
|
|
@@ -556,93 +563,22 @@ class OutlookOauth {
|
|
|
556
563
|
reqData.headers = Object.assign({}, options.headers, reqData.headers);
|
|
557
564
|
}
|
|
558
565
|
|
|
559
|
-
|
|
560
|
-
if (!Buffer.isBuffer(payload)) {
|
|
561
|
-
reqData.headers.Accept = 'application/json';
|
|
562
|
-
reqData.headers['Content-Type'] = options?.contentType || 'application/json';
|
|
563
|
-
reqData.body = JSON.stringify(payload);
|
|
564
|
-
} else {
|
|
565
|
-
reqData.headers['Content-Type'] = options?.contentType || 'application/x-www-form-urlencoded';
|
|
566
|
-
reqData.body = payload;
|
|
567
|
-
}
|
|
568
|
-
} else if (payload && method === 'get') {
|
|
569
|
-
let parsedUrl = new URL(url);
|
|
570
|
-
for (let key of Object.keys(payload)) {
|
|
571
|
-
if (typeof payload[key] === 'undefined' || payload[key] === null) {
|
|
572
|
-
continue;
|
|
573
|
-
}
|
|
574
|
-
parsedUrl.searchParams.append(key, payload[key].toString());
|
|
575
|
-
}
|
|
576
|
-
url = parsedUrl.href;
|
|
577
|
-
}
|
|
566
|
+
url = encodeRequest(reqData, url, method, payload, options);
|
|
578
567
|
|
|
579
|
-
let
|
|
580
|
-
let res = await fetchCmd(url, reqData).catch(err => {
|
|
581
|
-
// undici puts the network code on err.cause; callers read err.code
|
|
582
|
-
throw promoteCauseCode(err);
|
|
583
|
-
});
|
|
584
|
-
let reqTime = Date.now() - startTime;
|
|
568
|
+
let { res, reqTime } = await timedFetch(url, reqData);
|
|
585
569
|
|
|
586
570
|
if (!res.ok) {
|
|
587
|
-
let err =
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
status: res.status,
|
|
594
|
-
clientId: this.clientId,
|
|
595
|
-
scopes: this.scopes,
|
|
596
|
-
reqTime
|
|
597
|
-
};
|
|
598
|
-
|
|
599
|
-
// Capture Retry-After (sent with 429, and with 503 while Graph is shedding load) so
|
|
600
|
-
// the retry layer can honour it
|
|
601
|
-
const retryAfter = parseRetryAfter(res.headers);
|
|
602
|
-
if (retryAfter !== null) {
|
|
603
|
-
err.retryAfter = retryAfter;
|
|
604
|
-
err.oauthRequest.retryAfter = retryAfter;
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
try {
|
|
608
|
-
err.oauthRequest.response = await res.json();
|
|
609
|
-
|
|
610
|
-
if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.oauthRequest.response.error_description)) {
|
|
611
|
-
// key might have been invalidated or renewed
|
|
612
|
-
err.oauthRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
let flag = checkForFlags(err.oauthRequest.response);
|
|
616
|
-
if (flag) {
|
|
617
|
-
await this.setFlag(flag);
|
|
618
|
-
if (flag.code && !err.code) {
|
|
619
|
-
err.code = flag.code;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
} catch (E) {
|
|
623
|
-
// ignore
|
|
624
|
-
} finally {
|
|
625
|
-
if (this.logger) {
|
|
626
|
-
this.logger.warn(Object.assign({ msg: 'API request failed' }, err.oauthRequest));
|
|
627
|
-
}
|
|
628
|
-
}
|
|
571
|
+
let err = buildRequestFailure(res, Object.assign(this.logContext(url, method, res), { scopes: this.scopes, reqTime }));
|
|
572
|
+
await handleFailedResponse(this, res, err, {
|
|
573
|
+
checkForFlags,
|
|
574
|
+
exposeSecret: response => EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(response.error_description),
|
|
575
|
+
logger: this.logger
|
|
576
|
+
});
|
|
629
577
|
throw err;
|
|
630
578
|
}
|
|
631
579
|
|
|
632
580
|
if (this.logger) {
|
|
633
|
-
this.logger.debug(
|
|
634
|
-
Object.assign(
|
|
635
|
-
{ msg: 'External API request completed' },
|
|
636
|
-
{
|
|
637
|
-
url,
|
|
638
|
-
method,
|
|
639
|
-
provider: this.provider,
|
|
640
|
-
status: res.status,
|
|
641
|
-
clientId: this.clientId,
|
|
642
|
-
reqTime
|
|
643
|
-
}
|
|
644
|
-
)
|
|
645
|
-
);
|
|
581
|
+
this.logger.debug(Object.assign({ msg: 'External API request completed' }, this.logContext(url, method, res), { reqTime }));
|
|
646
582
|
}
|
|
647
583
|
|
|
648
584
|
// clear potential auth flag
|
|
@@ -661,46 +597,10 @@ class OutlookOauth {
|
|
|
661
597
|
// Parse JSON response with handling for empty or invalid responses
|
|
662
598
|
// Microsoft Graph API may occasionally return 200 OK with empty body
|
|
663
599
|
let responseText = await res.text();
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
err.oauthRequest = {
|
|
669
|
-
url,
|
|
670
|
-
method,
|
|
671
|
-
provider: this.provider,
|
|
672
|
-
status: res.status,
|
|
673
|
-
clientId: this.clientId,
|
|
674
|
-
reqTime
|
|
675
|
-
};
|
|
676
|
-
if (this.logger) {
|
|
677
|
-
this.logger.error(Object.assign({ msg: 'API returned empty response' }, err.oauthRequest));
|
|
678
|
-
}
|
|
679
|
-
throw err;
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
try {
|
|
683
|
-
return JSON.parse(responseText);
|
|
684
|
-
} catch (parseErr) {
|
|
685
|
-
let err = new Error('Invalid JSON response from API');
|
|
686
|
-
err.code = 'InvalidJSON';
|
|
687
|
-
err.statusCode = res.status;
|
|
688
|
-
err.oauthRequest = {
|
|
689
|
-
url,
|
|
690
|
-
method,
|
|
691
|
-
provider: this.provider,
|
|
692
|
-
status: res.status,
|
|
693
|
-
clientId: this.clientId,
|
|
694
|
-
reqTime,
|
|
695
|
-
responseLength: responseText.length,
|
|
696
|
-
responseStart: responseText.slice(0, 200),
|
|
697
|
-
responseEnd: responseText.length > 200 ? responseText.slice(-200) : undefined
|
|
698
|
-
};
|
|
699
|
-
if (this.logger) {
|
|
700
|
-
this.logger.error(Object.assign({ msg: 'API returned invalid JSON' }, err.oauthRequest, { err: parseErr }));
|
|
701
|
-
}
|
|
702
|
-
throw err;
|
|
703
|
-
}
|
|
600
|
+
return parseJsonResponse(responseText, extra => Object.assign(this.logContext(url, method, res), { reqTime }, extra), {
|
|
601
|
+
statusCode: res.status,
|
|
602
|
+
logger: this.logger
|
|
603
|
+
});
|
|
704
604
|
}
|
|
705
605
|
}
|
|
706
606
|
|