emailengine-app 2.77.0 → 2.79.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
@@ -6,9 +6,11 @@ const { redis } = require('../db');
6
6
  const { Account } = require('../account');
7
7
  const getSecret = require('../get-secret');
8
8
  const tokens = require('../tokens');
9
+ const tokenAuditLog = require('../token-audit-log');
9
10
  const { failAction } = require('../tools');
10
- const { handleError } = require('./route-helpers');
11
- const { accountIdSchema, tokenRestrictionsSchema, ipSchema, tokenIdSchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
11
+ const { handleError, throwNotFound } = require('./route-helpers');
12
+ const { accountIdSchema, tokenRestrictionsSchema, tokenPermissionsSchema, ipSchema, tokenIdSchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
13
+ const { IMPACT } = require('./operation-impact');
12
14
 
13
15
  const tokenAccessSchema = Joi.object({
14
16
  time: Joi.date().iso().allow(null).example('2021-02-17T13:43:18.860Z').description('Last time this token was used. Null if the token has never been used'),
@@ -41,6 +43,54 @@ const tokenMetadataSchema = Joi.string()
41
43
 
42
44
  // Both token listings (root and account) return the same item shape from tokens.list(),
43
45
  // the account listing just adds the account ID
46
+ // Either the plaintext value or the id a listing reports. Both are 64 hex characters, and both
47
+ // resolve to the same record - the value is the only one a caller still has right after creating a
48
+ // token, and the id is the only one available afterwards.
49
+ // DELETE resolves either the plaintext value or the id - it has done since before this, and the
50
+ // value is what a caller holds if it never recorded the id. The read routes take the id only: a
51
+ // token value in a URL path is written to the access log, and POST /v1/tokens returns the id, so
52
+ // there is no case that needs it.
53
+ const tokenReferenceSchema = Joi.string()
54
+ .length(64)
55
+ .hex()
56
+ .required()
57
+ .example('123456')
58
+ .description('The access token value, or the token id from a listing')
59
+ .label('TokenReference');
60
+
61
+ const tokenIdParamSchema = Joi.string()
62
+ .length(64)
63
+ .hex()
64
+ .required()
65
+ .example('123456')
66
+ .description('The token id, as reported by POST /v1/tokens and the token listing')
67
+ .label('TokenIdParam');
68
+
69
+ /**
70
+ * Resolves a token id to its record, or null when there is no such token.
71
+ *
72
+ * Only the two "there is no such token" outcomes become null. A blanket catch reported a Redis
73
+ * outage as a missing credential, which is the one answer an operator auditing a token must not be
74
+ * given: "this token does not exist" reads as a deletion that already happened.
75
+ *
76
+ * By id, never by the plaintext value. getRawData() would resolve either, but a token value in a URL
77
+ * path lands in the access log and in every reverse proxy in front of it - and nothing needs it
78
+ * here, since POST /v1/tokens returns the id.
79
+ *
80
+ * `allowExpired` because an expired token must still be inspectable: it is exactly the record
81
+ * someone reads to find out why a credential stopped working.
82
+ */
83
+ async function loadTokenById(tokenId) {
84
+ try {
85
+ return await tokens.get(tokenId, true, { allowExpired: true });
86
+ } catch (err) {
87
+ if (err.code === 'UnknownToken' || err.code === 'InvalidToken') {
88
+ return null;
89
+ }
90
+ throw err;
91
+ }
92
+ }
93
+
44
94
  const tokenListItemFields = {
45
95
  description: Joi.string().empty('').trim().max(1024).example('Token description').description('Token description'),
46
96
  metadata: tokenMetadataSchema,
@@ -48,6 +98,7 @@ const tokenListItemFields = {
48
98
  remoteAddress: ipSchema.description('IP address of the client that created the token').label('TokenRemoteAddress'),
49
99
  scopes: tokenScopesSchema,
50
100
  restrictions: tokenRestrictionsSchema,
101
+ permissions: tokenPermissionsSchema,
51
102
  created: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('The time this token was created'),
52
103
  expires: Joi.date()
53
104
  .iso()
@@ -63,7 +114,7 @@ async function init(args) {
63
114
 
64
115
  server.route({
65
116
  method: 'POST',
66
- path: '/v1/token',
117
+ path: '/v1/tokens',
67
118
 
68
119
  async handler(request) {
69
120
  let accountObject = new Account({
@@ -87,12 +138,26 @@ async function init(args) {
87
138
  throw Boom.forbidden('Can not provision an access token for an unauthenticated request');
88
139
  }
89
140
 
90
- // throws if account does not exist
91
- await accountObject.loadAccountData();
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
+ }
92
154
 
93
155
  let token = await tokens.provision(Object.assign({}, request.payload, { remoteAddress: request.app.ip }));
94
156
 
95
- return { token };
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) };
96
161
  } catch (err) {
97
162
  handleError(request, err);
98
163
  }
@@ -100,7 +165,10 @@ async function init(args) {
100
165
 
101
166
  options: {
102
167
  description: 'Provision an access token',
103
- notes: 'Provisions a new access token for an account',
168
+ // The conditional requirement is stated here because the schema cannot carry it: a flat
169
+ // `required` array has no way to say "unless `account` is set", and marking `permissions`
170
+ // required outright would describe the ordinary account-bound mint as invalid.
171
+ notes: 'Provisions a new access token. Either bind it to an account, or set `permissions` - an instance-wide token that is not narrowed reaches every account and every endpoint, so the API declines to mint one.',
104
172
  tags: ['api', 'Access Tokens'],
105
173
 
106
174
  plugins: {
@@ -124,7 +192,7 @@ async function init(args) {
124
192
  failAction,
125
193
 
126
194
  payload: Joi.object({
127
- account: accountIdSchema.required(),
195
+ account: accountIdSchema.description('Bind the token to one account. Omit for an instance-wide token, which then has to set `permissions`'),
128
196
 
129
197
  description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
130
198
 
@@ -142,13 +210,48 @@ async function init(args) {
142
210
 
143
211
  restrictions: tokenRestrictionsSchema,
144
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
+
145
242
  ip: ipSchema.description('IP address of the requester').label('TokenIP')
146
243
  }).label('CreateToken')
147
244
  },
148
245
 
149
246
  response: {
150
247
  schema: Joi.object({
151
- token: Joi.string().length(64).hex().required().example('123456').description('Access token')
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')
152
255
  }).label('CreateTokenResponse'),
153
256
  failAction: 'log'
154
257
  }
@@ -157,7 +260,7 @@ async function init(args) {
157
260
 
158
261
  server.route({
159
262
  method: 'DELETE',
160
- path: '/v1/token/{token}',
263
+ path: '/v1/tokens/{token}',
161
264
 
162
265
  async handler(request) {
163
266
  try {
@@ -173,6 +276,7 @@ async function init(args) {
173
276
 
174
277
  plugins: {
175
278
  openapi: {
279
+ 'x-ee-impact': IMPACT.DESTRUCTIVE,
176
280
  responses: apiResponses('Returns a deletion marker. The token stops working immediately.', 400, 401, 403, 429, 500)
177
281
  }
178
282
  },
@@ -192,7 +296,7 @@ async function init(args) {
192
296
  failAction,
193
297
 
194
298
  params: Joi.object({
195
- token: Joi.string().length(64).hex().required().example('123456').description('Access token')
299
+ token: tokenReferenceSchema
196
300
  }).label('DeleteTokenRequest')
197
301
  },
198
302
 
@@ -211,21 +315,30 @@ async function init(args) {
211
315
 
212
316
  async handler(request) {
213
317
  try {
214
- // TODO: allow paging
215
- return { tokens: (await tokens.list(null, 0, 1000)).tokens };
318
+ // Every token by default, not just the unbound ones. "Which credentials exist on
319
+ // this instance" was previously unanswerable in one call: root tokens and each
320
+ // account's tokens lived behind separate endpoints, so an audit meant one request
321
+ // per account. `account` narrows it to one account when that is what you want.
322
+ //
323
+ // `total` and `pages` come back too: without them a caller could not tell a complete
324
+ // listing from a truncated one, which is what the previous hardcoded cap of 1000
325
+ // silently produced.
326
+ return await tokens.list(request.query.account, request.query.page, request.query.pageSize, request.query.query, {
327
+ all: !request.query.account
328
+ });
216
329
  } catch (err) {
217
330
  handleError(request, err);
218
331
  }
219
332
  },
220
333
 
221
334
  options: {
222
- description: 'List root tokens',
223
- notes: 'Lists access tokens registered for root access',
335
+ description: 'List access tokens',
336
+ notes: 'Lists access tokens. Returns every token on the instance unless narrowed with the account argument. Token values are never returned - only the id each token is listed under.',
224
337
  tags: ['api', 'Access Tokens'],
225
338
 
226
339
  plugins: {
227
340
  openapi: {
228
- responses: apiResponses('Returns the root access tokens. Token values are never returned after creation.', 401, 403, 429, 500)
341
+ responses: apiResponses('Returns the matching access tokens. Token values are never returned after creation.', 400, 401, 403, 429, 500)
229
342
  }
230
343
  },
231
344
 
@@ -241,13 +354,46 @@ async function init(args) {
241
354
  abortEarly: false,
242
355
  convert: true
243
356
  },
244
- failAction
357
+ failAction,
358
+
359
+ query: Joi.object({
360
+ page: Joi.number()
361
+ .integer()
362
+ .min(0)
363
+ .max(1024 * 1024)
364
+ .default(0)
365
+ .example(0)
366
+ .description('Page number (zero indexed, so use 0 for first page)')
367
+ .label('PageNumber'),
368
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
369
+ query: Joi.string()
370
+ .empty('')
371
+ .trim()
372
+ .max(1024)
373
+ .example('agent')
374
+ .description('Filter by description, id or account')
375
+ .label('TokenSearchQuery'),
376
+ account: accountIdSchema.description('Only list tokens bound to this account. Omit to list every token on the instance')
377
+ }).label('TokensQuery')
245
378
  },
246
379
 
247
380
  response: {
248
381
  schema: Joi.object({
249
- tokens: Joi.array().items(Joi.object(tokenListItemFields).label('RootTokensItem')).label('RootTokensEntries')
250
- }).label('RootTokensResponse'),
382
+ account: accountIdSchema.allow(null).description('The account filter that was applied, or null when every token was listed'),
383
+ total: Joi.number().integer().example(12).description('How many tokens match'),
384
+ page: Joi.number().integer().example(0).description('Current page (zero indexed)'),
385
+ pages: Joi.number().integer().example(1).description('Total page count'),
386
+ tokens: Joi.array()
387
+ .items(
388
+ Joi.object({
389
+ // Null for an instance-wide token. Always present, so a client has
390
+ // one type for a token rather than one per listing.
391
+ account: accountIdSchema.allow(null).description('Account this token is bound to, or null for an instance-wide token'),
392
+ ...tokenListItemFields
393
+ }).label('TokensItem')
394
+ )
395
+ .label('TokensEntries')
396
+ }).label('TokensResponse'),
251
397
  failAction: 'log'
252
398
  }
253
399
  }
@@ -255,25 +401,52 @@ async function init(args) {
255
401
 
256
402
  server.route({
257
403
  method: 'GET',
258
- path: '/v1/tokens/account/{account}',
404
+ path: '/v1/tokens/{token}',
259
405
 
260
406
  async handler(request) {
261
407
  try {
262
- // TODO: allow paging
263
- return { tokens: (await tokens.list(request.params.account, 0, 1000)).tokens };
408
+ // Both reads at once: the last-use record is keyed by the id the path already
409
+ // carries, so it never needed the record resolved first. tokens.list() puts the
410
+ // same pair in one multi() for every token it lists.
411
+ const [tokenData, access] = await Promise.all([loadTokenById(request.params.token), tokens.getAccess(request.params.token)]);
412
+ if (!tokenData) {
413
+ throwNotFound('Requested access token was not found');
414
+ }
415
+
416
+ // Same shape as an entry in the listings, so a client has one type for a token
417
+ // however it obtained it. `access` lives in a second hash, which is why it is
418
+ // fetched here rather than arriving with the record - leaving it out made the one
419
+ // endpoint that describes a single credential the one that could not say when it
420
+ // was last used.
421
+ const { id, account, description, metadata, ip, remoteAddress, scopes, restrictions, permissions, created, expires } = tokenData;
422
+
423
+ return {
424
+ id,
425
+ account: account || null,
426
+ description,
427
+ metadata,
428
+ ip,
429
+ remoteAddress,
430
+ scopes,
431
+ restrictions,
432
+ permissions,
433
+ created,
434
+ expires: expires ? new Date(expires) : undefined,
435
+ access
436
+ };
264
437
  } catch (err) {
265
438
  handleError(request, err);
266
439
  }
267
440
  },
268
441
 
269
442
  options: {
270
- description: 'List account tokens',
271
- notes: 'Lists access tokens registered for an account',
443
+ description: 'Get token info',
444
+ notes: 'Returns stored information about a single access token. The token value itself is never returned - it is only shown once, when the token is created.',
272
445
  tags: ['api', 'Access Tokens'],
273
446
 
274
447
  plugins: {
275
448
  openapi: {
276
- responses: apiResponses('Returns the access tokens scoped to the account.', 400, 401, 403, 429, 500)
449
+ responses: apiResponses('Returns the stored token record. The token value is not included.', 400, 401, 403, 404, 429, 500)
277
450
  }
278
451
  },
279
452
 
@@ -290,22 +463,135 @@ async function init(args) {
290
463
  convert: true
291
464
  },
292
465
  failAction,
466
+
293
467
  params: Joi.object({
294
- account: accountIdSchema.required()
295
- })
468
+ token: tokenIdParamSchema
469
+ }).label('GetTokenRequest')
296
470
  },
297
471
 
298
472
  response: {
299
473
  schema: Joi.object({
300
- tokens: Joi.array()
474
+ account: accountIdSchema.allow(null).description('Account this token is bound to, or null for an instance-wide token'),
475
+ ...tokenListItemFields
476
+ }).label('TokenResponse'),
477
+ failAction: 'log'
478
+ }
479
+ }
480
+ });
481
+
482
+ server.route({
483
+ method: 'GET',
484
+ path: '/v1/tokens/{token}/log',
485
+
486
+ async handler(request) {
487
+ try {
488
+ const tokenData = await loadTokenById(request.params.token);
489
+ if (!tokenData) {
490
+ throwNotFound('Requested access token was not found');
491
+ }
492
+
493
+ return Object.assign({ token: tokenData.id }, await tokenAuditLog.list(tokenData.id, request.query));
494
+ } catch (err) {
495
+ handleError(request, err);
496
+ }
497
+ },
498
+
499
+ options: {
500
+ description: 'Get token audit log',
501
+ notes: 'Lists recent requests made with an access token, newest first. Requires the tokenAuditLog setting to be enabled; it is off by default, and entries only exist from the point it was switched on.',
502
+ tags: ['api', 'Access Tokens'],
503
+
504
+ plugins: {
505
+ openapi: {
506
+ 'x-ee-impact': IMPACT.READONLY,
507
+ responses: apiResponses('Returns the recorded requests for this token, newest first.', 400, 401, 403, 404, 429, 500)
508
+ }
509
+ },
510
+
511
+ auth: {
512
+ strategy: 'api-token',
513
+ mode: 'required'
514
+ },
515
+ cors: CORS_CONFIG,
516
+
517
+ validate: {
518
+ options: {
519
+ stripUnknown: false,
520
+ abortEarly: false,
521
+ convert: true
522
+ },
523
+ failAction,
524
+
525
+ params: Joi.object({
526
+ token: tokenIdParamSchema
527
+ }).label('TokenLogRequest'),
528
+
529
+ query: Joi.object({
530
+ page: Joi.number()
531
+ .integer()
532
+ .min(0)
533
+ .max(1024 * 1024)
534
+ .default(0)
535
+ .example(0)
536
+ .description('Page number (zero indexed, so use 0 for first page)')
537
+ .label('PageNumber'),
538
+ pageSize: Joi.number()
539
+ .integer()
540
+ .min(1)
541
+ .max(tokenAuditLog.LOG_ENTRIES)
542
+ .default(20)
543
+ .example(20)
544
+ .description('How many entries per page')
545
+ .label('PageSize')
546
+ }).label('TokenLogQuery')
547
+ },
548
+
549
+ response: {
550
+ schema: Joi.object({
551
+ token: tokenIdSchema,
552
+ total: Joi.number().integer().example(120).description('How many entries are stored for this token'),
553
+ page: Joi.number().integer().example(0).description('Current page (zero indexed)'),
554
+ pages: Joi.number().integer().example(6).description('Total page count'),
555
+ entries: Joi.array()
301
556
  .items(
302
557
  Joi.object({
303
- account: accountIdSchema.required(),
304
- ...tokenListItemFields
305
- }).label('AccountTokensItem')
558
+ time: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('When the request was made').label('TokenLogTime'),
559
+ ip: ipSchema.allow(null).description('Address the request came from').label('TokenLogIP'),
560
+ method: Joi.string()
561
+ .allow(null)
562
+ .example('get')
563
+ .description('HTTP method, or the surface name for SMTP and the IMAP proxy')
564
+ .label('TokenLogMethod'),
565
+ path: Joi.string()
566
+ .allow(null)
567
+ .example('/v1/account/{account}/messages')
568
+ .description('Route that was called')
569
+ .label('TokenLogPath'),
570
+ action: Joi.string()
571
+ .allow(null)
572
+ .example('read')
573
+ .description('Permission action the operation required')
574
+ .label('TokenLogAction'),
575
+ group: Joi.string()
576
+ .allow(null)
577
+ .example('message')
578
+ .description('Permission group the operation belongs to')
579
+ .label('TokenLogGroup'),
580
+ account: accountIdSchema.allow(null).description('Account the request addressed').label('TokenLogAccount'),
581
+ status: Joi.string()
582
+ .valid('allowed', 'denied')
583
+ .example('allowed')
584
+ .description('Whether the request was served')
585
+ .label('TokenLogStatus'),
586
+ reason: Joi.string()
587
+ .allow(null)
588
+ .example('group')
589
+ .description('Why it was refused. Null when it was allowed')
590
+ .label('TokenLogReason')
591
+ }).label('TokenLogEntry')
306
592
  )
307
- .label('AccountTokensEntries')
308
- }).label('AccountsTokensResponse'),
593
+ .label('TokenLogEntries')
594
+ }).label('TokenLogResponse'),
309
595
  failAction: 'log'
310
596
  }
311
597
  }
@@ -3,7 +3,7 @@
3
3
  const Joi = require('joi');
4
4
  const { webhooks: Webhooks } = require('../webhooks');
5
5
  const { failAction } = require('../tools');
6
- const { handleError, throwNotFound } = require('./route-helpers');
6
+ const { handleError, throwNotFound, maskSecrets, MASK_NOTE } = require('./route-helpers');
7
7
  const { settingsSchema, apiResponses } = require('../schemas');
8
8
 
9
9
  const webhookErrorFlagSchema = Joi.object({
@@ -27,7 +27,16 @@ async function init(args) {
27
27
 
28
28
  async handler(request) {
29
29
  try {
30
- return await Webhooks.list(request.query.page, request.query.pageSize);
30
+ const listing = await Webhooks.list(request.query.page, request.query.pageSize);
31
+
32
+ // customHeaders and the target URL both carry credentials for the customer's own
33
+ // receiver, so a reader of this listing could otherwise post forged, correctly
34
+ // authenticated webhooks into it
35
+ for (const entry of listing.webhooks || []) {
36
+ maskSecrets(entry);
37
+ }
38
+
39
+ return listing;
31
40
  } catch (err) {
32
41
  handleError(request, err);
33
42
  }
@@ -35,7 +44,7 @@ async function init(args) {
35
44
 
36
45
  options: {
37
46
  description: 'List webhook routes',
38
- notes: 'List custom webhook routes',
47
+ notes: `List custom webhook routes. ${MASK_NOTE}`,
39
48
  tags: ['api', 'Webhooks'],
40
49
 
41
50
  plugins: {
@@ -114,6 +123,7 @@ async function init(args) {
114
123
  if (!webhookRouteData) {
115
124
  throwNotFound();
116
125
  }
126
+ maskSecrets(webhookRouteData);
117
127
  return webhookRouteData;
118
128
  } catch (err) {
119
129
  handleError(request, err);
@@ -122,7 +132,7 @@ async function init(args) {
122
132
 
123
133
  options: {
124
134
  description: 'Get webhook route information',
125
- notes: 'Retrieve webhook route content and information',
135
+ notes: `Retrieve webhook route content and information. ${MASK_NOTE}`,
126
136
  tags: ['api', 'Webhooks'],
127
137
 
128
138
  plugins: {
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const msgpack = require('msgpack5')();
3
+ const msgpack = require('./msgpack');
4
4
 
5
5
  /**
6
6
  * Pushes an object to the end of a list where that list is stored in a hash field
@@ -43,19 +43,8 @@ async function list(redis, list, key) {
43
43
  return [];
44
44
  }
45
45
 
46
- return new Promise((resolve, reject) => {
47
- let decoder = msgpack.decoder({});
48
- let list = [];
49
- decoder.on('readable', () => {
50
- let data;
51
- while ((data = decoder.read()) !== null) {
52
- list.push(data);
53
- }
54
- });
55
- decoder.on('end', () => resolve(list));
56
- decoder.on('error', err => reject(err));
57
- decoder.end(contents);
58
- });
46
+ // the hash field holds a byte stream of concatenated msgpack values
47
+ return msgpack.decodeMulti(contents);
59
48
  }
60
49
 
61
50
  /**
package/lib/arf-detect.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  const libmime = require('libmime');
4
4
  const addressparser = require('nodemailer/lib/addressparser');
5
+ const { toCamelCase } = require('./utils/to-camel-case');
5
6
 
6
7
  const ARF_SINGLE = [
7
8
  'feedback-type',
@@ -199,4 +200,25 @@ const arfDetect = async messageInfo => {
199
200
  return report;
200
201
  };
201
202
 
202
- module.exports = { arfDetect };
203
+ /**
204
+ * Turns an ARF report into the camelCased shape published in a complaint notification
205
+ *
206
+ * @param {Object} report - Report from arfDetect()
207
+ * @returns {Object} The arf and headers sections with camelCased keys
208
+ */
209
+ function camelCaseComplaint(report) {
210
+ let complaint = {};
211
+
212
+ for (let subKey of ['arf', 'headers']) {
213
+ for (let key of Object.keys(report[subKey])) {
214
+ if (!complaint[subKey]) {
215
+ complaint[subKey] = {};
216
+ }
217
+ complaint[subKey][toCamelCase(key)] = report[subKey][key];
218
+ }
219
+ }
220
+
221
+ return complaint;
222
+ }
223
+
224
+ module.exports = { arfDetect, camelCaseComplaint };