emailengine-app 2.82.0 → 2.82.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.
- package/.ncurc.js +23 -1
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +44 -0
- package/DOCKER_DEPLOYMENT.md +13 -12
- package/bin/emailengine.js +77 -7
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +35 -10
- package/lib/api-routes/account-binding.js +58 -0
- package/lib/api-routes/account-routes.js +48 -9
- package/lib/api-routes/behavior-notes.js +4 -0
- package/lib/api-routes/gateway-routes.js +10 -2
- package/lib/api-routes/message-routes.js +10 -3
- package/lib/api-routes/outbox-routes.js +1 -1
- package/lib/api-routes/settings-routes.js +1 -2
- package/lib/api-routes/token-routes.js +1 -1
- package/lib/autodetect-imap-settings.js +146 -4
- package/lib/consts.js +12 -0
- package/lib/db.js +1 -19
- package/lib/delivery-error.js +68 -1
- package/lib/email-client/base-client.js +6 -13
- package/lib/email-client/credential-errors.js +21 -5
- package/lib/email-client/gmail-client.js +2 -2
- package/lib/email-client/imap-client.js +2 -1
- package/lib/email-client/message-builder.js +41 -11
- package/lib/email-client/outlook-client.js +196 -67
- package/lib/enum-descriptions.js +5 -1
- package/lib/export.js +8 -2
- package/lib/gateway.js +5 -0
- package/lib/get-secret.js +1 -21
- package/lib/mcp/tools.js +95 -36
- package/lib/oauth/gmail.js +42 -12
- package/lib/oauth/mail-ru.js +24 -17
- package/lib/oauth/outlook.js +34 -24
- package/lib/oauth/scope-checker.js +35 -1
- package/lib/oauth/scope-list.js +55 -0
- package/lib/oauth/token-fetch.js +47 -0
- package/lib/oauth2-apps.js +16 -47
- package/lib/outbox.js +2 -7
- package/lib/queue-retention.js +4 -2
- package/lib/read-env-value.js +33 -2
- package/lib/schemas.js +62 -15
- package/lib/token-audit-log.js +3 -2
- package/lib/tools.js +1 -1
- package/lib/ui-routes/account-routes.js +40 -7
- package/lib/ui-routes/oauth-config-routes.js +3 -14
- package/lib/ui-routes/route-helpers.js +23 -23
- package/lib/ui-routes/special-use-paths.js +33 -0
- package/lib/utils/network.js +9 -17
- package/package.json +18 -18
- package/sbom.json +1 -1
- package/server.js +21 -3
- package/setup-production.sh +16 -7
- package/static/licenses.html +30 -20
- package/translations/messages.pot +74 -56
- package/views/account-workspace-error.hbs +30 -0
- package/views/accounts/account.hbs +9 -4
- package/views/accounts/edit.hbs +11 -2
- package/views/internals/index.hbs +1 -1
- package/views/partials/gmail_api_scopes.hbs +16 -0
- package/views/partials/oauth_form.hbs +67 -94
- package/views/partials/oauth_pubsub_app_select.hbs +43 -0
- package/views/partials/scope_info.hbs +14 -23
- package/workers/api.js +62 -27
- package/workers/imap.js +6 -3
- package/workers/submit.js +2 -5
package/lib/mcp/tools.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
// The MCP tool registry and executor.
|
|
4
4
|
//
|
|
5
5
|
// Tools are not defined here. A route opts in by carrying a `plugins.mcp` block
|
|
6
|
-
// ({ name, title, description, keep?/omit?, force?, bounds?, binary?, resourceUriTemplate? }),
|
|
7
|
-
// this module derives everything else from what
|
|
8
|
-
//
|
|
6
|
+
// ({ name, title, description, keep?/omit?, force?, bounds?, binary?, tail?, resourceUriTemplate? }),
|
|
7
|
+
// and this module derives everything else from what the route already declares: the input schema from
|
|
8
|
+
// its joi validation schemas, the behavior
|
|
9
9
|
// annotations from routeGrant() - the same source /swagger.json publishes as x-ee-action and
|
|
10
10
|
// x-ee-group - and the dispatch target from its method and path. There is deliberately no second
|
|
11
11
|
// description of any endpoint: a tool cannot disagree with the route it wraps.
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
// do over REST. This module never touches Redis and never bypasses a handler.
|
|
17
17
|
|
|
18
18
|
const { routeGrant, surfaceAdmits, surfaceBoundAdmits, PER_REQUEST_SURFACES, ACTION } = require('../api-routes/permission-map');
|
|
19
|
+
const { routeAdmitsBoundToken } = require('../api-routes/account-binding');
|
|
19
20
|
const tokenPermissions = require('../token-permissions');
|
|
20
21
|
const { mcpOptions } = require('../api-routes/route-metadata');
|
|
21
22
|
const { joiToJsonSchema } = require('./json-schema');
|
|
@@ -39,9 +40,27 @@ const MAX_TOOL_BINARY_BYTES = 1024 * 1024;
|
|
|
39
40
|
|
|
40
41
|
const TRUNCATION_NOTICE = size => `\n\n[Result truncated by EmailEngine: the full response was ${size} bytes. Narrow the request to see the rest.]`;
|
|
41
42
|
|
|
43
|
+
// The same notice for a result cut from the front, where it has to lead so the kept text still ends
|
|
44
|
+
// on the newest line
|
|
45
|
+
const LEADING_TRUNCATION_NOTICE = size =>
|
|
46
|
+
`[Earlier output dropped by EmailEngine: the full response was ${size} bytes. Only the most recent output follows.]\n\n`;
|
|
47
|
+
|
|
42
48
|
// Every key a plugins.mcp block may carry. The one place the block's shape is written down, so a
|
|
43
49
|
// misspelling is a build failure rather than a knob that quietly does nothing.
|
|
44
|
-
const MCP_OPTION_KEYS = new Set([
|
|
50
|
+
const MCP_OPTION_KEYS = new Set([
|
|
51
|
+
'name',
|
|
52
|
+
'title',
|
|
53
|
+
'description',
|
|
54
|
+
'keep',
|
|
55
|
+
'omit',
|
|
56
|
+
'force',
|
|
57
|
+
'bounds',
|
|
58
|
+
'binary',
|
|
59
|
+
'tail',
|
|
60
|
+
'resourceUriTemplate',
|
|
61
|
+
'endpoint',
|
|
62
|
+
'openWorld'
|
|
63
|
+
]);
|
|
45
64
|
|
|
46
65
|
// One registry per Hapi server, built on first use and held for the life of the worker - route
|
|
47
66
|
// definitions cannot change while it runs, and the build walks every joi schema of every wrapped
|
|
@@ -279,7 +298,19 @@ function buildToolRegistry(routes) {
|
|
|
279
298
|
// are declared: the other half of what tools/list filters on, and what the admin
|
|
280
299
|
// pages group and count by
|
|
281
300
|
surfaces: [...PER_REQUEST_SURFACES].filter(scope => surfaceAdmits(scope, grant)),
|
|
301
|
+
// Whether an account-bound credential can reach this tool at all, which is the same
|
|
302
|
+
// question the api-token strategy answers when it checks the binding - so it is answered
|
|
303
|
+
// from the table that strategy switches on (lib/api-routes/account-binding.js) rather
|
|
304
|
+
// than from "the route takes an `account` argument". The two are different questions:
|
|
305
|
+
// verify_oauth2_app's `account` is a mailbox address for a delegation check, and
|
|
306
|
+
// create_account, create_account_setup_link and add_to_blocklist all take one in the
|
|
307
|
+
// payload, yet a bound token is refused every one of them.
|
|
308
|
+
accountScoped: routeAdmitsBoundToken(route.method, route.path),
|
|
282
309
|
binary: !!options.binary,
|
|
310
|
+
// A text result whose newest and most useful lines are LAST, so the cap keeps its end
|
|
311
|
+
// rather than its beginning. Declared by the route, because which half of a response
|
|
312
|
+
// matters is a property of that endpoint and not something this module can infer
|
|
313
|
+
tail: !!options.tail,
|
|
283
314
|
resourceUriTemplate: options.resourceUriTemplate
|
|
284
315
|
});
|
|
285
316
|
}
|
|
@@ -291,7 +322,7 @@ function buildToolRegistry(routes) {
|
|
|
291
322
|
// the worker and three admin pages plus the MCP door read this.
|
|
292
323
|
const grants = tools.map(tool => {
|
|
293
324
|
const entry = byName.get(tool.name);
|
|
294
|
-
return Object.assign({ name: tool.name, accountScoped: entry.
|
|
325
|
+
return Object.assign({ name: tool.name, accountScoped: entry.accountScoped, surfaces: entry.surfaces }, entry.grant);
|
|
295
326
|
});
|
|
296
327
|
|
|
297
328
|
return { tools, byName, grants };
|
|
@@ -318,7 +349,7 @@ function buildToolRegistry(routes) {
|
|
|
318
349
|
function effectiveArguments(tool, args, boundAccount) {
|
|
319
350
|
const effective = Object.assign({}, args, tool.forcedValues);
|
|
320
351
|
|
|
321
|
-
if (boundAccount && tool.
|
|
352
|
+
if (boundAccount && tool.accountScoped && (effective.account === undefined || effective.account === null || effective.account === '')) {
|
|
322
353
|
effective.account = boundAccount;
|
|
323
354
|
}
|
|
324
355
|
|
|
@@ -371,8 +402,22 @@ function buildQuery(args, sources) {
|
|
|
371
402
|
return rendered ? `?${rendered}` : '';
|
|
372
403
|
}
|
|
373
404
|
|
|
374
|
-
|
|
375
|
-
|
|
405
|
+
/**
|
|
406
|
+
* An MCP text result, cut to the size cap.
|
|
407
|
+
*
|
|
408
|
+
* The cap applies here and not only in jsonResult(), because plenty of what this endpoint returns is
|
|
409
|
+
* already text: an account's whole connection log, a raw message source, and the API's own error body
|
|
410
|
+
* echoed back on a 4xx. Those used to be returned whole, so one tool call could put megabytes into
|
|
411
|
+
* the conversation while the JSON results beside it were held to 128KB.
|
|
412
|
+
*
|
|
413
|
+
* @param {String} text - the result text
|
|
414
|
+
* @param {Object} [opts]
|
|
415
|
+
* @param {Boolean} [opts.isError] - mark the result as a tool execution error
|
|
416
|
+
* @param {Boolean} [opts.tail] - keep the END of an oversized value rather than its beginning
|
|
417
|
+
* @returns {Object} an MCP tool result
|
|
418
|
+
*/
|
|
419
|
+
function textResult(text, { isError = false, tail = false } = {}) {
|
|
420
|
+
const result = { content: [{ type: 'text', text: capText(text, tail) }] };
|
|
376
421
|
if (isError) {
|
|
377
422
|
result.isError = true;
|
|
378
423
|
}
|
|
@@ -380,44 +425,58 @@ function textResult(text, { isError = false } = {}) {
|
|
|
380
425
|
}
|
|
381
426
|
|
|
382
427
|
/**
|
|
383
|
-
*
|
|
428
|
+
* Applies the result cap to a text value, with the notice that says what was dropped.
|
|
429
|
+
*
|
|
430
|
+
* The budget is in bytes, and String.slice() counts UTF-16 code units: slicing to the byte cap left a
|
|
431
|
+
* result up to three times over it, so a mailbox of CJK or Cyrillic text sailed through while carrying
|
|
432
|
+
* a notice claiming it had been truncated. The value is encoded once here and both halves of the cut
|
|
433
|
+
* work on that buffer.
|
|
384
434
|
*
|
|
385
|
-
* String
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
* any trailing continuation byte, keeps the budget honest and never emits a split code point.
|
|
435
|
+
* @param {String} text - the result text
|
|
436
|
+
* @param {Boolean} [tail] - keep the END of an oversized value rather than its beginning
|
|
437
|
+
* @returns {String} the value itself, or a cut of it carrying the notice
|
|
389
438
|
*/
|
|
390
|
-
function
|
|
439
|
+
function capText(text, tail) {
|
|
391
440
|
const buf = Buffer.from(text, 'utf8');
|
|
392
|
-
if (buf.length <=
|
|
441
|
+
if (buf.length <= MAX_TOOL_RESULT_BYTES) {
|
|
393
442
|
return text;
|
|
394
443
|
}
|
|
444
|
+
return tail ? LEADING_TRUNCATION_NOTICE(buf.length) + lastBytesOf(buf) : firstBytesOf(buf) + TRUNCATION_NOTICE(buf.length);
|
|
445
|
+
}
|
|
395
446
|
|
|
396
|
-
|
|
397
|
-
|
|
447
|
+
// The first MAX_TOOL_RESULT_BYTES of an encoded value, backed off any trailing continuation byte
|
|
448
|
+
// (0b10xxxxxx marks one) so the cut never splits a code point into a replacement character.
|
|
449
|
+
function firstBytesOf(buf) {
|
|
450
|
+
let end = MAX_TOOL_RESULT_BYTES;
|
|
398
451
|
while (end > 0 && (buf[end] & 0xc0) === 0x80) {
|
|
399
452
|
end--;
|
|
400
453
|
}
|
|
401
|
-
|
|
402
454
|
return buf.subarray(0, end).toString('utf8');
|
|
403
455
|
}
|
|
404
456
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
text = truncateToBytes(text, MAX_TOOL_RESULT_BYTES) + TRUNCATION_NOTICE(size);
|
|
414
|
-
// A structuredContent that repeats the oversized value would defeat the cap
|
|
415
|
-
structuredContent = undefined;
|
|
457
|
+
// The last MAX_TOOL_RESULT_BYTES of an encoded value, starting on a whole code point and a whole line.
|
|
458
|
+
// A result that declares `tail` carries one record per line (an account log is one JSON entry per
|
|
459
|
+
// line), so a cut landing mid-line hands the reader a fragment that does not parse; the partial first
|
|
460
|
+
// line is dropped when there is a later one to start from.
|
|
461
|
+
function lastBytesOf(buf) {
|
|
462
|
+
let start = buf.length - MAX_TOOL_RESULT_BYTES;
|
|
463
|
+
while (start < buf.length && (buf[start] & 0xc0) === 0x80) {
|
|
464
|
+
start++;
|
|
416
465
|
}
|
|
466
|
+
const lineBreak = buf.indexOf(0x0a, start);
|
|
467
|
+
return buf.subarray(lineBreak < 0 ? start : lineBreak + 1).toString('utf8');
|
|
468
|
+
}
|
|
417
469
|
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
470
|
+
function jsonResult(value) {
|
|
471
|
+
// Compact on purpose: an indent is pure padding to a model, it inflates every response by a
|
|
472
|
+
// double-digit percentage, and it counts against the size cap
|
|
473
|
+
const text = JSON.stringify(value);
|
|
474
|
+
const capped = capText(text);
|
|
475
|
+
|
|
476
|
+
const result = { content: [{ type: 'text', text: capped }] };
|
|
477
|
+
// A structuredContent that repeats an oversized value would defeat the cap
|
|
478
|
+
if (capped === text && value !== null && typeof value === 'object') {
|
|
479
|
+
result.structuredContent = value;
|
|
421
480
|
}
|
|
422
481
|
return result;
|
|
423
482
|
}
|
|
@@ -521,7 +580,7 @@ async function callTool({ server, tool, args, request }) {
|
|
|
521
580
|
}
|
|
522
581
|
|
|
523
582
|
if (typeof res.result === 'string') {
|
|
524
|
-
return textResult(res.result);
|
|
583
|
+
return textResult(res.result, { tail: tool.tail });
|
|
525
584
|
}
|
|
526
585
|
|
|
527
586
|
return jsonResult(dropPlaintextTwin(res.result));
|
|
@@ -564,7 +623,7 @@ function buildResourceUri(tool, args) {
|
|
|
564
623
|
* The single spelling of what tools/list filters on, so a credential's view of the catalog is
|
|
565
624
|
* decided in one place. Two rules, and a consumer that applies only one of them overstates the
|
|
566
625
|
* catalog: the permission record, and the account binding - a credential bound to one account is
|
|
567
|
-
* never offered the tools that
|
|
626
|
+
* never offered the tools that are not about one account, because there is nothing to bind them to.
|
|
568
627
|
*
|
|
569
628
|
* Advertisement only. tools/call dispatches whatever is asked and the injected inner request stays
|
|
570
629
|
* the enforcement, so this is allowed to be a prediction rather than a gate.
|
|
@@ -576,7 +635,7 @@ function buildResourceUri(tool, args) {
|
|
|
576
635
|
* @returns {Boolean}
|
|
577
636
|
*/
|
|
578
637
|
function toolVisibleTo(entry, { tokenData, boundAccount }) {
|
|
579
|
-
if (boundAccount && !entry.
|
|
638
|
+
if (boundAccount && !entry.accountScoped) {
|
|
580
639
|
return false;
|
|
581
640
|
}
|
|
582
641
|
// The scope bound first: a credential holding only the mail scope is not offered the
|
|
@@ -605,7 +664,7 @@ function toolVisibleTo(entry, { tokenData, boundAccount }) {
|
|
|
605
664
|
* @returns {Object} the tool definition to advertise
|
|
606
665
|
*/
|
|
607
666
|
function toolDefinitionFor(entry, { boundAccount } = {}) {
|
|
608
|
-
if (!boundAccount || !entry.
|
|
667
|
+
if (!boundAccount || !entry.accountScoped) {
|
|
609
668
|
return entry.definition;
|
|
610
669
|
}
|
|
611
670
|
|
package/lib/oauth/gmail.js
CHANGED
|
@@ -7,6 +7,7 @@ const crypto = require('crypto');
|
|
|
7
7
|
const { fetch: fetchCmd } = require('undici');
|
|
8
8
|
|
|
9
9
|
const { ExternalAccountSigner } = require('./external-account-signer');
|
|
10
|
+
const { fetchTokenRequest } = require('./token-fetch');
|
|
10
11
|
|
|
11
12
|
const SERVICE_AUTH_METHODS = new Set(['serviceKey', 'externalAccount']);
|
|
12
13
|
|
|
@@ -48,6 +49,14 @@ function parseExternalAccountConfig(externalAccount) {
|
|
|
48
49
|
}
|
|
49
50
|
}
|
|
50
51
|
|
|
52
|
+
// The two providers that reach Gmail, whichever way they authenticate: `gmail` sends a user through
|
|
53
|
+
// Google's consent screen, `gmailService` presents a service account's domain-wide delegation. What
|
|
54
|
+
// they reach (IMAP XOAUTH2 or the Gmail HTTP API) is decided by baseScopes, not by which of these it is.
|
|
55
|
+
const GMAIL_PROVIDERS = new Set(['gmail', 'gmailService']);
|
|
56
|
+
|
|
57
|
+
// Every Gmail scope is this plus a short name, which is the form the app form's skipScopes presets use
|
|
58
|
+
const GMAIL_SCOPE_PREFIX = 'https://www.googleapis.com/auth';
|
|
59
|
+
|
|
51
60
|
const GMAIL_SCOPES = {
|
|
52
61
|
imap: ['https://mail.google.com/'],
|
|
53
62
|
api: ['https://www.googleapis.com/auth/gmail.modify'],
|
|
@@ -205,6 +214,24 @@ const formatFetchResponse = (responseObj, logRaw) => {
|
|
|
205
214
|
return data;
|
|
206
215
|
};
|
|
207
216
|
|
|
217
|
+
/**
|
|
218
|
+
* The Google Workspace or Cloud organization domain an ID token belongs to, or null.
|
|
219
|
+
*
|
|
220
|
+
* `hd=*` on the authorization URL (generateAuthUrl below, for an application with "Show only Google
|
|
221
|
+
* Workspace accounts") only filters the account chooser Google SHOWS. A link assembled without that
|
|
222
|
+
* argument, or a user who switches account inside the chooser, reaches the callback with a consumer
|
|
223
|
+
* account and used to complete the setup anyway. The hosted-domain claim of the ID token is the
|
|
224
|
+
* back-channel answer to the same question: Google sets it only for an account that belongs to a
|
|
225
|
+
* Workspace or Cloud organization, so its absence is what a consumer account looks like.
|
|
226
|
+
*
|
|
227
|
+
* @param {Object|null} idTokenPayload - decoded ID token payload (lib/decode-jwt-payload.js)
|
|
228
|
+
* @returns {String|null} the hosted domain, or null when the token names none
|
|
229
|
+
*/
|
|
230
|
+
function workspaceDomainOf(idTokenPayload) {
|
|
231
|
+
const hd = idTokenPayload && typeof idTokenPayload.hd === 'string' ? idTokenPayload.hd.trim() : '';
|
|
232
|
+
return hd || null;
|
|
233
|
+
}
|
|
234
|
+
|
|
208
235
|
class GmailOauth {
|
|
209
236
|
constructor(opts) {
|
|
210
237
|
const defaultBaseScopes = (opts.baseScopes && GMAIL_SCOPES[opts.baseScopes]) || GMAIL_SCOPES.imap;
|
|
@@ -372,12 +399,12 @@ class GmailOauth {
|
|
|
372
399
|
body: tokenRequest.body
|
|
373
400
|
};
|
|
374
401
|
|
|
375
|
-
let res = await
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
);
|
|
402
|
+
let res = await fetchTokenRequest(requestUrl, fetchOpts, {
|
|
403
|
+
grant: 'authorization_code',
|
|
404
|
+
provider: this.provider,
|
|
405
|
+
clientId: this.clientId,
|
|
406
|
+
serviceClient: this.serviceClient
|
|
407
|
+
});
|
|
381
408
|
|
|
382
409
|
let responseJson;
|
|
383
410
|
try {
|
|
@@ -487,12 +514,12 @@ class GmailOauth {
|
|
|
487
514
|
body: bodyString
|
|
488
515
|
};
|
|
489
516
|
|
|
490
|
-
let res = await
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
);
|
|
517
|
+
let res = await fetchTokenRequest(requestUrl, fetchOpts, {
|
|
518
|
+
grant: 'refresh_token',
|
|
519
|
+
provider: this.provider,
|
|
520
|
+
clientId: this.clientId,
|
|
521
|
+
serviceClient: this.serviceClient
|
|
522
|
+
});
|
|
496
523
|
|
|
497
524
|
let responseJson;
|
|
498
525
|
try {
|
|
@@ -826,8 +853,11 @@ module.exports.GmailOauth = GmailOauth;
|
|
|
826
853
|
// Exported for unit testing the auth error-to-flag mapping.
|
|
827
854
|
module.exports.checkForFlags = checkForFlags;
|
|
828
855
|
module.exports.checkForUserFlags = checkForUserFlags;
|
|
856
|
+
module.exports.workspaceDomainOf = workspaceDomainOf;
|
|
829
857
|
module.exports.GMAIL_SCOPES = GMAIL_SCOPES;
|
|
830
858
|
module.exports.GMAIL_API_SCOPES = GMAIL_API_SCOPES;
|
|
859
|
+
module.exports.GMAIL_PROVIDERS = GMAIL_PROVIDERS;
|
|
860
|
+
module.exports.GMAIL_SCOPE_PREFIX = GMAIL_SCOPE_PREFIX;
|
|
831
861
|
module.exports.OPENID_SCOPES = OPENID_SCOPES;
|
|
832
862
|
module.exports.LocalKeySigner = LocalKeySigner;
|
|
833
863
|
module.exports.parseExternalAccountConfig = parseExternalAccountConfig;
|
package/lib/oauth/mail-ru.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const packageData = require('../../package.json');
|
|
4
4
|
const { fetch: fetchCmd } = require('undici');
|
|
5
|
+
const { fetchTokenRequest } = require('./token-fetch');
|
|
5
6
|
const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
|
|
6
7
|
|
|
7
8
|
const MAIL_RU_SCOPES = ['userinfo', 'mail.imap'];
|
|
@@ -109,16 +110,19 @@ class MailRuOauth {
|
|
|
109
110
|
let requestUrl = tokenRequest.url;
|
|
110
111
|
let method = 'post';
|
|
111
112
|
|
|
112
|
-
let res = await
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
113
|
+
let res = await fetchTokenRequest(
|
|
114
|
+
tokenRequest.url,
|
|
115
|
+
{
|
|
116
|
+
method,
|
|
117
|
+
headers: {
|
|
118
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
119
|
+
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
|
|
120
|
+
Authorization: `Basic ${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64')}`
|
|
121
|
+
},
|
|
122
|
+
body: tokenRequest.body
|
|
118
123
|
},
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
});
|
|
124
|
+
{ grant: 'authorization_code', provider: this.provider, clientId: this.clientId }
|
|
125
|
+
);
|
|
122
126
|
|
|
123
127
|
let responseJson;
|
|
124
128
|
try {
|
|
@@ -194,15 +198,18 @@ class MailRuOauth {
|
|
|
194
198
|
let method = 'post';
|
|
195
199
|
|
|
196
200
|
const bodyString = url.searchParams.toString();
|
|
197
|
-
let res = await
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
201
|
+
let res = await fetchTokenRequest(
|
|
202
|
+
requestUrl,
|
|
203
|
+
{
|
|
204
|
+
method,
|
|
205
|
+
headers: {
|
|
206
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
207
|
+
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
208
|
+
},
|
|
209
|
+
body: bodyString
|
|
202
210
|
},
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
});
|
|
211
|
+
{ grant: 'refresh_token', provider: this.provider, clientId: this.clientId }
|
|
212
|
+
);
|
|
206
213
|
|
|
207
214
|
let responseJson;
|
|
208
215
|
try {
|
package/lib/oauth/outlook.js
CHANGED
|
@@ -4,6 +4,7 @@ const packageData = require('../../package.json');
|
|
|
4
4
|
const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
|
|
5
5
|
|
|
6
6
|
const { fetch: fetchCmd } = require('undici');
|
|
7
|
+
const { fetchTokenRequest } = require('./token-fetch');
|
|
7
8
|
|
|
8
9
|
// Individual MS Graph API scope names for detection
|
|
9
10
|
// These are the scope names extracted from full MS Graph API scope URLs
|
|
@@ -269,15 +270,18 @@ class OutlookOauth {
|
|
|
269
270
|
let requestUrl = tokenRequest.url;
|
|
270
271
|
let method = 'post';
|
|
271
272
|
|
|
272
|
-
let res = await
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
273
|
+
let res = await fetchTokenRequest(
|
|
274
|
+
tokenRequest.url,
|
|
275
|
+
{
|
|
276
|
+
method,
|
|
277
|
+
headers: {
|
|
278
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
279
|
+
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
280
|
+
},
|
|
281
|
+
body: tokenRequest.body
|
|
277
282
|
},
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
});
|
|
283
|
+
{ grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority }
|
|
284
|
+
);
|
|
281
285
|
|
|
282
286
|
let responseJson;
|
|
283
287
|
try {
|
|
@@ -370,15 +374,18 @@ class OutlookOauth {
|
|
|
370
374
|
let method = 'post';
|
|
371
375
|
|
|
372
376
|
const bodyString = url.searchParams.toString();
|
|
373
|
-
let res = await
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
377
|
+
let res = await fetchTokenRequest(
|
|
378
|
+
requestUrl,
|
|
379
|
+
{
|
|
380
|
+
method,
|
|
381
|
+
headers: {
|
|
382
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
383
|
+
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
384
|
+
},
|
|
385
|
+
body: bodyString
|
|
378
386
|
},
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
});
|
|
387
|
+
{ grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority }
|
|
388
|
+
);
|
|
382
389
|
|
|
383
390
|
let responseJson;
|
|
384
391
|
try {
|
|
@@ -461,15 +468,18 @@ class OutlookOauth {
|
|
|
461
468
|
let method = 'post';
|
|
462
469
|
|
|
463
470
|
const bodyString = url.searchParams.toString();
|
|
464
|
-
let res = await
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
471
|
+
let res = await fetchTokenRequest(
|
|
472
|
+
requestUrl,
|
|
473
|
+
{
|
|
474
|
+
method,
|
|
475
|
+
headers: {
|
|
476
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
477
|
+
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
478
|
+
},
|
|
479
|
+
body: bodyString
|
|
469
480
|
},
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
});
|
|
481
|
+
{ grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority }
|
|
482
|
+
);
|
|
473
483
|
|
|
474
484
|
let responseJson;
|
|
475
485
|
try {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { GMAIL_API_SCOPES } = require('./gmail');
|
|
3
|
+
const { GMAIL_API_SCOPES, GMAIL_SCOPES, GMAIL_PROVIDERS, GMAIL_SCOPE_PREFIX } = require('./gmail');
|
|
4
|
+
const { formatExtraScopes } = require('./scope-list');
|
|
4
5
|
const { OUTLOOK_API_SCOPES } = require('./outlook');
|
|
5
6
|
|
|
6
7
|
// Known Microsoft Graph API endpoints across different cloud environments
|
|
@@ -173,6 +174,38 @@ function checkOutlookScopes(accountData, logger) {
|
|
|
173
174
|
return checkAccountScopes('outlook', scopes, logger);
|
|
174
175
|
}
|
|
175
176
|
|
|
177
|
+
/**
|
|
178
|
+
* Whether an OAuth2 APPLICATION is configured for sending only, as the app page presents it.
|
|
179
|
+
*
|
|
180
|
+
* Only an API-based Gmail app can be: `baseScopes: 'api'` is what makes one reach the Gmail HTTP API
|
|
181
|
+
* rather than IMAP XOAUTH2, and it is not a property of the provider - a service account delegated
|
|
182
|
+
* gmail.send alone is as send-only as an interactive app, which the admin route used to miss by keying
|
|
183
|
+
* on `provider === 'gmail'`.
|
|
184
|
+
*
|
|
185
|
+
* Judged on the scopes the app really requests, which is the list the authentication URL is built from:
|
|
186
|
+
* the api-mode default it does not have to repeat, its own extras, minus what skipScopes removes.
|
|
187
|
+
* Reading extraScopes alone called an app send-only while it still requested gmail.modify. A scope may
|
|
188
|
+
* be stored under its short name, which Google's own scope URLs are not, so the list is expanded first.
|
|
189
|
+
*
|
|
190
|
+
* Pure: extracted out of lib/ui-routes/oauth-config-routes.js, which built an Account instance and
|
|
191
|
+
* resolved the encryption secret only to reach checkAccountScopes() above.
|
|
192
|
+
*
|
|
193
|
+
* @param {Object} app - A stored OAuth2 application record
|
|
194
|
+
* @returns {boolean} True when the app grants sending but not reading
|
|
195
|
+
*/
|
|
196
|
+
function isSendOnlyGmailApp(app) {
|
|
197
|
+
if (!app || !GMAIL_PROVIDERS.has(app.provider) || app.baseScopes !== 'api') {
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const scopes = formatExtraScopes(app.extraScopes, app.baseScopes, GMAIL_SCOPES, app.skipScopes, GMAIL_SCOPE_PREFIX).map(scope =>
|
|
202
|
+
scope.startsWith('https://') ? scope : `${GMAIL_SCOPE_PREFIX}/${scope}`
|
|
203
|
+
);
|
|
204
|
+
const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
|
|
205
|
+
|
|
206
|
+
return hasSendScope && !hasReadScope;
|
|
207
|
+
}
|
|
208
|
+
|
|
176
209
|
/**
|
|
177
210
|
* Determines if an account is in send-only mode based on its scopes.
|
|
178
211
|
*
|
|
@@ -189,6 +222,7 @@ function isSendOnlyByScopes(provider, accountData, logger) {
|
|
|
189
222
|
|
|
190
223
|
module.exports = {
|
|
191
224
|
checkAccountScopes,
|
|
225
|
+
isSendOnlyGmailApp,
|
|
192
226
|
checkGmailScopes,
|
|
193
227
|
checkOutlookScopes,
|
|
194
228
|
isSendOnlyByScopes,
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The scope list an OAuth2 application actually requests, derived from what is stored on it. Kept in a
|
|
4
|
+
// leaf module because two callers need it from opposite ends of the dependency graph: lib/oauth2-apps.js
|
|
5
|
+
// builds the authentication URL from it, and lib/oauth/scope-checker.js decides from it what an
|
|
6
|
+
// application can do - the latter must not pull the Redis chain in to ask.
|
|
7
|
+
|
|
8
|
+
// The last path segment of a scope URL, which is the short name the scope presets on the OAuth2 app
|
|
9
|
+
// form write into skipScopes ("Mail.ReadWrite", "gmail.modify"). Derived from the scope's own prefix
|
|
10
|
+
// rather than compared against a list of hosts: the Outlook defaults are requested under
|
|
11
|
+
// graph.microsoft.com on the global cloud but under graph.microsoft.us, dod-graph.microsoft.us or
|
|
12
|
+
// microsoftgraph.chinacloudapi.cn on GCC High, DoD and China, and a host list that named only the
|
|
13
|
+
// global one left every default scope of such an application in place.
|
|
14
|
+
function shortScopeName(scope) {
|
|
15
|
+
const separator = scope.lastIndexOf('/');
|
|
16
|
+
return separator < 0 ? scope : scope.slice(separator + 1);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function formatExtraScopes(extraScopes, baseScopes, defaultScopesList, skipScopes, scopePrefix) {
|
|
20
|
+
let defaultScopes;
|
|
21
|
+
|
|
22
|
+
// An empty entry would match the short name of a scope URL ending in a slash
|
|
23
|
+
skipScopes = [].concat(skipScopes || []).filter(entry => entry);
|
|
24
|
+
|
|
25
|
+
if (Array.isArray(defaultScopesList)) {
|
|
26
|
+
defaultScopes = defaultScopesList;
|
|
27
|
+
} else {
|
|
28
|
+
defaultScopes = (baseScopes && defaultScopesList[baseScopes]) || defaultScopesList.imap;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (!extraScopes && !skipScopes.length) {
|
|
32
|
+
return defaultScopes;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
extraScopes = extraScopes || [];
|
|
36
|
+
|
|
37
|
+
let extras = [];
|
|
38
|
+
for (let extraScope of extraScopes) {
|
|
39
|
+
if (defaultScopes.includes(extraScope) || (scopePrefix && defaultScopes.includes(`${scopePrefix}/${extraScope}`))) {
|
|
40
|
+
// skip existing
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
extras.push(extraScope);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let result = extras.length ? extras.concat(defaultScopes) : defaultScopes;
|
|
47
|
+
|
|
48
|
+
if (skipScopes.length) {
|
|
49
|
+
result = result.filter(scope => !skipScopes.some(skipScope => scope === skipScope || shortScopeName(scope) === skipScope));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { shortScopeName, formatExtraScopes };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { fetch: fetchCmd } = require('undici');
|
|
4
|
+
const { httpAgent } = require('../tools');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Performs a token-endpoint request, and says which endpoint failed when the request never got there.
|
|
8
|
+
*
|
|
9
|
+
* A rejected response is already described in detail by each provider client (`ETokenRefresh`, the
|
|
10
|
+
* status, the parsed body). A request that never reaches the endpoint is not: undici rejects a failed
|
|
11
|
+
* fetch with a bare `fetch failed` whose own `code` is unset, the reason (ENOTFOUND, ECONNREFUSED,
|
|
12
|
+
* UND_ERR_CONNECT_TIMEOUT, a TLS failure) sitting on `err.cause`. Such a failure is correctly treated
|
|
13
|
+
* as transient - the account reports a connectError and keeps retrying rather than being parked - but
|
|
14
|
+
* the webhook then carried "fetch failed" and no serverResponseCode, which is indistinguishable from
|
|
15
|
+
* the mail server itself being unreachable. That is the one thing it is not.
|
|
16
|
+
*
|
|
17
|
+
* The error is ANNOTATED rather than replaced. Its code and cause are what isTransientNetworkError()
|
|
18
|
+
* reads (lib/email-client/credential-errors.js), and a token endpoint that could not be reached has
|
|
19
|
+
* not refused the refresh token: a replacement error carrying a code of its own would be read as an
|
|
20
|
+
* authentication failure and would park the account.
|
|
21
|
+
*
|
|
22
|
+
* @param {String} url - the token endpoint
|
|
23
|
+
* @param {Object} options - fetch options; the retrying dispatcher is applied here and cannot be overridden
|
|
24
|
+
* @param {Object} context - what to record about the attempt, as the rejected-response path records it.
|
|
25
|
+
* The method is read from `options`, so the two cannot disagree
|
|
26
|
+
* @returns {Promise<Response>} the response, whatever its status
|
|
27
|
+
*/
|
|
28
|
+
async function fetchTokenRequest(url, options, context) {
|
|
29
|
+
try {
|
|
30
|
+
// The dispatcher is applied last, so this helper really is the one place that decides it -
|
|
31
|
+
// with the default first, a caller that passed one would silently lose the retrying agent
|
|
32
|
+
return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.retry }));
|
|
33
|
+
} catch (err) {
|
|
34
|
+
// The cause carries the actionable code. Promoted onto the error itself so the connectError
|
|
35
|
+
// webhook has something to report - the transient check consults both, so no verdict changes.
|
|
36
|
+
if (!err.code && err.cause && err.cause.code) {
|
|
37
|
+
err.code = err.cause.code;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
err.tokenRequest = Object.assign({ url, method: (options && options.method) || 'get', error: err.message, errorCode: err.code }, context);
|
|
41
|
+
err.message = `Token request to ${url} failed${err.code ? ` [${err.code}]` : ''}: ${(err.cause && err.cause.message) || err.message}`;
|
|
42
|
+
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { fetchTokenRequest };
|