emailengine-app 2.77.0 → 2.78.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 (94) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/bin/emailengine.js +1 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +1 -1
  7. package/lib/account/expected-identity.js +88 -0
  8. package/lib/account.js +75 -26
  9. package/lib/api-reference/format.js +14 -0
  10. package/lib/api-reference/index.js +24 -7
  11. package/lib/api-reference/model.js +4 -2
  12. package/lib/api-routes/account-routes.js +19 -2
  13. package/lib/api-routes/behavior-notes.js +3 -0
  14. package/lib/append-list.js +3 -14
  15. package/lib/arf-detect.js +23 -1
  16. package/lib/autodetect-imap-settings.js +40 -16
  17. package/lib/base32.js +30 -0
  18. package/lib/bounce-detect.js +182 -62
  19. package/lib/egress-filter.js +89 -8
  20. package/lib/email-client/base-client.js +8 -72
  21. package/lib/email-client/gmail-client.js +3 -3
  22. package/lib/email-client/imap/listing-diff.js +3 -3
  23. package/lib/email-client/imap/mailbox.js +5 -69
  24. package/lib/email-client/imap-client.js +3 -2
  25. package/lib/email-client/message-builder.js +13 -13
  26. package/lib/email-client/outlook-client.js +1 -1
  27. package/lib/export.js +1 -1
  28. package/lib/gateway.js +1 -1
  29. package/lib/get-raw-email.js +1 -1
  30. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  31. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  32. package/lib/imapproxy/imap-server.js +13 -3
  33. package/lib/license-beacon.js +1 -1
  34. package/lib/llm-pre-process.js +1 -1
  35. package/lib/msgpack.js +62 -0
  36. package/lib/oauth/decode-jwt-payload.js +39 -0
  37. package/lib/oauth/outlook-identity.js +61 -0
  38. package/lib/oauth/retry-setup.js +38 -0
  39. package/lib/oauth2-apps.js +1 -1
  40. package/lib/outbox.js +66 -3
  41. package/lib/pre-process.js +1 -1
  42. package/lib/read-env-value.js +37 -0
  43. package/lib/schemas.js +12 -0
  44. package/lib/templates.js +1 -1
  45. package/lib/tokens.js +1 -1
  46. package/lib/tools.js +117 -48
  47. package/lib/totp.js +67 -0
  48. package/lib/ui-routes/account-routes.js +91 -15
  49. package/lib/ui-routes/admin-config-routes.js +2 -7
  50. package/lib/ui-routes/auth-routes.js +6 -24
  51. package/lib/ui-routes/reference-routes.js +8 -5
  52. package/lib/ui-routes/route-helpers.js +28 -0
  53. package/lib/utils/is-email.js +34 -0
  54. package/lib/utils/to-camel-case.js +17 -0
  55. package/lib/webhook-egress.js +37 -0
  56. package/lib/webhooks.js +1 -1
  57. package/package.json +22 -24
  58. package/sbom.json +1 -0
  59. package/server.js +1 -1
  60. package/static/css/flyonui.css +1 -1
  61. package/static/css/public.css +3 -0
  62. package/static/css/src/app.tailwind.css +23 -0
  63. package/static/js/app.js +69 -0
  64. package/static/js/reference.js +286 -1
  65. package/static/licenses.html +656 -1558
  66. package/translations/README.md +64 -0
  67. package/translations/de.mo +0 -0
  68. package/translations/de.po +164 -120
  69. package/translations/en.po +200 -161
  70. package/translations/et.mo +0 -0
  71. package/translations/et.po +163 -120
  72. package/translations/fr.mo +0 -0
  73. package/translations/fr.po +163 -120
  74. package/translations/ja.mo +0 -0
  75. package/translations/ja.po +163 -120
  76. package/translations/messages.pot +76 -46
  77. package/translations/nl.mo +0 -0
  78. package/translations/nl.po +164 -120
  79. package/translations/pl.mo +0 -0
  80. package/translations/pl.po +163 -120
  81. package/views/account-identity-error.hbs +34 -0
  82. package/views/accounts/edit.hbs +1 -0
  83. package/views/accounts/register/imap.hbs +12 -2
  84. package/views/layout/app.hbs +29 -5
  85. package/views/oauth-scope-error.hbs +1 -1
  86. package/views/partials/reference/nav.hbs +36 -9
  87. package/views/partials/reference/operation.hbs +1 -1
  88. package/views/partials/reference/schema-node.hbs +1 -1
  89. package/views/partials/reference/token-alert.hbs +35 -10
  90. package/views/reference/index.hbs +1 -1
  91. package/workers/api.js +157 -87
  92. package/workers/imap.js +1 -1
  93. package/workers/submit.js +1 -1
  94. package/workers/webhooks.js +2 -13
@@ -1,5 +1,5 @@
1
1
  <!DOCTYPE html>
