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
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+
3
+ // Presentation of the token permission vocabulary for the admin UI: the checkbox rows on the token
4
+ // form, the presets above them, and the one-line summary on the token list.
5
+ //
6
+ // Its own module because two views need the same labels, and because the labels have to be derived
7
+ // from lib/api-routes/permission-map.js rather than typed again - a group added there without a
8
+ // label here would render as a blank checkbox, and one removed would leave a control that posts a
9
+ // value the API refuses.
10
+
11
+ const { ACTION, GROUP, GRANTABLE_GROUPS, SURFACE_GRANTS } = require('./api-routes/permission-map');
12
+ const tokenPermissions = require('./token-permissions');
13
+ const { ENUM_DESCRIPTIONS } = require('./enum-descriptions');
14
+
15
+ // Sentence-case labels for the checkbox rows. The slug itself is shown beside each one, so this only
16
+ // has to read well - it is not the identifier.
17
+ const ACTION_LABELS = {
18
+ [ACTION.READ]: 'Read',
19
+ [ACTION.WRITE]: 'Create and modify',
20
+ [ACTION.SEND]: 'Send email',
21
+ [ACTION.DESTRUCTIVE]: 'Delete'
22
+ };
23
+
24
+ const GROUP_LABELS = {
25
+ [GROUP.ACCOUNT]: 'Accounts',
26
+ [GROUP.MAILBOX]: 'Folders',
27
+ [GROUP.MESSAGE]: 'Messages',
28
+ [GROUP.SUBMIT]: 'Sending',
29
+ [GROUP.OUTBOX]: 'Sending queue',
30
+ [GROUP.EXPORT]: 'Bulk export',
31
+ [GROUP.TEMPLATE]: 'Templates',
32
+ [GROUP.BLOCKLIST]: 'Suppression lists',
33
+ [GROUP.WEBHOOK]: 'Webhook routes',
34
+ [GROUP.GATEWAY]: 'SMTP gateways',
35
+ [GROUP.EVENTS]: 'Change stream',
36
+ [GROUP.DIAGNOSTICS]: 'Statistics and status',
37
+ [GROUP.LOGS]: 'Connection logs'
38
+ };
39
+
40
+ // Clusters for the section list. Thirteen rows at identical weight is a scan rather than a choice,
41
+ // and the split is the one a reader already has: the mail itself, the things that act on it, and the
42
+ // things that only watch.
43
+ const GROUP_CLUSTERS = [
44
+ { label: 'Mail', groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.SUBMIT, GROUP.OUTBOX, GROUP.EXPORT] },
45
+ { label: 'Configuration', groups: [GROUP.TEMPLATE, GROUP.BLOCKLIST, GROUP.WEBHOOK, GROUP.GATEWAY] },
46
+ { label: 'Monitoring', groups: [GROUP.EVENTS, GROUP.DIAGNOSTICS, GROUP.LOGS] }
47
+ ];
48
+
49
+ // Starting points, because a fourteen-row matrix is not how anyone begins. Each is a real shape
50
+ // somebody asks for rather than an illustration of the axes.
51
+ const PRESETS = [
52
+ {
53
+ label: 'Read only',
54
+ title: 'Read messages, folders and accounts. Cannot change or send anything',
55
+ actions: [ACTION.READ],
56
+ groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.OUTBOX, GROUP.DIAGNOSTICS]
57
+ },
58
+ {
59
+ // Not "never delete it". Filing mail is the same operation as deleting it here - the delete
60
+ // endpoint moves the message to Trash, which this preset allows the token to do directly -
61
+ // so the honest claim is about the endpoints, not the outcome. See the note on
62
+ // ACTION.DESTRUCTIVE in lib/api-routes/permission-map.js.
63
+ label: 'Mail agent',
64
+ title: 'Read, file and send mail, without reaching the delete endpoints',
65
+ actions: [ACTION.READ, ACTION.WRITE, ACTION.SEND],
66
+ groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.SUBMIT, GROUP.OUTBOX]
67
+ },
68
+ {
69
+ // Deliberately not described as "no access to stored messages": a submit payload may carry
70
+ // `reference: {message, action: 'forward'}`, which reads a stored message and delivers it, so
71
+ // sending implies read-through of a message the holder can name. The grant is route-level and
72
+ // does not inspect the payload, so the claim would have been false.
73
+ label: 'Send only',
74
+ title: 'Submit mail and watch the sending queue',
75
+ actions: [ACTION.READ, ACTION.SEND],
76
+ groups: [GROUP.SUBMIT, GROUP.OUTBOX]
77
+ },
78
+ {
79
+ label: 'Everything allowed',
80
+ title: 'Every action on every section that can be granted. Still cannot reach credentials or settings',
81
+ actions: Object.values(ACTION),
82
+ groups: GRANTABLE_GROUPS
83
+ }
84
+ ];
85
+
86
+ // How each non-API scope reads in a sentence. The grants themselves come from SURFACE_GRANTS, which
87
+ // is what the enforcement reads, so this cannot describe rules that have since changed.
88
+ const SURFACE_LABELS = {
89
+ smtp: 'send over SMTP',
90
+ 'imap-proxy': 'connect through the IMAP proxy',
91
+ metrics: 'read the metrics endpoint'
92
+ };
93
+
94
+ /**
95
+ * View model for the permission controls on the token form.
96
+ *
97
+ * @returns {Object} { permissionActions, permissionGroups, permissionPresets }
98
+ */
99
+ function formModel() {
100
+ return {
101
+ permissionActions: Object.values(ACTION).map(value => ({
102
+ value,
103
+ inputId: `permissionAction_${value}`,
104
+ label: ACTION_LABELS[value] || value,
105
+ description: ENUM_DESCRIPTIONS.tokenAction[value] || ''
106
+ })),
107
+
108
+ // Clustered rather than flat. Asserted against GRANTABLE_GROUPS in the tests, so a group
109
+ // added without a cluster cannot silently vanish from the form.
110
+ permissionGroupClusters: GROUP_CLUSTERS.map(cluster => ({
111
+ label: cluster.label,
112
+ groups: cluster.groups.map(value => ({
113
+ value,
114
+ inputId: `permissionGroup_${value}`,
115
+ label: GROUP_LABELS[value] || value,
116
+ description: ENUM_DESCRIPTIONS.tokenGroup[value] || ''
117
+ }))
118
+ })),
119
+
120
+ // What each non-API scope needs before it can be used, derived from the tables that enforce
121
+ // it rather than restated in the page script. A hand-copied mirror would let the form keep
122
+ // showing an old warning after the grant list changed, which is exactly the drift
123
+ // lib/auth-token.js exists to prevent.
124
+ permissionSurfaces: Object.entries(SURFACE_LABELS).map(([scope, label]) => ({
125
+ scope,
126
+ label,
127
+ actionList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.action))].join(','),
128
+ groupList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.group))].join(',')
129
+ })),
130
+
131
+ // data-actions/data-groups are read by the preset buttons in views/tokens/new.hbs
132
+ permissionPresets: PRESETS.map(preset => ({
133
+ label: preset.label,
134
+ title: preset.title,
135
+ actionList: preset.actions.join(','),
136
+ groupList: preset.groups.join(',')
137
+ }))
138
+ };
139
+ }
140
+
141
+ // Phrases the two axes as something a person reads rather than as two labelled fields. An axis that
142
+ // is absent is not a restriction, so it is left out of the sentence entirely - saying "all sections"
143
+ // would imply a grant the record does not make.
144
+ //
145
+ // An axis that names everything is collapsed rather than enumerated. Spelling out all thirteen
146
+ // sections produced a line long enough to push the table sideways, and it read as a detailed
147
+ // restriction when it is the opposite: the interesting fact about such a token is what it still
148
+ // cannot reach.
149
+ function sentenceFor(actions, groups, coversAllActions, coversAllGroups) {
150
+ // An empty allowlist allows nothing, so the token authenticates and then refuses everything.
151
+ // "Can none only" said the record; this says what it means.
152
+ if (actions === 'none' || groups === 'none') {
153
+ return 'Allows nothing - this token cannot make any request';
154
+ }
155
+ const verb = coversAllActions ? 'Full access' : actions && `Can ${actions.toLowerCase()}`;
156
+ const where = coversAllGroups ? 'every section' : groups;
157
+
158
+ if (verb && where) {
159
+ return coversAllActions && coversAllGroups ? 'Full access, except settings, credentials and tokens' : `${verb} in ${where}`;
160
+ }
161
+ if (verb) {
162
+ return coversAllActions ? 'Full access' : `${verb} only`;
163
+ }
164
+ if (where) {
165
+ return coversAllGroups ? 'Every section' : `Limited to ${where}`;
166
+ }
167
+ return 'Restricted';
168
+ }
169
+
170
+ /**
171
+ * One-line description of what a stored `permissions` record allows, for the token list.
172
+ *
173
+ * @param {*} permissions - the record's `permissions` field
174
+ * @returns {Object|null} { actions, groups, unreadable } or null when the token is not narrowed
175
+ */
176
+ function summarize(permissions) {
177
+ // Asked of the module that enforces it rather than re-derived here. `{}`, an unknown axis and a
178
+ // slug outside the vocabulary are all refusals, so a view that only looked for a non-object
179
+ // would render them as working narrow credentials - which is the opposite of the truth, since
180
+ // every request such a token makes is denied.
181
+ const verdict = tokenPermissions.inspect({ permissions });
182
+
183
+ if (!verdict.narrowed) {
184
+ return null;
185
+ }
186
+
187
+ if (verdict.malformed) {
188
+ return { actions: null, groups: null, unreadable: true };
189
+ }
190
+
191
+ const label = (values, labels) => {
192
+ if (!Array.isArray(values)) {
193
+ return null;
194
+ }
195
+ if (!values.length) {
196
+ // An empty allowlist allows nothing, which is the opposite of the axis being absent
197
+ return 'none';
198
+ }
199
+ // Object.hasOwn rather than a bare lookup, for the same reason the parse uses it: a slug of
200
+ // `constructor` would otherwise render an Object.prototype member
201
+ return values.map(value => (Object.hasOwn(labels, value) ? labels[value] : value)).join(', ');
202
+ };
203
+
204
+ const actions = label(permissions.actions, ACTION_LABELS);
205
+ const groups = label(permissions.groups, GROUP_LABELS);
206
+
207
+ const covers = (values, whole) => Array.isArray(values) && values.length === whole.length && whole.every(entry => values.includes(entry));
208
+
209
+ return {
210
+ actions,
211
+ groups,
212
+ // One line a person can read, rather than two labelled fragments. "Can: Read / In: Messages"
213
+ // is the record read out loud; this is what the record means.
214
+ sentence: sentenceFor(actions, groups, covers(permissions.actions, Object.values(ACTION)), covers(permissions.groups, GRANTABLE_GROUPS)),
215
+ unreadable: false
216
+ };
217
+ }
218
+
219
+ module.exports = { formModel, summarize, ACTION_LABELS, GROUP_LABELS };
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ // Narrowing check for an access token that carries a `permissions` record.
4
+ //
5
+ // Two axes, both subtractive: `actions` says what the token may do, `groups` says what it may
6
+ // touch, and the vocabulary for both lives in lib/api-routes/permission-map.js. This function only
7
+ // ever SUBTRACTS from what `scopes` and the account binding already allow - there is no value of
8
+ // `permissions` that grants anything, so it is safe to run after those checks rather than instead
9
+ // of them.
10
+ //
11
+ // Shared by both enforcement points on the same precedent that put lib/auth-token.js in one place:
12
+ // the api-token strategy in workers/api.js for HTTP, and lib/auth-token.js for the SMTP submission
13
+ // and IMAP proxy surfaces. A policy change that landed on one and missed the other would be a hole
14
+ // in whichever surface was forgotten.
15
+
16
+ const { NEVER_GRANTABLE, ACTION_VALUES, GROUP_VALUES } = require('./api-routes/permission-map');
17
+
18
+ // The axes a record may carry, and the vocabulary each accepts. Anything else is a record this
19
+ // version does not understand.
20
+ const AXIS_VALUES = {
21
+ actions: ACTION_VALUES,
22
+ groups: GROUP_VALUES
23
+ };
24
+
25
+ const AXES = Object.keys(AXIS_VALUES);
26
+
27
+ // Why a request was refused. Reported to the caller rather than rendered here, because HTTP, SMTP
28
+ // and IMAP each say "no" differently.
29
+ const REASON = {
30
+ // The route resolved to no action or no group, so this vocabulary does not describe it. Means
31
+ // the route table and permission-map.js have diverged, which test/api-routes-table-test.js
32
+ // exists to prevent.
33
+ UNCLASSIFIED: 'unclassified',
34
+
35
+ // `permissions` is present but not a shape this version can read. Deliberately NOT treated as
36
+ // absent: see the comment on parsePermissions().
37
+ MALFORMED: 'malformed',
38
+
39
+ // A group no `permissions` record may ever name, whatever it says.
40
+ RESTRICTED: 'restricted',
41
+
42
+ ACTION: 'action',
43
+ GROUP: 'group'
44
+ };
45
+
46
+ /**
47
+ * Reads a `permissions` record, or reports that it cannot be read.
48
+ *
49
+ * The distinction between "absent" and "unreadable" is the whole safety of this module, because the
50
+ * two mean opposite things: absent is every token issued before permissions existed and must keep
51
+ * working unnarrowed, while unreadable must grant nothing. Collapsing them would turn a malformed
52
+ * record into a full-privilege token.
53
+ *
54
+ * That is not hypothetical. tokens.setRawData() writes whatever fields its input carries with no
55
+ * joi schema at all, and it is the import path for EENGINE_PREPARED_TOKEN, so an arbitrary
56
+ * `permissions` value can reach a record without ever passing route validation.
57
+ *
58
+ * @param {*} permissions - the record's `permissions` field
59
+ * @returns {{narrowed: Boolean, axes: (Object|null), malformed: Boolean}}
60
+ */
61
+ function parsePermissions(permissions) {
62
+ if (permissions === null || typeof permissions === 'undefined') {
63
+ return { narrowed: false, axes: null, malformed: false };
64
+ }
65
+
66
+ if (typeof permissions !== 'object' || Array.isArray(permissions)) {
67
+ return { narrowed: true, axes: null, malformed: true };
68
+ }
69
+
70
+ const keys = Object.keys(permissions);
71
+
72
+ // An unknown key is refused rather than ignored. That is what lets a later version add a third
73
+ // axis without this one silently disregarding it - an older release denies the request instead
74
+ // of honouring a narrowing it cannot apply.
75
+ if (keys.some(key => !AXES.includes(key))) {
76
+ return { narrowed: true, axes: null, malformed: true };
77
+ }
78
+
79
+ // `{}` is ambiguous between "no narrowing" and "grant nothing". The joi schema refuses it so it
80
+ // never reaches a record through the API, and anything that gets in another way is denied.
81
+ if (!keys.length) {
82
+ return { narrowed: true, axes: null, malformed: true };
83
+ }
84
+
85
+ const axes = {};
86
+ for (const axis of AXES) {
87
+ // Object.hasOwn rather than `in`: this record was msgpack-decoded from Redis by a path with
88
+ // no schema, and `in` walks the prototype chain, so a payload that got something onto the
89
+ // decoded object's prototype could otherwise supply an axis the record does not own.
90
+ if (!Object.hasOwn(permissions, axis)) {
91
+ continue;
92
+ }
93
+
94
+ const value = permissions[axis];
95
+ if (!Array.isArray(value) || value.some(entry => !AXIS_VALUES[axis].has(entry))) {
96
+ return { narrowed: true, axes: null, malformed: true };
97
+ }
98
+
99
+ // An empty array is well-formed and grants nothing: an allowlist that lists nothing allows
100
+ // nothing. That is the opposite of the axis being absent, and it matches how `scopes: []`
101
+ // already behaves.
102
+ axes[axis] = value;
103
+ }
104
+
105
+ return { narrowed: true, axes, malformed: false };
106
+ }
107
+
108
+ /**
109
+ * Is this operation allowed to the token?
110
+ *
111
+ * @param {Object} opts
112
+ * @param {Object} opts.tokenData - the record from tokens.get()
113
+ * @param {Object} opts.operation - { action, group }, resolved by the caller from the route
114
+ * @returns {{allowed: Boolean, reason: (String|null), required: (Object|null)}}
115
+ */
116
+ function check({ tokenData, operation }) {
117
+ const { action = null, group = null } = operation || {};
118
+ const parsed = parsePermissions(tokenData && tokenData.permissions);
119
+
120
+ if (!parsed.narrowed) {
121
+ // No narrowing on this token, so nothing to subtract. Every token issued before this
122
+ // feature shipped takes this path, which is what makes the change additive.
123
+ return { allowed: true, reason: null, required: null };
124
+ }
125
+
126
+ const required = { action, group };
127
+
128
+ if (parsed.malformed) {
129
+ return { allowed: false, reason: REASON.MALFORMED, required };
130
+ }
131
+
132
+ if (!action || !group) {
133
+ return { allowed: false, reason: REASON.UNCLASSIFIED, required };
134
+ }
135
+
136
+ // Checked before the axes, and independently of them, so no value of `groups` can reach these.
137
+ // This is the rule the rest of the model rests on: while it holds, a narrowed token cannot read
138
+ // the settings blob, cannot read a stored OAuth2 credential, and cannot mint or revoke a token,
139
+ // so it cannot widen itself. Encoded as a deny set rather than as an absence from the grantable
140
+ // list so that widening the grantable list can never quietly reopen it.
141
+ if (NEVER_GRANTABLE.has(group)) {
142
+ return { allowed: false, reason: REASON.RESTRICTED, required };
143
+ }
144
+
145
+ if (parsed.axes.actions && !parsed.axes.actions.includes(action)) {
146
+ return { allowed: false, reason: REASON.ACTION, required };
147
+ }
148
+
149
+ if (parsed.axes.groups && !parsed.axes.groups.includes(group)) {
150
+ return { allowed: false, reason: REASON.GROUP, required };
151
+ }
152
+
153
+ return { allowed: true, reason: null, required };
154
+ }
155
+
156
+ /**
157
+ * What this module makes of a token's `permissions` field, without an operation to check against.
158
+ *
159
+ * Exists so the admin UI can label a record the same way the enforcement reads it. Deriving the
160
+ * shape a second time in the view diverged immediately: `{}`, an unknown axis and an out-of-vocabulary
161
+ * slug are all refusals here, but a view that only looked for a non-object rendered them as working
162
+ * narrow credentials.
163
+ *
164
+ * @param {Object} tokenData - the record from tokens.get()
165
+ * @returns {{narrowed: Boolean, malformed: Boolean}}
166
+ */
167
+ function inspect(tokenData) {
168
+ const { narrowed, malformed } = parsePermissions(tokenData && tokenData.permissions);
169
+ return { narrowed, malformed };
170
+ }
171
+
172
+ module.exports = { check, inspect, REASON };