emailengine-app 2.79.0 → 2.79.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.
Files changed (50) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +39 -0
  3. package/lib/account.js +43 -2
  4. package/lib/api-routes/permission-map.js +4 -0
  5. package/lib/api-routes/route-helpers.js +71 -0
  6. package/lib/api-routes/settings-routes.js +37 -14
  7. package/lib/api-routes/token-routes.js +290 -122
  8. package/lib/arf-detect.js +17 -4
  9. package/lib/bounce-detect.js +28 -17
  10. package/lib/consts.js +6 -0
  11. package/lib/db.js +6 -0
  12. package/lib/email-client/gmail-client.js +4 -7
  13. package/lib/email-client/imap/mailbox.js +35 -35
  14. package/lib/email-client/imap-client.js +49 -2
  15. package/lib/email-client/outlook-client.js +3 -10
  16. package/lib/lua/h-set-new-mark.lua +36 -0
  17. package/lib/message-port-stream.js +84 -1
  18. package/lib/oauth2-apps.js +84 -15
  19. package/lib/openapi/build-document.js +5 -1
  20. package/lib/schemas.js +2 -2
  21. package/lib/settings.js +23 -9
  22. package/lib/token-audit-log.js +32 -9
  23. package/lib/tokens.js +163 -66
  24. package/lib/ui-routes/account-routes.js +13 -6
  25. package/lib/ui-routes/admin-entities-routes.js +52 -17
  26. package/lib/ui-routes/oauth-config-routes.js +7 -7
  27. package/lib/ui-routes/route-helpers.js +28 -1
  28. package/lib/ui-routes/suppression-list-routes.js +14 -9
  29. package/lib/utils/decode-headers.js +42 -0
  30. package/lib/utils/header-map.js +48 -0
  31. package/lib/utils/unsafe-key.js +59 -0
  32. package/lib/webhook-routing.js +6 -2
  33. package/lib/webhooks.js +28 -0
  34. package/package.json +1 -1
  35. package/server.js +39 -17
  36. package/views/accounts/account.hbs +8 -8
  37. package/views/accounts/browse.hbs +1 -1
  38. package/views/accounts/edit.hbs +2 -2
  39. package/views/gateways/edit.hbs +1 -1
  40. package/views/gateways/gateway.hbs +2 -2
  41. package/views/gateways/index.hbs +7 -7
  42. package/views/partials/accounts_table.hbs +7 -7
  43. package/views/suppression-lists/list.hbs +1 -1
  44. package/views/templates/index.hbs +2 -2
  45. package/views/templates/template.hbs +1 -1
  46. package/views/tokens/index.hbs +22 -2
  47. package/views/tokens/new.hbs +10 -3
  48. package/workers/api.js +41 -47
  49. package/workers/imap.js +65 -72
  50. package/workers/webhooks.js +21 -1
@@ -54,7 +54,7 @@ const tokenReferenceSchema = Joi.string()
54
54
  .length(64)
55
55
  .hex()
56
56
  .required()
57
- .example('123456')
57
+ .example('1bc12baf7f0d5e51fe0a4e0eda06e1be5b8d6cc2c66b95dc0fbe4d2e9f5d5e1a')
58
58
  .description('The access token value, or the token id from a listing')
59
59
  .label('TokenReference');
60
60
 
@@ -62,7 +62,7 @@ const tokenIdParamSchema = Joi.string()
62
62
  .length(64)
63
63
  .hex()
64
64
  .required()
65
- .example('123456')
65
+ .example('1bc12baf7f0d5e51fe0a4e0eda06e1be5b8d6cc2c66b95dc0fbe4d2e9f5d5e1a')
66
66
  .description('The token id, as reported by POST /v1/tokens and the token listing')
67
67
  .label('TokenIdParam');
68
68
 