2
- <html lang="en">
2
+ <html lang="en" class="ee-app-chrome">
3
3
 
4
4
  <head>
5
5
 
@@ -208,11 +208,35 @@
208
208
  level of the same menu rather than a panel floating in the page. A page
209
209
  opts in by setting `secondaryNav` to a partial name in its view context;
210
210
  every other page renders exactly as before.
211
- On small screens it becomes a bounded scroll strip above the content,
212
- because the sidebar drawer has no room for a second column. -->
213
- <aside class="bg-base-100 border-base-content/20 max-h-48 shrink-0 overflow-y-auto border-b lg:sticky lg:top-topbar lg:h-[calc(100vh-var(--spacing-topbar))] lg:max-h-none lg:w-64 lg:self-start lg:border-e lg:border-b-0"
211
+
212
+ Below lg there is no room for a second column, so the whole thing collapses
213
+ to the row below, closed by default. It used to be a 192px scroll strip
214
+ pinned above the content, which showed about a fifth of the list, hid the
215
+ rest behind a nested scrollbar most people never notice, and still pushed
216
+ the page heading off the first screen. A disclosure costs one row instead.
217
+ Opened, it is capped at the screen and scrolls itself - the difference from
218
+ what it replaced is that the space is asked for, not permanently taken, and
219
+ that the filter's 82 hits cannot push the page a thousand pixels down.
220
+
221
+ aria-expanded on the button is the only state there is: below lg the panel
222
+ derives its visibility from it, above lg it is a column regardless of what
223
+ the button last said. -->
224
+ <aside class="bg-base-100 border-base-content/20 shrink-0 border-b lg:sticky lg:top-topbar lg:h-[calc(100vh-var(--spacing-topbar))] lg:w-64 lg:overflow-y-auto lg:border-e lg:border-b-0"
214
225
  aria-label="Section navigation">
215
- {{> (lookup . "secondaryNav")}}
226
+
227
+ <button type="button" id="secondary-nav-toggle" aria-expanded="false" aria-controls="secondary-nav-panel"
228
+ class="peer group hover:bg-base-200 flex w-full cursor-pointer items-center justify-between gap-2 px-4 py-3 text-sm font-semibold lg:hidden">
229
+ <span class="flex items-center gap-2">
230
+ <span class="icon-[tabler--list-search] size-4 shrink-0"></span>
231
+ {{#if secondaryNavLabel}}{{secondaryNavLabel}}{{else}}Sections{{/if}}
232
+ </span>
233
+ <span class="icon-[tabler--chevron-down] size-4 shrink-0 transition-transform duration-200 group-aria-expanded:rotate-180"></span>
234
+ </button>
235
+
236
+ <div id="secondary-nav-panel"
237
+ class="border-base-content/10 hidden border-t max-lg:max-h-[calc(100dvh-var(--spacing-topbar))] max-lg:overflow-y-auto max-lg:overscroll-contain max-lg:peer-aria-expanded:block lg:block lg:border-t-0">
238
+ {{> (lookup . "secondaryNav")}}
239
+ </div>
216
240
  </aside>
217
241
  {{/if}}
218
242
 
@@ -24,7 +24,7 @@ permissions; offers a link to restart the consent flow. --}}
24
24
  </p>
25
25
 
26
26
  <div class="ee-form-actions">
27
- <a href="{{reAuthUrl}}" class="ee-btn ee-btn-primary ee-btn-block">
27
+ <a href="{{retryUrl}}" class="ee-btn ee-btn-primary ee-btn-block">
28
28
  <span class="ee-icon ee-icon-refresh"></span>{{_ "Try Again" templateLocale}}
29
29
  </a>
30
30
  </div>
@@ -18,7 +18,7 @@
18
18
  the endpoints that accept them, not only the ones with the word in their path.
19
19
 
20
20
  Params (from the reference view context):
21
- nav - tags with { name, slug, operationCount, active, operations[] }
21
+ nav - tags with { name, slug, url, operationCount, active, operations[] }
22
22
  searchIndex - flat operation list backing the filter
23
23
  --}}
24
24
  <div class="flex flex-col gap-3 p-3">
@@ -68,24 +68,51 @@
68
68
  <li id="ref-filter-empty" class="text-base-content/50 hidden px-2 py-2 text-xs">No matching endpoints</li>
69
69
  </ul>
70
70
 
