emailengine-app 2.78.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 (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +112 -36
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. 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('1bc12baf7f0d5e51fe0a4e0eda06e1be5b8d6cc2c66b95dc0fbe4d2e9f5d5e1a')
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('1bc12baf7f0d5e51fe0a4e0eda06e1be5b8d6cc2c66b95dc0fbe4d2e9f5d5e1a')
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()
@@ -61,51 +112,191 @@ const tokenListItemFields = {
61
112
  async function init(args) {
62
113
  const { server, call, CORS_CONFIG } = args;
63
114
 
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
+ });
195
+
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
+ }
208
+
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
+ }
222
+
223
+ let token = await tokens.provision(Object.assign({}, request.payload, { remoteAddress: request.app.ip }));
224
+
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
+ };
233
+
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
+
64
242
  server.route({
65
243
  method: 'POST',
66
- path: '/v1/token',
244
+ path: '/v1/tokens',
67
245
 
68
- async handler(request) {
69
- let accountObject = new Account({
70
- redis,
71
- account: request.payload.account,
72
- call,
73
- secret: await getSecret(),
74
- timeout: request.headers['x-ee-timeout']
75
- });
246
+ handler: provisionTokenHandler,
76
247
 
77
- try {
78
- // Nothing invalidates an access token once it is minted, so a token handed to an
79
- // anonymous caller keeps working indefinitely. This route normally requires a real
80
- // credential (`auth: {strategy: 'api-token', mode: 'required'}`) and a caller
81
- // presenting one is trusted, but the `disableTokens` setting rewrites a
82
- // credential-less request to `access_token=preauth` and the strategy accepts it,
83
- // marking the credentials `{preauth: true}`. That anonymous caller must never mint a
84
- // lasting token - whether or not an admin password happens to be set - so refuse it
85
- // here (headless provisioning uses the CLI or EENGINE_PREPARED_TOKEN, not this route).
86
- if (request.auth.credentials?.preauth) {
87
- throw Boom.forbidden('Can not provision an access token for an unauthenticated request');
248
+ options: {
249
+ description: 'Provision an access token',
250
+ // The conditional requirement is stated here because the schema cannot carry it: a flat
251
+ // `required` array has no way to say "unless `account` is set", and marking `permissions`
252
+ // required outright would describe the ordinary account-bound mint as invalid.
253
+ 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.',
254
+ tags: ['api', 'Access Tokens'],
255
+
256
+ plugins: {
257
+ openapi: {
258
+ responses: apiResponses('Returns the new token value. This is the only time it is shown - store it now.', 400, 401, 403, 404, 429, 500)
88
259
  }
260
+ },
89
261
 
90
- // throws if account does not exist
91
- await accountObject.loadAccountData();
262
+ auth: {
263
+ strategy: 'api-token',
264
+ mode: 'required'
265
+ },
266
+ cors: CORS_CONFIG,
267
+
268
+ validate: {
269
+ options: {
270
+ stripUnknown: false,
271
+ abortEarly: false,
272
+ convert: true
273
+ },
274
+ failAction,
92
275
 
93
- let token = await tokens.provision(Object.assign({}, request.payload, { remoteAddress: request.app.ip }));
276
+ payload: createTokenPayloadSchema
277
+ },
94
278
 
95
- return { token };
96
- } catch (err) {
97
- handleError(request, err);
279
+ response: {
280
+ schema: createTokenResponseSchema,
281
+ failAction: 'log'
98
282
  }
99
- },
283
+ }
284
+ });
285
+
286
+ server.route({
287
+ method: 'DELETE',
288
+ path: '/v1/tokens/{token}',
100
289
 
290
+ handler: deleteTokenHandler,
101
291
  options: {
102
- description: 'Provision an access token',
103
- notes: 'Provisions a new access token for an account',
292
+ description: 'Remove a token',
293
+ notes: 'Delete an access token',
104
294
  tags: ['api', 'Access Tokens'],
105
295
 
106
296
  plugins: {
107
297
  openapi: {
108
- responses: apiResponses('Returns the new token value. This is the only time it is shown - store it now.', 400, 401, 403, 404, 429, 500)
298
+ 'x-ee-impact': IMPACT.DESTRUCTIVE,
299
+ responses: apiResponses('Returns a deletion marker. The token stops working immediately.', 400, 401, 403, 429, 500)
109
300
  }
110
301
  },
111
302
 
@@ -123,57 +314,154 @@ async function init(args) {
123
314
  },
124
315
  failAction,
125
316
 
126
- payload: Joi.object({
127
- account: accountIdSchema.required(),
317
+ params: deleteTokenParamsSchema
318
+ },
319
+
320
+ response: {
321
+ schema: deleteTokenResponseSchema,
322
+ failAction: 'log'
323
+ }
324
+ }
325
+ });
128
326
 
129
- description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
327
+ server.route({
328
+ method: 'GET',
329
+ path: '/v1/tokens',
130
330
 
131
- scopes: Joi.array()
132
- .items(Joi.string().valid('api', 'smtp', 'imap-proxy').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
133
- .single()
134
- .default(['api'])
135
- .required()
136
- .description(
137
- 'Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication'
138
- )
139
- .label('Scopes'),
331
+ async handler(request) {
332
+ try {
333
+ // Every token by default, not just the unbound ones. "Which credentials exist on
334
+ // this instance" was previously unanswerable in one call: root tokens and each
335
+ // account's tokens lived behind separate endpoints, so an audit meant one request
336
+ // per account. `account` narrows it to one account when that is what you want.
337
+ //
338
+ // `total` and `pages` come back too: without them a caller could not tell a complete
339
+ // listing from a truncated one, which is what the previous hardcoded cap of 1000
340
+ // silently produced.
341
+ return await tokens.list(request.query.account, request.query.page, request.query.pageSize, request.query.query, {
342
+ all: !request.query.account
343
+ });
344
+ } catch (err) {
345
+ handleError(request, err);
346
+ }
347
+ },
348
+
349
+ options: {
350
+ description: 'List access tokens',
351
+ 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.',
352
+ tags: ['api', 'Access Tokens'],
353
+
354
+ plugins: {
355
+ openapi: {
356
+ responses: apiResponses('Returns the matching access tokens. Token values are never returned after creation.', 400, 401, 403, 429, 500)
357
+ }
358
+ },
140
359
 
141
- metadata: tokenMetadataSchema,
360
+ auth: {
361
+ strategy: 'api-token',
362
+ mode: 'required'
363
+ },
364
+ cors: CORS_CONFIG,
142
365
 
143
- restrictions: tokenRestrictionsSchema,
366
+ validate: {
367
+ options: {
368
+ stripUnknown: false,
369
+ abortEarly: false,
370
+ convert: true
371
+ },
372
+ failAction,
144
373
 
145
- ip: ipSchema.description('IP address of the requester').label('TokenIP')
146
- }).label('CreateToken')
374
+ query: Joi.object({
375
+ page: Joi.number()
376
+ .integer()
377
+ .min(0)
378
+ .max(1024 * 1024)
379
+ .default(0)
380
+ .example(0)
381
+ .description('Page number (zero indexed, so use 0 for first page)')
382
+ .label('PageNumber'),
383
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
384
+ query: Joi.string()
385
+ .empty('')
386
+ .trim()
387
+ .max(1024)
388
+ .example('agent')
389
+ .description('Filter by description, id or account')
390
+ .label('TokenSearchQuery'),
391
+ account: accountIdSchema.description('Only list tokens bound to this account. Omit to list every token on the instance')
392
+ }).label('TokensQuery')
147
393
  },
148
394
 
149
395
  response: {
150
396
  schema: Joi.object({
151
- token: Joi.string().length(64).hex().required().example('123456').description('Access token')
152
- }).label('CreateTokenResponse'),
397
+ account: accountIdSchema.allow(null).description('The account filter that was applied, or null when every token was listed'),
398
+ total: Joi.number().integer().example(12).description('How many tokens match'),
399
+ page: Joi.number().integer().example(0).description('Current page (zero indexed)'),
400
+ pages: Joi.number().integer().example(1).description('Total page count'),
401
+ tokens: Joi.array()
402
+ .items(
403
+ Joi.object({
404
+ // Null for an instance-wide token. Always present, so a client has
405
+ // one type for a token rather than one per listing.
406
+ account: accountIdSchema.allow(null).description('Account this token is bound to, or null for an instance-wide token'),
407
+ ...tokenListItemFields
408
+ }).label('TokensItem')
409
+ )
410
+ .label('TokensEntries')
411
+ }).label('TokensResponse'),
153
412
  failAction: 'log'
154
413
  }
155
414
  }
156
415
  });