@@ -112,56 +112,138 @@ const tokenListItemFields = {
112
112
  async function init(args) {
113
113
  const { server, call, CORS_CONFIG } = args;
114
114
 
115
- server.route({
116
- method: 'POST',
117
- path: '/v1/tokens',
115
+ // The provision and delete routes are registered twice - the current path and the
116
+ // deprecated pre-2.79 alias at the bottom of this file - so the handlers and the request/
117
+ // response schemas are shared. Sharing the schema INSTANCES matters beyond reuse: the
118
+ // OpenAPI generator names components after joi labels, and two different schema objects
119
+ // carrying the same label would come out numbered (CreateToken1).
120
+ const createTokenPayloadSchema = Joi.object({
121
+ account: accountIdSchema.description('Bind the token to one account. Omit for an instance-wide token, which then has to set `permissions`'),
122
+
123
+ description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
124
+
125
+ scopes: Joi.array()
126
+ .items(Joi.string().valid('api', 'smtp', 'imap-proxy').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
127
+ .single()
128
+ .default(['api'])
129
+ .required()
130
+ .description('Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication')
131
+ .label('Scopes'),
132
+
133
+ metadata: tokenMetadataSchema,
134
+
135
+ restrictions: tokenRestrictionsSchema,
136
+
137
+ // An unbound token reaches instance-wide endpoints and every account, so it may
138
+ // only be issued narrowed. A bound one is already limited to its account, so the
139
+ // narrowing stays optional there.
140
+ // `.invalid(null)` matters as much as `.required()`: tokenPermissionsSchema allows
141
+ // null so the admin form can post "not narrowed", and joi's required() is a
142
+ // presence check that an explicit null satisfies. Without this, sending
143
+ // `permissions: null` with no account - which any template rendering an unset
144
+ // variable produces - passed the rule and minted a full instance-wide token.
145
+ permissions: tokenPermissionsSchema.when('account', {
146
+ is: Joi.exist(),
147
+ otherwise: tokenPermissionsSchema.required().invalid(null).messages({
148
+ 'any.required': 'A token with no account must set permissions, so that an instance-wide credential is always a narrowed one',
149
+ 'any.invalid': 'A token with no account must set permissions, so that an instance-wide credential is always a narrowed one'
150
+ })
151
+ }),
152
+
153
+ // provision() has always accepted an expiry; the route did not, so until now the
154
+ // API could not mint a short-lived token at all. A narrow token that never
155
+ // expires is only half of what a per-task credential is for.
156
+ expires: Joi.date()
157
+ .iso()
158
+ .greater('now')
159
+ .example('2021-02-17T14:43:18.860Z')
160
+ .description('Optional time when this token stops working. Omit for a token that never expires')
161
+ // Distinct from the TokenExpires the listing uses: a joi label is a public
162
+ // type name in the generated document, so reusing it would collide and the
163
+ // generator would number one of them
164
+ .label('CreateTokenExpires'),
165
+
166
+ ip: ipSchema.description('IP address of the requester').label('TokenIP')
167
+ }).label('CreateToken');
168
+
169
+ const createTokenResponseSchema = Joi.object({
170
+ token: Joi.string()
171
+ .length(64)
172
+ .hex()
173
+ .required()
174
+ .example('9a6d24f8f43e01b1f2c4f11a5c5b8e51fe0a4e0eda06e1be5b8d6cc2c66b95dc')
175
+ .description('The access token. This is the only time it is returned - store it now'),
176
+ id: tokenIdSchema.required().description('Identifier for this token, as reported by the token listings')
177
+ }).label('CreateTokenResponse');
178
+
179
+ const deleteTokenParamsSchema = Joi.object({
180
+ token: tokenReferenceSchema
181
+ }).label('DeleteTokenRequest');
182
+
183
+ const deleteTokenResponseSchema = Joi.object({
184
+ deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the token deleted')
185
+ }).label('DeleteTokenRequestResponse');
186
+
187
+ const provisionTokenHandler = async request => {
188
+ let accountObject = new Account({
189
+ redis,
190
+ account: request.payload.account,
191
+ call,
192
+ secret: await getSecret(),
193
+ timeout: request.headers['x-ee-timeout']
194
+ });
118
195
 
119
- async handler(request) {
120
- let accountObject = new Account({
121
- redis,
122
- account: request.payload.account,
123
- call,
124
- secret: await getSecret(),
125
- timeout: request.headers['x-ee-timeout']
126
- });
196
+ try {
197
+ // Nothing invalidates an access token once it is minted, so a token handed to an
198
+ // anonymous caller keeps working indefinitely. This route normally requires a real
199
+ // credential (`auth: {strategy: 'api-token', mode: 'required'}`) and a caller
200
+ // presenting one is trusted, but the `disableTokens` setting rewrites a
201
+ // credential-less request to `access_token=preauth` and the strategy accepts it,
202
+ // marking the credentials `{preauth: true}`. That anonymous caller must never mint a
203
+ // lasting token - whether or not an admin password happens to be set - so refuse it
204
+ // here (headless provisioning uses the CLI or EENGINE_PREPARED_TOKEN, not this route).
205
+ if (request.auth.credentials?.preauth) {
206
+ throw Boom.forbidden('Can not provision an access token for an unauthenticated request');
207
+ }
127
208
 
128
- try {
129
- // Nothing invalidates an access token once it is minted, so a token handed to an
130
- // anonymous caller keeps working indefinitely. This route normally requires a real
131
- // credential (`auth: {strategy: 'api-token', mode: 'required'}`) and a caller
132
- // presenting one is trusted, but the `disableTokens` setting rewrites a
133
- // credential-less request to `access_token=preauth` and the strategy accepts it,
134
- // marking the credentials `{preauth: true}`. That anonymous caller must never mint a
135
- // lasting token - whether or not an admin password happens to be set - so refuse it
136
- // here (headless provisioning uses the CLI or EENGINE_PREPARED_TOKEN, not this route).
137
- if (request.auth.credentials?.preauth) {
138
- throw Boom.forbidden('Can not provision an access token for an unauthenticated request');
139
- }
209
+ // An account-bound token is validated against a real account; an instance-wide one has
210
+ // nothing to validate. The schema already refuses an unbound token that is not
211
+ // narrowed, so reaching here without an account means `permissions` is set.
212
+ //
213
+ // Safe because this route sits in the never-grantable `admin` group and has no
214
+ // `{account}` parameter, so an account-bound token is refused by the binding check and
215
+ // a narrowed one by the group check. The caller is therefore always a full-privilege
216
+ // root token, and every token it can mint here is strictly narrower than what it
217
+ // already holds.
218
+ if (request.payload.account) {
219
+ // throws if account does not exist
220
+ await accountObject.loadAccountData();
221
+ }
140
222
 
141
- // An account-bound token is validated against a real account; an instance-wide one has
142
- // nothing to validate. The schema already refuses an unbound token that is not
143
- // narrowed, so reaching here without an account means `permissions` is set.
144
- //
145
- // Safe because this route sits in the never-grantable `admin` group and has no
146
- // `{account}` parameter, so an account-bound token is refused by the binding check and
147
- // a narrowed one by the group check. The caller is therefore always a full-privilege
148
- // root token, and every token it can mint here is strictly narrower than what it
149
- // already holds.
150
- if (request.payload.account) {
151
- // throws if account does not exist
152
- await accountObject.loadAccountData();
153
- }
223
+ let token = await tokens.provision(Object.assign({}, request.payload, { remoteAddress: request.app.ip }));
154
224
 
155
- let token = await tokens.provision(Object.assign({}, request.payload, { remoteAddress: request.app.ip }));
225
+ // The id as well as the value: the value is never shown again and the listings report
226
+ // only the id, so returning the value alone left a caller unable to say which of its
227
+ // own tokens it had just created without hashing it themselves.
228
+ return { token, id: tokens.tokenId(token) };
229
+ } catch (err) {
230
+ handleError(request, err);
231
+ }
232
+ };
156
233
 
157
- // The id as well as the value: the value is never shown again and the listings report
158
- // only the id, so returning the value alone left a caller unable to say which of its
159
- // own tokens it had just created without hashing it themselves.
160
- return { token, id: tokens.tokenId(token) };
161
- } catch (err) {
162
- handleError(request, err);
163
- }
164
- },
234
+ const deleteTokenHandler = async request => {
235
+ try {
236
+ return { deleted: await tokens.delete(request.params.token, { remoteAddress: request.app.ip }) };
237
+ } catch (err) {
238
+ handleError(request, err);
239
+ }
240
+ };
241
+
242
+ server.route({
243
+ method: 'POST',
244
+ path: '/v1/tokens',
245
+
246
+ handler: provisionTokenHandler,
165
247
 
166
248
  options: {
167
249
  description: 'Provision an access token',
@@ -191,68 +273,11 @@ async function init(args) {
191
273
  },
192
274
  failAction,
193
275
 
194
- payload: Joi.object({
195
- account: accountIdSchema.description('Bind the token to one account. Omit for an instance-wide token, which then has to set `permissions`'),
196
-
197
- description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
198
-
199
- scopes: Joi.array()
200
- .items(Joi.string().valid('api', 'smtp', 'imap-proxy').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
201
- .single()
202
- .default(['api'])
203
- .required()
204
- .description(
205
- 'Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication'
206
- )
207
- .label('Scopes'),
208
-
209
- metadata: tokenMetadataSchema,
210
-
211
- restrictions: tokenRestrictionsSchema,
212
-
213
- // An unbound token reaches instance-wide endpoints and every account, so it may
214
- // only be issued narrowed. A bound one is already limited to its account, so the
215
- // narrowing stays optional there.
216
- // `.invalid(null)` matters as much as `.required()`: tokenPermissionsSchema allows
217
- // null so the admin form can post "not narrowed", and joi's required() is a
218
- // presence check that an explicit null satisfies. Without this, sending
219
- // `permissions: null` with no account - which any template rendering an unset
220
- // variable produces - passed the rule and minted a full instance-wide token.
221
- permissions: tokenPermissionsSchema.when('account', {
222
- is: Joi.exist(),
223
- otherwise: tokenPermissionsSchema.required().invalid(null).messages({
224
- 'any.required': 'A token with no account must set permissions, so that an instance-wide credential is always a narrowed one',
225
- 'any.invalid': 'A token with no account must set permissions, so that an instance-wide credential is always a narrowed one'
226
- })
227
- }),
228
-
229
- // provision() has always accepted an expiry; the route did not, so until now the
230
- // API could not mint a short-lived token at all. A narrow token that never
231
- // expires is only half of what a per-task credential is for.
232
- expires: Joi.date()
233
- .iso()
234
- .greater('now')
235
- .example('2021-02-17T14:43:18.860Z')
236
- .description('Optional time when this token stops working. Omit for a token that never expires')
237
- // Distinct from the TokenExpires the listing uses: a joi label is a public
238
- // type name in the generated document, so reusing it would collide and the
239
- // generator would number one of them
240
- .label('CreateTokenExpires'),
241
-
242
- ip: ipSchema.description('IP address of the requester').label('TokenIP')
243
- }).label('CreateToken')
276
+ payload: createTokenPayloadSchema
244
277
  },
245
278
 
246
279
  response: {
247
- schema: Joi.object({
248
- token: Joi.string()
249
- .length(64)
250
- .hex()
251
- .required()
252
- .example('123456')
253
- .description('The access token. This is the only time it is returned - store it now'),
254
- id: tokenIdSchema.required().description('Identifier for this token, as reported by the token listings')
255
- }).label('CreateTokenResponse'),
280
+ schema: createTokenResponseSchema,
256
281
  failAction: 'log'
257
282
  }
258
283
  }
@@ -262,13 +287,7 @@ async function init(args) {
262
287
  method: 'DELETE',
263
288
  path: '/v1/tokens/{token}',
264
289
 
265
- async handler(request) {
266
- try {
267
- return { deleted: await tokens.delete(request.params.token, { remoteAddress: request.app.ip }) };
268
- } catch (err) {
269
- handleError(request, err);
270
- }
271
- },
290
+ handler: deleteTokenHandler,
272
291
  options: {
273
292
  description: 'Remove a token',
274
293
  notes: 'Delete an access token',
@@ -295,15 +314,11 @@ async function init(args) {
295
314
  },
296
315
  failAction,
297
316
 
298
- params: Joi.object({
299
- token: tokenReferenceSchema
300
- }).label('DeleteTokenRequest')
317
+ params: deleteTokenParamsSchema
301
318
  },
302
319
 
303
320
  response: {
304
- schema: Joi.object({
305
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the token deleted')
306
- }).label('DeleteTokenRequestResponse'),
321
+ schema: deleteTokenResponseSchema,
307
322
  failAction: 'log'
308
323
  }
309
324
  }
@@ -538,9 +553,9 @@ async function init(args) {
538
553
  pageSize: Joi.number()
539
554
  .integer()
540
555
  .min(1)
541
- .max(tokenAuditLog.LOG_ENTRIES)
542
- .default(20)
543
- .example(20)
556
+ .max(tokenAuditLog.MAX_PAGE_SIZE)
557
+ .default(tokenAuditLog.DEFAULT_LOG_PAGE_SIZE)
558
+ .example(tokenAuditLog.DEFAULT_LOG_PAGE_SIZE)
544
559
  .description('How many entries per page')
545
560
  .label('PageSize')
546
561
  }).label('TokenLogQuery')
@@ -596,6 +611,159 @@ async function init(args) {
596
611
  }
597
612
  }
598
613
  });
614
+
615
+ // --------------------------------------------------------------------------------------------
616
+ // Deprecated aliases. v2.79.0 renamed the token endpoints (POST /v1/token -> POST /v1/tokens,
617
+ // DELETE /v1/token/{token} -> DELETE /v1/tokens/{token}) and folded the per-account listing
618
+ // into GET /v1/tokens?account=..., which handed every pre-2.79 integration that provisions,
619
+ // revokes or lists tokens a 404 from a minor upgrade - token-rotation pipelines failing
620
+ // first. The old paths stay registered against the same handlers and schema instances, but are
621
+ // left OUT of the published document and the API reference (plugins.openapi.deprecated - see
622
+ // lib/openapi/build-document.js): they exist for old integrations to keep working, and
623
+ // documenting them would steer new ones onto retired paths.
624
+
625
+ server.route({
626
+ method: 'POST',
627
+ path: '/v1/token',
628
+
629
+ handler: provisionTokenHandler,
630
+
631
+ options: {
632
+ description: 'Provision an access token (deprecated)',
633
+ notes: 'Deprecated alias of `POST /v1/tokens`, which behaves identically - use that path instead.',
634
+ tags: ['api', 'Access Tokens'],
635
+
636
+ plugins: {
637
+ openapi: {
638
+ deprecated: true,
639
+ responses: apiResponses('Returns the new token value. This is the only time it is shown - store it now.', 400, 401, 403, 404, 429, 500)
640
+ }
641
+ },
642
+
643
+ auth: {
644
+ strategy: 'api-token',
645
+ mode: 'required'
646
+ },
647
+ cors: CORS_CONFIG,
648
+
649
+ validate: {
650
+ options: {
651
+ stripUnknown: false,
652
+ abortEarly: false,
653
+ convert: true
654
+ },
655
+ failAction,
656
+
657
+ payload: createTokenPayloadSchema
658
+ },
659
+
660
+ response: {
661
+ schema: createTokenResponseSchema,
662
+ failAction: 'log'
663
+ }
664
+ }
665
+ });
666
+
667
+ server.route({
668
+ method: 'DELETE',
669
+ path: '/v1/token/{token}',
670
+
671
+ handler: deleteTokenHandler,
672
+ options: {
673
+ description: 'Remove a token (deprecated)',
674
+ notes: 'Deprecated alias of `DELETE /v1/tokens/{token}`, which behaves identically - use that path instead.',
675
+ tags: ['api', 'Access Tokens'],
676
+
677
+ plugins: {
678
+ openapi: {
679
+ deprecated: true,
680
+ 'x-ee-impact': IMPACT.DESTRUCTIVE,
681
+ responses: apiResponses('Returns a deletion marker. The token stops working immediately.', 400, 401, 403, 429, 500)
682
+ }
683
+ },
684
+
685
+ auth: {
686
+ strategy: 'api-token',
687
+ mode: 'required'
688
+ },
689
+ cors: CORS_CONFIG,
690
+
691
+ validate: {
692
+ options: {
693
+ stripUnknown: false,
694
+ abortEarly: false,
695
+ convert: true
696
+ },
697
+ failAction,
698
+
699
+ params: deleteTokenParamsSchema
700
+ },
701
+
702
+ response: {
703
+ schema: deleteTokenResponseSchema,
704
+ failAction: 'log'
705
+ }
706
+ }
707
+ });
708
+
709
+ server.route({
710
+ method: 'GET',
711
+ path: '/v1/tokens/account/{account}',
712
+
713
+ async handler(request) {
714
+ try {
715
+ // The pre-2.79 response shape: the account's tokens with no paging metadata
716
+ return { tokens: (await tokens.list(request.params.account, 0, 1000)).tokens };
717
+ } catch (err) {
718
+ handleError(request, err);
719
+ }
720
+ },
721
+
722
+ options: {
723
+ description: 'List account tokens (deprecated)',
724
+ notes: 'Deprecated alias for listing the access tokens of one account - use `GET /v1/tokens` with the `account` argument instead, which also pages the listing.',
725
+ tags: ['api', 'Access Tokens'],
726
+
727
+ plugins: {
728
+ openapi: {
729
+ deprecated: true,
730
+ responses: apiResponses('Returns the access tokens scoped to the account.', 400, 401, 403, 429, 500)
731
+ }
732
+ },
733
+
734
+ auth: {
735
+ strategy: 'api-token',
736
+ mode: 'required'
737
+ },
738
+ cors: CORS_CONFIG,
739
+
740
+ validate: {
741
+ options: {
742
+ stripUnknown: false,
743
+ abortEarly: false,
744
+ convert: true
745
+ },
746
+ failAction,
747
+ params: Joi.object({
748
+ account: accountIdSchema.required()
749
+ })
750
+ },
751
+
752
+ response: {
753
+ schema: Joi.object({
754
+ tokens: Joi.array()
755
+ .items(
756
+ Joi.object({
757
+ account: accountIdSchema.required(),
758
+ ...tokenListItemFields
759
+ }).label('AccountTokensItem')
760
+ )
761
+ .label('AccountTokensEntries')
762
+ }).label('AccountsTokensResponse'),
763
+ failAction: 'log'
764
+ }
765
+ }
766
+ });
599
767
  }
600
768
 
601
769
  module.exports = init;
package/lib/arf-detect.js CHANGED
@@ -3,6 +3,8 @@
3
3
  const libmime = require('libmime');
4
4
  const addressparser = require('nodemailer/lib/addressparser');
5
5
  const { toCamelCase } = require('./utils/to-camel-case');
6
+ const { decodeHeaders } = require('./utils/decode-headers');
7
+ const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
6
8
 
7
9
  const ARF_SINGLE = [
8
10
  'feedback-type',
@@ -33,7 +35,7 @@ const arfDetect = async messageInfo => {
33
35
  case 'message/feedback-report': {
34
36
  // found a feedback report
35
37
 
36
- const contents = libmime.decodeHeaders((attachment.content || '').toString());
38
+ const contents = decodeHeaders((attachment.content || '').toString());
37
39
 
38
40
  Object.keys(contents).forEach(key => {
39
41
  let value = contents[key];
@@ -88,7 +90,7 @@ const arfDetect = async messageInfo => {
88
90
  contents = contents.substr(0, headerPos.index);
89
91
  }
90
92
 
91
- const headers = libmime.decodeHeaders(contents);
93
+ const headers = decodeHeaders(contents);
92
94
 
93
95
  // Hotmail original recipient X-HmXmrOriginalRecipient
94
96
  const addresses = addressparser([].concat(headers['x-hmxmroriginalrecipient'] || []).join(', '))
@@ -110,7 +112,7 @@ const arfDetect = async messageInfo => {
110
112
  }
111
113
 
112
114
  let sourceIp = [].concat(headers['x-sender-ip'] || []).pop();
113
- if (sourceIp && !report['source-ip']) {
115
+ if (sourceIp && !report.arf['source-ip']) {
114
116
  report.arf['source-ip'] = sourceIp;
115
117
  }
116
118
 
@@ -211,10 +213,21 @@ function camelCaseComplaint(report) {
211
213
 
212
214
  for (let subKey of ['arf', 'headers']) {
213
215
  for (let key of Object.keys(report[subKey])) {
216
+ // decodeHeaders() dropped the prototype-shaped names at the parse boundary, but
217
+ // toCamelCase() re-creates one out of a name that boundary had no reason to refuse:
218
+ // "_-_proto__" camelCases into "__proto__" (a prototype swap) and "to-string" into
219
+ // "toString" (an own property shadowing the method), hence the transformed-key test
220
+ // covering every Object.prototype member. A feedback report is an attacker-supplied
221
+ // attachment, so the name is theirs to choose.
222
+ let displayKey = toCamelCase(key);
223
+ if (isUnsafeTransformedKey(displayKey)) {
224
+ continue;
225
+ }
226
+
214
227
  if (!complaint[subKey]) {
215
228
  complaint[subKey] = {};
216
229
  }
217
- complaint[subKey][toCamelCase(key)] = report[subKey][key];
230
+ complaint[subKey][displayKey] = report[subKey][key];
218
231
  }
219
232
  }
220
233
 
@@ -22,7 +22,9 @@
22
22
  * @requires mailparser - For parsing email messages
23
23
  */
24
24
 
25
- const libmime = require('libmime');
25
+ const { decodeHeaders } = require('./utils/decode-headers');
26
+ const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
27
+ const { pushHeaderValue } = require('./utils/header-map');
26
28
  const simpleParser = require('mailparser').simpleParser;
27
29
  const { toCamelCase } = require('./utils/to-camel-case');
28
30
 
@@ -45,7 +47,7 @@ function splitAddressType(value) {
45
47
  *
46
48
  * A DSN body is not a single header block. RFC 3464 splits it into a per-message block and a
47
49
  * separate per-recipient block for every reported address, with an empty line between them.
48
- * libmime.decodeHeaders() stops at the first empty line, as that is where a header block ends,
50
+ * decodeHeaders() stops at the first empty line, as that is where a header block ends,
49
51
  * so each block is decoded on its own.
50
52
  *
51
53
  * @param {string|Buffer} content - Raw message/delivery-status body
@@ -57,7 +59,7 @@ function decodeDeliveryStatusBlocks(content) {
57
59
  .toString()
58
60
  .replace(/\r\n|\r/g, '\n')
59
61
  .split(/\n{2,}/)
60
- .map(block => libmime.decodeHeaders(block))
62
+ .map(block => decodeHeaders(block))
61
63
  // A block of nothing but a continuation line decodes to a single empty key, which is
62
64
  // not a header and would otherwise be merged into the result
63
65
  .filter(entries => Object.keys(entries).some(key => key))
@@ -126,14 +128,23 @@ function parseDeliveryReport(content) {
126
128
  let structured = {};
127
129
 
128
130
  for (let key of Object.keys(entries)) {
129
- // The field names come from the message. "__proto__" names no DSN field, while assigning
130
- // it would hand the value to the Object.prototype setter and swap the report's prototype,
131
- // and defining it as an own property instead leaves a key msgpack refuses to decode
132
- if (!key || key === '__proto__') {
131
+ if (!key) {
133
132
  continue;
134
133
  }
135
134
 
135
+ // The field names come from the message. "__proto__" names no DSN field, while assigning
136
+ // it would hand the value to the Object.prototype setter and swap the report's prototype,
137
+ // and defining it as an own property instead leaves a key msgpack refuses to decode.
138
+ //
139
+ // Checked on the camelCased key rather than the raw name: decodeHeaders() already dropped
140
+ // the raw name at the parse boundary, but toCamelCase() re-creates it out of a name that
141
+ // boundary had no reason to refuse - "_-_proto__" camelCases straight into "__proto__",
142
+ // and "to-string" into "toString", which as an own property shadows the method on the
143
+ // published report - hence the transformed-key test covering every Object.prototype member.
136
144
  let displayKey = toCamelCase(key);
145
+ if (isUnsafeTransformedKey(displayKey)) {
146
+ continue;
147
+ }
137
148
  let value = entries[key].at(-1);
138
149
 
139
150
  if (typeof value !== 'string') {
@@ -247,7 +258,7 @@ function parseDeliveryStatus(content) {
247
258
  * Takes decoded entries rather than the raw attachment, as every caller has just decoded the
248
259
  * same content, most of them to keep as the reported message headers.
249
260
  *
250
- * @param {Object} entries - Header entries from libmime.decodeHeaders()
261
+ * @param {Object} entries - Header entries from decodeHeaders()
251
262
  * @returns {Object} Parsed header information
252
263
  * @returns {string} [returns.messageId] - The Message-ID header value
253
264
  */
@@ -359,7 +370,7 @@ async function bounceDetect(sourceStream) {
359
370
 
360
371
  // Process RFC822 headers attachment (contains headers of the original message)
361
372
  if (messageHeaders) {
362
- parsedMessageHeaders = libmime.decodeHeaders((messageHeaders.content || '').toString().trim());
373
+ parsedMessageHeaders = decodeHeaders((messageHeaders.content || '').toString().trim());
363
374
  result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
364
375
  }
365
376
 
@@ -374,11 +385,11 @@ async function bounceDetect(sourceStream) {
374
385
 
375
386
  if (parsedOriginal.headerLines && Array.isArray(parsedOriginal.headerLines)) {
376
387
  parsedOriginal.headerLines.forEach(entry => {
377
- if (!headers[entry.key]) {
378
- headers[entry.key] = [];
379
- }
380
- // Preserve the original header value (after the key and colon)
381
- headers[entry.key].push(entry.line.substring(entry.key.length + 1).trim());
388
+ // Preserve the original header value (after the key and colon).
389
+ // pushHeaderValue() skips names that resolve to an Object.prototype member,
390
+ // which a bare `!headers[key]` probe would have pushed onto, throwing out of
391
+ // the whole block and losing every header of the bounced message
392
+ pushHeaderValue(headers, entry.key, entry.line.substring(entry.key.length + 1).trim());
382
393
  });
383
394
  }
384
395
 
@@ -402,7 +413,7 @@ async function bounceDetect(sourceStream) {
402
413
  if (!messageHeaders) {
403
414
  messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
404
415
  if (messageHeaders) {
405
- let headerEntries = libmime.decodeHeaders((messageHeaders.content || '').toString().trim());
416
+ let headerEntries = decodeHeaders((messageHeaders.content || '').toString().trim());
406
417
  result = Object.assign(result, parseDeliveryHeaders(headerEntries));
407
418
  }
408
419
  }
@@ -459,7 +470,7 @@ async function bounceDetect(sourceStream) {
459
470
  // Additional validation: content should look like email headers
460
471
  // Check for common header patterns (Received:, Message-ID:, Date:, From:)
461
472
  if (/^\s*(Received|Message-ID|Date|From):/im.test(headerContent)) {
462
- let headers = libmime.decodeHeaders(headerContent);
473
+ let headers = decodeHeaders(headerContent);
463
474
  if (headers && headers['message-id']) {
464
475
  parsedMessageHeaders = headers;
465
476
  result = Object.assign(result, parseDeliveryHeaders(headers));
@@ -905,7 +916,7 @@ async function bounceDetect(sourceStream) {
905
916
  let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
906
917
  if (end) {
907
918
  let headers = text.substr(m.index, m[0].length + end.index).trim();
908
- let entries = libmime.decodeHeaders(headers);
919
+ let entries = decodeHeaders(headers);
909
920
  if (entries['message-id'] && entries['message-id'].length) {
910
921
  result.messageId = entries['message-id'][0].trim();
911
922
  // Only use these headers if we haven't found headers elsewhere