71
+ {{!-- Every group carries its operations, so the list of a group you are not on can be
72
+ opened without loading its page. Below the layout's lg breakpoint the nav is a
73
+ disclosure, and there static/js/reference.js turns a tap on a group row into opening
74
+ that list instead of a page load - the chevron is the affordance for it. Which list
75
+ is open is aria-expanded on the group row and nothing else: the attribute is the
76
+ state, `max-lg:peer-aria-expanded:block` is the rendering.
77
+
78
+ As a column it is not a disclosure at all - the active group's list is shown by
79
+ lg:block and every other stays hidden, no matter what the reader last expanded on a
80
+ narrow window. Without that, widening after collapsing the active group would leave
81
+ the column with no list and no control to bring one back.
82
+
83
+ Not FlyonUI's collapse or accordion, though both are in the bundle: HSCollapse
84
+ animates an inline height that would fight lg:block (and strand a stale one when the
85
+ viewport crosses lg), HSAccordion needs a <button> where these rows have to stay
86
+ links above lg, and neither has any notion of a breakpoint - which is the whole
87
+ problem here. --}}
71
88
  <ul id="ref-tag-list" class="flex flex-col gap-0.5">
72
89
  {{#each nav}}
73
90
  <li>
74
- <a href="/admin/reference/{{slug}}"
75
- class="flex items-center justify-between gap-2 rounded-field px-2 py-1.5 text-sm{{#if active}} bg-primary/10 text-primary font-semibold{{else}} hover:bg-base-200{{/if}}">
91
+ <a href="{{url}}" aria-controls="ref-ops-{{slug}}" aria-expanded="{{#if active}}true{{else}}false{{/if}}"
92
+ class="peer group flex items-center justify-between gap-2 rounded-field px-2 py-1.5 text-sm{{#if active}} bg-primary/10 text-primary font-semibold{{else}} hover:bg-base-200{{/if}}">
76
93
  <span class="truncate">{{name}}</span>
77
- <span class="text-base-content/40 text-2xs">{{operationCount}}</span>
94
+ <span class="flex shrink-0 items-center gap-1">
95
+ <span class="text-base-content/40 text-2xs">{{operationCount}}</span>
96
+ <span
97
+ class="icon-[tabler--chevron-down] text-base-content/40 size-3.5 transition-transform duration-200 group-aria-expanded:rotate-180 lg:hidden"></span>
98
+ </span>
78
99
  </a>
79
- {{#if operations.length}}
80
- <ul class="border-base-content/10 my-1 ms-3 border-s ps-2">
100
+ {{!-- ee-ref-op-nav marks the ACTIVE group's list only: it is the hook static/js/
101
+ reference.js scroll-spies on, and only that list holds in-page anchors to mark.
102
+ The current-state styling is written as aria-[current] variants here rather than
103
+ a rule in app.tailwind.css because a components-layer rule loses to the
104
+ text-base-content/70 utility on this same element - utilities are emitted later,
105
+ so the colour would silently not apply. Same utilities as the active tag entry
106
+ above, so the two levels read as one marker. --}}
107
+ <ul id="ref-ops-{{slug}}"
108
+ class="{{#if active}}ee-ref-op-nav lg:block {{/if}}border-base-content/10 my-1 ms-3 hidden border-s ps-2 max-lg:peer-aria-expanded:block">
81
109
  {{#each operations}}
82
110
  <li>
83
- <a href="#{{id}}"
84
- class="text-base-content/70 hover:bg-base-200 hover:text-base-content block truncate rounded-field px-2 py-1 text-xs">{{summary}}</a>
111
+ <a href="{{url}}"
112
+ class="text-base-content/70 hover:bg-base-200 hover:text-base-content aria-[current=location]:bg-primary/10 aria-[current=location]:text-primary aria-[current=location]:font-semibold block truncate rounded-field px-2 py-1 text-xs">{{summary}}</a>
85
113
  </li>
86
114
  {{/each}}
87
115
  </ul>
88
- {{/if}}
89
116
  </li>
90
117
  {{/each}}
91
118
  </ul>
@@ -12,7 +12,7 @@
12
12
  neutralizes its own hash params inside the partial block, so the operation id is
13
13
  not reachable from there to compose them with.
14
14
  --}}
15
- <section id="{{id}}" class="ee-ref-op card bg-base-100 mb-6 scroll-mt-20 shadow-md">
15
+ <section id="{{id}}" class="ee-ref-op card bg-base-100 mb-6 shadow-md">
16
16
  <div class="card-body">
17
17
 
18
18
  <div class="flex flex-wrap items-center gap-2">
@@ -21,7 +21,7 @@
21
21
  descriptionHtml is pre-escaped by lib/api-reference/format.js (escape first, then a
22
22
  closed set of tags added back), which is why it renders unescaped.
23
23
  --}}
24
- <li class="ee-ref-prop min-w-0 scroll-mt-20"{{#if anchor}} id="{{anchor}}"{{/if}}>
24
+ <li class="ee-ref-prop min-w-0"{{#if anchor}} id="{{anchor}}"{{/if}}>
25
25
 
26
26
  <div class="ee-ref-prop-head flex flex-wrap items-baseline gap-x-2 gap-y-1">
27
27
  {{#if name}}<code class="text-sm font-semibold break-all">{{name}}</code>{{/if}}
@@ -3,22 +3,47 @@
3
3
  pages. Server-rendered but hidden by default; static/js/reference.js unhides it when
4
4
  the tab holds no token, because whether one is set is client state.
5
5
 
6
+ The banner sticks below the topbar instead of scrolling away, because the Try it panels
7
+ it warns about sit hundreds of pixels down a group page - a warning only visible at the
8
+ top of the page is read once and then gone. Sticky, not fixed: the band keeps its place
9
+ in normal flow, so at rest it pushes the page down instead of covering it, and it takes
10
+ the page background with it so operations passing underneath do not show through.
11
+ Nothing ends up permanently hidden behind it either - reference.js publishes the band's
12
+ measured height as --ee-sticky-band-h, and the layout's scroll-padding (.ee-app-chrome in
13
+ app.tailwind.css) adds it to the scroller's top inset, so anything scrolled into view -
14
+ a deep link, find-in-page, the focus moving through a Try it panel - lands below it.
15
+
6
16
  Rendered only when a token is actually required: with the `disableTokens` setting on,
7
17
  the API accepts uncredentialed callers, so the banner would be wrong.
8
18
 
9
19
  Not shown on the access-token page itself - the control is already there.
10
20
  --}}
11
21
  {{#unless disableTokens}}
12
- <div id="ref-token-alert" class="alert alert-soft alert-warning mb-6 hidden flex-wrap items-center gap-3" role="alert">
13
- <span class="icon-[tabler--key-off] size-5 shrink-0"></span>
14
- <div class="min-w-0 grow text-sm">
15
- No access token is set, so the <strong>Try it</strong> panels on this page will be rejected with a 401.
16
- </div>
17
- <div class="flex shrink-0 flex-wrap items-center gap-2">
18
- {{> ui/btn variant="primary" size="sm" icon="icon-[tabler--clock-plus]" label="Mint temporary token"
19
- class="ref-token-mint" id="" href="" style="" bare="" type="" overlay="" external=""}}
20
- {{> ui/btn href="/admin/reference/token" variant="neutral" style="soft" size="sm" label="Set a token" icon=""
21
- id="" bare="" type="" overlay="" external=""}}
22
+ {{!-- -mx-6/px-6 is the content column's own gutter (views/layout/app.hbs), cancelled out so
23
+ the opaque band reaches the column edges and nothing scrolls up beside it. The vertical
24
+ padding is the rest of that band: it keeps a strip of page background between the alert
25
+ and whatever is passing underneath, instead of content touching the alert's edge. Both
26
+ pairs cancel to the spacing this banner had before it became sticky. --}}
27
+ <div id="ref-token-alert" class="bg-base-200 @container sticky top-topbar z-20 -mx-6 -mt-2 mb-3 hidden px-6 pt-2 pb-3">
28
+ {{!-- One row wherever there is room for one: with wrapping on, flex breaks the line on the
29
+ text's full width, so the actions drop below it even where they would have fitted
30
+ beside a text column half as wide. Asked of the container rather than the viewport,
31
+ because the constraint is this column - at lg the sidebar and the section nav take
32
+ 544px out of the window, and a viewport breakpoint would unwrap the band exactly
33
+ where the column is at its narrowest, stacking the sentence seven lines high. 42rem
34
+ is where the text still fits two lines beside the actions: measured 84-94px for the
35
+ one-row form above it, against 168px for the wrapped form below it. --}}
36
+ <div class="alert alert-soft alert-warning flex flex-wrap items-center gap-3 @2xl:flex-nowrap" role="alert">
37
+ <span class="icon-[tabler--key-off] size-5 shrink-0"></span>
38
+ <div class="min-w-0 grow text-sm">
39
+ No access token is set, so <strong>Try it</strong> requests will be rejected with a 401.
40
+ </div>
41
+ <div class="flex shrink-0 flex-wrap items-center gap-2">
42
+ {{> ui/btn variant="primary" size="sm" icon="icon-[tabler--clock-plus]" label="Mint temporary token"
43
+ class="ref-token-mint" id="" href="" style="" bare="" type="" overlay="" external=""}}
44
+ {{> ui/btn href="/admin/reference/token" variant="neutral" style="soft" size="sm" label="Set a token"
45
+ icon="" id="" bare="" type="" overlay="" external=""}}
46
+ </div>
22
47
  </div>
23
48
  </div>
24
49
  {{/unless}}
@@ -57,7 +57,7 @@ subtitle="Every EmailEngine REST endpoint, generated from the same schemas the A
57
57
 
58
58
  <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
59
59
  {{#each tags}}
60
- <a href="/admin/reference/{{slug}}"
60
+ <a href="{{url}}"
61
61
  class="card bg-base-100 hover:border-primary/40 border border-transparent shadow-md transition-colors">
62
62
  <div class="card-body gap-1 p-4">
63
63
  <div class="flex items-baseline justify-between gap-2">
package/workers/api.js CHANGED
@@ -8,7 +8,7 @@ const logger = require('../lib/logger');
8
8
  const Path = require('path');
9
9
  const Gettext = require('@postalsys/gettext');
10
10
  const { loadTranslations, gt, joiLocales, locales } = require('../lib/translations');
11
- const { accountStateLabel, formatServerState } = require('../lib/ui-routes/route-helpers');
11
+ const { accountStateLabel, formatServerState, identityErrorView } = require('../lib/ui-routes/route-helpers');
12
12
  const util = require('util');
13
13
  const { webhooks: Webhooks } = require('../lib/webhooks');
14
14
  const featureFlags = require('../lib/feature-flags');
@@ -63,6 +63,10 @@ const pathlib = require('path');
63
63
  const crypto = require('crypto');
64
64
  const { registeredPublishers, openChangeStream } = require('../lib/response-stream');
65
65
  const { oauth2Apps } = require('../lib/oauth2-apps');
66
+ const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
67
+ const { resolveOutlookUserInfo } = require('../lib/oauth/outlook-identity');
68
+ const { buildRetrySetup } = require('../lib/oauth/retry-setup');
69
+ const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity } = require('../lib/account/expected-identity');
66
70
 
67
71
  const handlebars = require('handlebars');
68
72
  const AuthBearer = require('hapi-auth-bearer-token');
@@ -2056,6 +2060,18 @@ const init = async () => {
2056
2060
 
2057
2061
  const provider = accountData.oauth2.provider;
2058
2062
 
2063
+ // What the caller originally asked for, captured before the provider branches below rewrite
2064
+ // accountData from whoever signed in. A retry has to start from this rather than from the
2065
+ // rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
2066
+ // with the authenticated address), `name` gets filled in from the rejected user's profile when
2067
+ // the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
2068
+ // credential, so it must survive while the tokens do not.
2069
+ const requestedSetup = {
2070
+ email: accountData.email,
2071
+ name: accountData.name,
2072
+ delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
2073
+ };
2074
+
2059
2075
  const oauth2App = await oauth2Apps.get(provider);
2060
2076
  if (!oauth2App) {
2061
2077
  let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
@@ -2064,6 +2080,44 @@ const init = async () => {
2064
2080
 
2065
2081
  const oAuth2Client = await oauth2Apps.getClient(oauth2App.id);
2066
2082
 
2083
+ // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
2084
+ const renderRedirect = httpRedirectUrl =>
2085
+ h.view(
2086
+ 'redirect',
2087
+ {
2088
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2089
+ httpRedirectUrl
2090
+ },
2091
+ {
2092
+ layout: 'public'
2093
+ }
2094
+ );
2095
+
2096
+ // Hands the user back to the provider after a failure they can correct themselves, as a fresh
2097
+ // single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
2098
+ // _meta rides along so the redirect URL, the expected identity and the form nonce all survive
2099
+ // it - that nonce is claimed only on success, so it is still unspent here.
2100
+ const startOAuthRetry = async (loginHint, prompt) => {
2101
+ const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
2102
+ const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
2103
+
2104
+ await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2105
+
2106
+ // The address to steer the user towards rides on the authorize URL only - persisting it
2107
+ // would overwrite a shared mailbox with the principal that is signing in to reach it.
2108
+ return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
2109
+ };
2110
+
2111
+ // Addresses the provider itself returned over a back channel, the only values allowed to
2112
+ // satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
2113
+ // fills this in; one that does not leaves it empty, and an empty list fails the check closed.
2114
+ const providerIdentities = [];
2115
+
2116
+ // The token to revoke if the setup is rejected after the code was already exchanged, set by
2117
+ // each provider case because the token response is scoped to the switch. Prefer the refresh
2118
+ // token: revoking either invalidates the grant, but the access token may already be expired.
2119
+ let grantToken;
2120
+
2067
2121
  // `app.provider` is for example "gmail", `provider` is oauth2 app id
2068
2122
  switch (oauth2App.provider) {
2069
2123
  case 'gmail': {
@@ -2094,19 +2148,7 @@ const init = async () => {
2094
2148
  request.logger.error({ msg: 'Failed to revoke partial OAuth2 token', err });
2095
2149
  });
2096
2150
 
2097
- const reAuthNonce = crypto.randomBytes(NONCE_BYTES).toString('base64url');
2098
- const reAuthState = `account:add:${reAuthNonce}`;
2099
- const reAuthAccountData = Object.assign({}, accountData, {
2100
- oauth2: { provider },
2101
- _meta: accountMeta
2102
- });
2103
-
2104
- await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
2105
-
2106
- const reAuthUrl = oAuth2Client.generateAuthUrl({
2107
- state: reAuthState,
2108
- email: accountData.email
2109
- });
2151
+ const retryUrl = await startOAuthRetry(accountData.email);
2110
2152
 
2111
2153
  const missingScopesList = missingScopes.map(formatScopeDescription);
2112
2154
 
@@ -2115,7 +2157,7 @@ const init = async () => {
2115
2157
  {
2116
2158
  pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2117
2159
  templateLocale: request.app.locale,
2118
- reAuthUrl,
2160
+ retryUrl,
2119
2161
  missingScopesList
2120
2162
  },
2121
2163
  {
@@ -2130,20 +2172,14 @@ const init = async () => {
2130
2172
 
2131
2173
  // With OpenID Connect scopes (openid, email, profile), the ID token contains user info
2132
2174
  // This works for all account types including send-only accounts
2133
- if (r.id_token && typeof r.id_token === 'string') {
2134
- let [, encodedValue] = r.id_token.split('.');
2135
- if (encodedValue) {
2136
- try {
2137
- let decodedValue = JSON.parse(Buffer.from(encodedValue, 'base64url').toString());
2138
- if (decodedValue && typeof decodedValue.email === 'string' && isEmail(decodedValue.email)) {
2139
- userEmail = decodedValue.email;
2140
- userName = decodedValue.name || null;
2141
- request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2142
- }
2143
- } catch (err) {
2144
- request.logger.error({ msg: 'Failed to decode Gmail ID token', err });
2145
- }
2146
- }
2175
+ const idTokenPayload = decodeJwtPayload(r.id_token);
2176
+ if (r.id_token && !idTokenPayload) {
2177
+ request.logger.error({ msg: 'Failed to decode Gmail ID token' });
2178
+ }
2179
+ if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2180
+ userEmail = idTokenPayload.email;
2181
+ userName = idTokenPayload.name || null;
2182
+ request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2147
2183
  }
2148
2184
 
2149
2185
  // If ID token didn't provide email, fall back to Gmail API profile endpoint
@@ -2188,6 +2224,11 @@ const init = async () => {
2188
2224
  throw error;
2189
2225
  }
2190
2226
 
2227
+ // Back-channel only: either the id_token from the token endpoint or the Gmail profile
2228
+ // API response, never a value that travelled through the browser.
2229
+ providerIdentities.push(userEmail);
2230
+ grantToken = r.refresh_token || r.access_token;
2231
+
2191
2232
  accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
2192
2233
 
2193
2234
  const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
@@ -2222,43 +2263,31 @@ const init = async () => {
2222
2263
  throw error;
2223
2264
  }
2224
2265
 
2225
- let userInfo = {};
2266
+ let userInfo;
2226
2267
 
2227
2268
  if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
2228
- // Read account info from GET arguments
2229
- // This is needed because previously EmailEngine did not request for the User.Read scope
2230
-
2231
- let clientInfo = request.query.client_info ? JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString()) : false;
2269
+ // Read account info from the id_token, falling back to the client_info GET argument.
2270
+ // The fallback is needed because previously EmailEngine did not request for the
2271
+ // User.Read scope - but client_info arrives through the browser, so it is a display
2272
+ // fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
2232
2273
 
2233
- if (clientInfo && typeof clientInfo.name === 'string') {
2234
- userInfo.name = clientInfo.name;
2274
+ let clientInfo = false;
2275
+ if (request.query.client_info) {
2276
+ try {
2277
+ clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
2278
+ } catch (err) {
2279
+ // Base64-shaped but not JSON. It is an optional display hint, so log and continue
2280
+ // rather than failing the whole setup on a value we do not trust anyway.
2281
+ request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
2282
+ }
2235
2283
  }
2236
2284
 
2237
- if (clientInfo && clientInfo.preferred_username && isEmail(clientInfo.preferred_username)) {
2238
- userInfo.email = clientInfo.preferred_username;
2285
+ const idTokenPayload = decodeJwtPayload(r.id_token);
2286
+ if (r.id_token && !idTokenPayload) {
2287
+ request.logger.error({ msg: 'Failed to decode JWT payload' });
2239
2288
  }
2240
2289
 
2241
- if (r.id_token && typeof r.id_token === 'string') {
2242
- let [, encodedValue] = r.id_token.split('.');
2243
- if (encodedValue) {
2244
- try {
2245
- let decodedValue = JSON.parse(Buffer.from(encodedValue, 'base64url').toString());
2246
- if (decodedValue && typeof decodedValue.name === 'string') {
2247
- userInfo.name = decodedValue.name;
2248
- }
2249
-
2250
- if (decodedValue && typeof decodedValue.email === 'string' && isEmail(decodedValue.email)) {
2251
- userInfo.email = decodedValue.email;
2252
- }
2253
-
2254
- if (decodedValue && typeof decodedValue.preferred_username === 'string' && isEmail(decodedValue.preferred_username)) {
2255
- userInfo.username = decodedValue.preferred_username;
2256
- }
2257
- } catch (err) {
2258
- request.logger.error({ msg: 'Failed to decode JWT payload', err, encodedValue });
2259
- }
2260
- }
2261
- }
2290
+ userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
2262
2291
  } else {
2263
2292
  // Request profile info from API
2264
2293
 
@@ -2275,28 +2304,14 @@ const init = async () => {
2275
2304
  throw err;
2276
2305
  }
2277
2306
 
2307
+ userInfo = resolveOutlookUserInfo({ profile: profileRes });
2308
+
2278
2309
  request.logger.info({
2279
2310
  msg: 'User profile returned by MS Graph API',
2280
2311
  user: userInfo.email,
2281
2312
  provider: oauth2App.provider,
2282
2313
  profile: profileRes
2283
2314
  });
2284
-
2285
- if (profileRes.displayName) {
2286
- userInfo.name = profileRes.displayName;
2287
- }
2288
-
2289
- if (profileRes.mail) {
2290
- userInfo.email = profileRes.mail;
2291
- }
2292
-
2293
- if (profileRes.userPrincipalName) {
2294
- userInfo.username = profileRes.userPrincipalName;
2295
- }
2296
- }
2297
-
2298
- if (!userInfo.email && userInfo.username && isEmail(userInfo.username)) {
2299
- userInfo.email = userInfo.username;
2300
2315
  }
2301
2316
 
2302
2317
  const authData = {
@@ -2308,6 +2323,10 @@ const init = async () => {
2308
2323
  throw error;
2309
2324
  }
2310
2325
 
2326
+ // Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
2327
+ providerIdentities.push(...userInfo.verifiedIdentities);
2328
+ grantToken = r.refresh_token || r.access_token;
2329
+
2311
2330
  if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser) {
2312
2331
  // Delegated user (shared mailbox) specified in oauth2.auth.delegatedUser
2313
2332
  authData.delegatedUser = accountData.oauth2.auth.delegatedUser;
@@ -2369,6 +2388,10 @@ const init = async () => {
2369
2388
  throw error;
2370
2389
  }
2371
2390
 
2391
+ // Back-channel only: the Mail.ru userinfo endpoint response.
2392
+ providerIdentities.push(profileRes.email);
2393
+ grantToken = r.refresh_token || r.access_token;
2394
+
2372
2395
  accountData.name = accountData.name || profileRes.name || '';
2373
2396
  accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
2374
2397
 
@@ -2398,6 +2421,61 @@ const init = async () => {
2398
2421
  }
2399
2422
  }
2400
2423
 
2424
+ // Expected identity check. Runs before the nonce claim and before create(), so a rejected
2425
+ // setup neither consumes the signed link nor overwrites the credentials already on the
2426
+ // account. The expectation can come from the signed form blob or from the account itself -
2427
+ // persisting it is what makes the constraint outlive the link that introduced it, and it is
2428
+ // why a later link issued without expectedEmail cannot quietly drop the pin.
2429
+ const expectedEmail = await resolveExpectedIdentity(redis, {
2430
+ account: accountData.account,
2431
+ blobExpectation: pendingSetupExpectation(accountData, accountMeta)
2432
+ });
2433
+
2434
+ if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
2435
+ // Neither address is logged: the expectation and the authenticated identity both belong to
2436
+ // the end user, and this line is the one record of a failed attempt. Note the provider
2437
+ // identity was already logged by the "Provisioned OAuth2 tokens" line above.
2438
+ request.logger.warn({
2439
+ msg: 'OAuth2 identity did not match the expected email address',
2440
+ account: accountData.account,
2441
+ provider: oauth2App.provider
2442
+ });
2443
+
2444
+ // The code was already exchanged, so we are holding a refresh token we will never use.
2445
+ // Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
2446
+ // GmailOauth implements revokeToken, and a rejected setup must not become a 500.
2447
+ if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2448
+ try {
2449
+ await oAuth2Client.revokeToken(grantToken);
2450
+ } catch (err) {
2451
+ request.logger.error({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
2452
+ }
2453
+ }
2454
+
2455
+ // Stop here with a way back rather than redirecting to the calling application: signing in
2456
+ // as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
2457
+ // success. Hint the address they were supposed to use, and force the account picker:
2458
+ // they are already signed in to the one that just failed, so without select_account Google
2459
+ // would hand back the same account and the retry would loop. Microsoft always shows the
2460
+ // picker and Mail.ru ignores the hint, so this only changes Google's behavior.
2461
+ const retryUrl = await startOAuthRetry(expectedEmail, 'select_account consent');
2462
+
2463
+ return identityErrorView(request, h, {
2464
+ expectedEmail,
2465
+ // The primary address the provider reported. Microsoft can return both a mailbox
2466
+ // address and a user principal name, and either would have satisfied the pin, so
2467
+ // naming the first is enough to show which account actually signed in.
2468
+ actualEmail: providerIdentities[0],
2469
+ retryUrl
2470
+ });
2471
+ }
2472
+
2473
+ if (expectedEmail) {
2474
+ // Pin the account so every later setup is checked, including one driven by a link that
2475
+ // carries no expectation of its own.
2476
+ accountData.expectedEmail = expectedEmail;
2477
+ }
2478
+
2401
2479
  if ('delegated' in accountData) {
2402
2480
  // remove artefacts
2403
2481
  delete accountData.delegated;
@@ -2463,17 +2541,7 @@ const init = async () => {
2463
2541
  httpRedirectUrl = `/admin/accounts/${result.account}`;
2464
2542
  }
2465
2543
 
2466
- // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
2467
- return h.view(
2468
- 'redirect',
2469
- {
2470
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
2471
- httpRedirectUrl
2472
- },
2473
- {
2474
- layout: 'public'
2475
- }
2476
- );
2544
+ return renderRedirect(httpRedirectUrl);
2477
2545
  },
2478
2546
  options: {
2479
2547
  description: 'OAuth2 response endpoint',
@@ -2504,7 +2572,9 @@ const init = async () => {
2504
2572
  .description('OAuth2 scopes'),
2505
2573
  client_info: Joi.string()
2506
2574
  .empty('')
2507
- .max(1024 * 1024)
2575
+ // A few hundred bytes of JSON in practice. Bounded tightly because this is an
2576
+ // unauthenticated route and the value is JSON.parse-d.
2577
+ .max(4 * 1024)
2508
2578
  .base64({ urlSafe: true, paddingRequired: false })
2509
2579
  .description('Outlook client info'),
2510
2580
  error: Joi.string()
package/workers/imap.js CHANGED
@@ -23,7 +23,7 @@ const { MessagePortWritable, pipeToMessagePort } = require('../lib/message-port-
23
23
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
24
24
  const { getESClient } = require('../lib/document-store');
25
25
  const settings = require('../lib/settings');
26
- const msgpack = require('msgpack5')();
26
+ const msgpack = require('../lib/msgpack');
27
27
 
28
28
  const getSecret = require('../lib/get-secret');
29
29
 
package/workers/submit.js CHANGED
@@ -19,7 +19,7 @@ const { redis, queueConf, submitQueue } = require('../lib/db');
19
19
  const { Worker } = require('bullmq');
20
20
  const { Account } = require('../lib/account');
21
21
  const getSecret = require('../lib/get-secret');
22
- const msgpack = require('msgpack5')();
22
+ const msgpack = require('../lib/msgpack');
23
23
 
24
24
  const { EMAIL_FAILED_NOTIFY } = require('../lib/consts');
25
25
 
@@ -12,7 +12,7 @@ const { GooglePubSub } = require('../lib/oauth/pubsub/google');
12
12
 
13
13
  const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, maybeReloadHttpProxyAgent } = require('../lib/tools');
14
14
  const { sendWebhookRequest } = require('../lib/webhook-request');
15
- const { assertAllowedUrl, normalizePolicy, POLICY_OFF } = require('../lib/egress-filter');
15
+ const { validateWebhookTarget } = require('../lib/webhook-egress');
16
16
 
17
17
  const { initSentry } = require('../lib/sentry');
18
18
  initSentry('webhooks');
@@ -40,17 +40,6 @@ const NOTIFY_QC = (readEnvValue('EENGINE_NOTIFY_QC') && Number(readEnvValue('EEN
40
40
  // DEFAULT_WEBHOOK_REQUEST_TIMEOUT baked into sendWebhookRequest when unset
41
41
  const WEBHOOK_TIMEOUT = getDuration(readEnvValue('EENGINE_WEBHOOK_TIMEOUT')) || false;
42
42
 
43
- // Which destinations webhook deliveries may reach. An account-scoped API token can set both the
44
- // webhook URL and its custom headers, so without this the least-privileged credential in the
45
- // system can aim EmailEngine at anything its host can route to. Defaults to blocking the
46
- // link-local range (cloud instance metadata); `private` also blocks RFC1918 and friends, `off`
47
- // disables the check and restores redirect following. See lib/egress-filter.js
48
- const WEBHOOK_EGRESS_POLICY = normalizePolicy(readEnvValue('EENGINE_WEBHOOK_EGRESS_POLICY'));
49
-
50
- // Built once rather than per delivery. Null when the policy is off, which also restores fetch's
51
- // own redirect following in sendWebhookRequest().
52
- const validateWebhookTarget = WEBHOOK_EGRESS_POLICY === POLICY_OFF ? null : target => assertAllowedUrl(target, { policy: WEBHOOK_EGRESS_POLICY });
53
-
54
43
  let callQueue = new Map();
55
44
  let mids = 0;
56
45
 
@@ -424,7 +413,7 @@ const notifyWorker = new Worker(
424
413
  method: 'post',
425
414
  body,
426
415
  headers,
427
- dispatcher: httpAgent.retry,
416
+ dispatcher: httpAgent.webhook,
428
417
  timeout: WEBHOOK_TIMEOUT,
429
418
  validateTarget: validateWebhookTarget
430
419
  });