157
416
 
158
417
  server.route({
159
- method: 'DELETE',
160
- path: '/v1/token/{token}',
418
+ method: 'GET',
419
+ path: '/v1/tokens/{token}',
161
420
 
162
421
  async handler(request) {
163
422
  try {
164
- return { deleted: await tokens.delete(request.params.token, { remoteAddress: request.app.ip }) };
423
+ // Both reads at once: the last-use record is keyed by the id the path already
424
+ // carries, so it never needed the record resolved first. tokens.list() puts the
425
+ // same pair in one multi() for every token it lists.
426
+ const [tokenData, access] = await Promise.all([loadTokenById(request.params.token), tokens.getAccess(request.params.token)]);
427
+ if (!tokenData) {
428
+ throwNotFound('Requested access token was not found');
429
+ }
430
+
431
+ // Same shape as an entry in the listings, so a client has one type for a token
432
+ // however it obtained it. `access` lives in a second hash, which is why it is
433
+ // fetched here rather than arriving with the record - leaving it out made the one
434
+ // endpoint that describes a single credential the one that could not say when it
435
+ // was last used.
436
+ const { id, account, description, metadata, ip, remoteAddress, scopes, restrictions, permissions, created, expires } = tokenData;
437
+
438
+ return {
439
+ id,
440
+ account: account || null,
441
+ description,
442
+ metadata,
443
+ ip,
444
+ remoteAddress,
445
+ scopes,
446
+ restrictions,
447
+ permissions,
448
+ created,
449
+ expires: expires ? new Date(expires) : undefined,
450
+ access
451
+ };
165
452
  } catch (err) {
166
453
  handleError(request, err);
167
454
  }
168
455
  },
456
+
169
457
  options: {
170
- description: 'Remove a token',
171
- notes: 'Delete an access token',
458
+ description: 'Get token info',
459
+ 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.',
172
460
  tags: ['api', 'Access Tokens'],
173
461
 
174
462
  plugins: {
175
463
  openapi: {
176
- responses: apiResponses('Returns a deletion marker. The token stops working immediately.', 400, 401, 403, 429, 500)
464
+ responses: apiResponses('Returns the stored token record. The token value is not included.', 400, 401, 403, 404, 429, 500)
177
465
  }
178
466
  },
179
467
 
@@ -192,14 +480,15 @@ async function init(args) {
192
480
  failAction,
193
481
 
194
482
  params: Joi.object({
195
- token: Joi.string().length(64).hex().required().example('123456').description('Access token')
196
- }).label('DeleteTokenRequest')
483
+ token: tokenIdParamSchema
484
+ }).label('GetTokenRequest')
197
485
  },
198
486
 
199
487
  response: {
200
488
  schema: Joi.object({
201
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the token deleted')
202
- }).label('DeleteTokenRequestResponse'),
489
+ account: accountIdSchema.allow(null).description('Account this token is bound to, or null for an instance-wide token'),
490
+ ...tokenListItemFields
491
+ }).label('TokenResponse'),
203
492
  failAction: 'log'
204
493
  }
205
494
  }
@@ -207,25 +496,30 @@ async function init(args) {
207
496
 
208
497
  server.route({
209
498
  method: 'GET',
210
- path: '/v1/tokens',
499
+ path: '/v1/tokens/{token}/log',
211
500
 
212
501
  async handler(request) {
213
502
  try {
214
- // TODO: allow paging
215
- return { tokens: (await tokens.list(null, 0, 1000)).tokens };
503
+ const tokenData = await loadTokenById(request.params.token);
504
+ if (!tokenData) {
505
+ throwNotFound('Requested access token was not found');
506
+ }
507
+
508
+ return Object.assign({ token: tokenData.id }, await tokenAuditLog.list(tokenData.id, request.query));
216
509
  } catch (err) {
217
510
  handleError(request, err);
218
511
  }
219
512
  },
220
513
 
221
514
  options: {
222
- description: 'List root tokens',
223
- notes: 'Lists access tokens registered for root access',
515
+ description: 'Get token audit log',
516
+ 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.',
224
517
  tags: ['api', 'Access Tokens'],
225
518
 
226
519
  plugins: {
227
520
  openapi: {
228
- responses: apiResponses('Returns the root access tokens. Token values are never returned after creation.', 401, 403, 429, 500)
521
+ 'x-ee-impact': IMPACT.READONLY,
522
+ responses: apiResponses('Returns the recorded requests for this token, newest first.', 400, 401, 403, 404, 429, 500)
229
523
  }
230
524
  },
231
525
 
@@ -241,13 +535,172 @@ async function init(args) {
241
535
  abortEarly: false,
242
536
  convert: true
243
537
  },
244
- failAction
538
+ failAction,
539
+
540
+ params: Joi.object({
541
+ token: tokenIdParamSchema
542
+ }).label('TokenLogRequest'),
543
+
544
+ query: Joi.object({
545
+ page: Joi.number()
546
+ .integer()
547
+ .min(0)
548
+ .max(1024 * 1024)
549
+ .default(0)
550
+ .example(0)
551
+ .description('Page number (zero indexed, so use 0 for first page)')
552
+ .label('PageNumber'),
553
+ pageSize: Joi.number()
554
+ .integer()
555
+ .min(1)
556
+ .max(tokenAuditLog.MAX_PAGE_SIZE)
557
+ .default(tokenAuditLog.DEFAULT_LOG_PAGE_SIZE)
558
+ .example(tokenAuditLog.DEFAULT_LOG_PAGE_SIZE)
559
+ .description('How many entries per page')
560
+ .label('PageSize')
561
+ }).label('TokenLogQuery')
245
562
  },
246
563
 
247
564
  response: {
248
565
  schema: Joi.object({
249
- tokens: Joi.array().items(Joi.object(tokenListItemFields).label('RootTokensItem')).label('RootTokensEntries')
250
- }).label('RootTokensResponse'),
566
+ token: tokenIdSchema,
567
+ total: Joi.number().integer().example(120).description('How many entries are stored for this token'),
568
+ page: Joi.number().integer().example(0).description('Current page (zero indexed)'),
569
+ pages: Joi.number().integer().example(6).description('Total page count'),
570
+ entries: Joi.array()
571
+ .items(
572
+ Joi.object({
573
+ time: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('When the request was made').label('TokenLogTime'),
574
+ ip: ipSchema.allow(null).description('Address the request came from').label('TokenLogIP'),
575
+ method: Joi.string()
576
+ .allow(null)
577
+ .example('get')
578
+ .description('HTTP method, or the surface name for SMTP and the IMAP proxy')
579
+ .label('TokenLogMethod'),
580
+ path: Joi.string()
581
+ .allow(null)
582
+ .example('/v1/account/{account}/messages')
583
+ .description('Route that was called')
584
+ .label('TokenLogPath'),
585
+ action: Joi.string()
586
+ .allow(null)
587
+ .example('read')
588
+ .description('Permission action the operation required')
589
+ .label('TokenLogAction'),
590
+ group: Joi.string()
591
+ .allow(null)
592
+ .example('message')
593
+ .description('Permission group the operation belongs to')
594
+ .label('TokenLogGroup'),
595
+ account: accountIdSchema.allow(null).description('Account the request addressed').label('TokenLogAccount'),
596
+ status: Joi.string()
597
+ .valid('allowed', 'denied')
598
+ .example('allowed')
599
+ .description('Whether the request was served')
600
+ .label('TokenLogStatus'),
601
+ reason: Joi.string()
602
+ .allow(null)
603
+ .example('group')
604
+ .description('Why it was refused. Null when it was allowed')
605
+ .label('TokenLogReason')
606
+ }).label('TokenLogEntry')
607
+ )
608
+ .label('TokenLogEntries')
609
+ }).label('TokenLogResponse'),
610
+ failAction: 'log'
611
+ }
612
+ }
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,
251
704
  failAction: 'log'
252
705
  }
253
706
  }
@@ -259,7 +712,7 @@ async function init(args) {
259
712
 
260
713
  async handler(request) {
261
714
  try {
262
- // TODO: allow paging
715
+ // The pre-2.79 response shape: the account's tokens with no paging metadata
263
716
  return { tokens: (await tokens.list(request.params.account, 0, 1000)).tokens };
264
717
  } catch (err) {
265
718
  handleError(request, err);
@@ -267,12 +720,13 @@ async function init(args) {
267
720
  },
268
721
 
269
722
  options: {
270
- description: 'List account tokens',
271
- notes: 'Lists access tokens registered for an account',
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.',
272
725
  tags: ['api', 'Access Tokens'],
273
726
 
274
727
  plugins: {
275
728
  openapi: {
729
+ deprecated: true,
276
730
  responses: apiResponses('Returns the access tokens scoped to the account.', 400, 401, 403, 429, 500)
277
731
  }
278
732
  },