emailengine-app 2.79.1 → 2.79.2

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 (81) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +40 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +95 -18
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +97 -1
  15. package/lib/api-routes/route-helpers.js +16 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/submit-routes.js +41 -0
  18. package/lib/api-routes/template-routes.js +7 -0
  19. package/lib/api-routes/token-routes.js +4 -2
  20. package/lib/consts.js +30 -1
  21. package/lib/email-client/base-client.js +102 -117
  22. package/lib/email-client/gmail-client.js +87 -22
  23. package/lib/email-client/imap/mailbox.js +140 -66
  24. package/lib/email-client/outlook-client.js +17 -14
  25. package/lib/enum-descriptions.js +2 -1
  26. package/lib/field-usage.js +17 -1
  27. package/lib/lua/s-list-accounts.lua +5 -2
  28. package/lib/mcp/index.js +29 -0
  29. package/lib/mcp/inject.js +70 -0
  30. package/lib/mcp/json-schema.js +120 -0
  31. package/lib/mcp/listen.js +171 -0
  32. package/lib/mcp/oauth.js +324 -0
  33. package/lib/mcp/protocol.js +489 -0
  34. package/lib/mcp/resources.js +139 -0
  35. package/lib/mcp/tools.js +655 -0
  36. package/lib/openapi/index.js +3 -1
  37. package/lib/response-stream.js +52 -21
  38. package/lib/routes-ui.js +4 -0
  39. package/lib/schemas.js +24 -3
  40. package/lib/token-permission-view.js +104 -8
  41. package/lib/tokens.js +34 -5
  42. package/lib/tools.js +96 -0
  43. package/lib/ui-routes/account-routes.js +43 -1
  44. package/lib/ui-routes/admin-config-routes.js +114 -1
  45. package/lib/ui-routes/admin-entities-routes.js +54 -5
  46. package/lib/ui-routes/auth-routes.js +13 -0
  47. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  48. package/lib/ui-routes/route-helpers.js +116 -1
  49. package/lib/utils/network.js +9 -1
  50. package/lib/web-safe-html.js +61 -0
  51. package/lib/webhooks.js +3 -8
  52. package/package.json +9 -8
  53. package/sbom.json +1 -1
  54. package/scripts/README.md +25 -0
  55. package/scripts/build-icon.js +77 -0
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +98 -0
  58. package/static/emailengine.ico +0 -0
  59. package/static/js/ui.js +465 -1
  60. package/static/licenses.html +42 -22
  61. package/translations/messages.pot +57 -57
  62. package/views/config/mcp.hbs +361 -0
  63. package/views/config/oauth/index.hbs +7 -0
  64. package/views/layout/prompt.hbs +62 -0
  65. package/views/mcp/authorize.hbs +136 -0
  66. package/views/partials/head_assets.hbs +3 -3
  67. package/views/partials/mcp_access_levels.hbs +13 -0
  68. package/views/partials/mcp_account_limit.hbs +14 -0
  69. package/views/partials/mcp_tool_count.hbs +19 -0
  70. package/views/partials/side_menu.hbs +1 -0
  71. package/views/partials/ui/account-picker.hbs +59 -0
  72. package/views/partials/ui/code-block.hbs +26 -0
  73. package/views/partials/ui/menu-item.hbs +5 -0
  74. package/views/partials/ui/radio.hbs +41 -0
  75. package/views/partials/ui/tab.hbs +15 -10
  76. package/views/partials/ui/tabs.hbs +8 -5
  77. package/views/templates/template.hbs +4 -3
  78. package/views/tokens/index.hbs +8 -2
  79. package/views/tokens/new.hbs +514 -243
  80. package/winconf.js +148 -48
  81. package/workers/api.js +198 -48
@@ -28,142 +28,99 @@
28
28
 
29
29
  {{> ui/form-field id="description" label="Description" value=values.description error=errors.description required=true hint="This description is shown when listing active tokens."}}
30
30
 
31
- {{!-- Free text rather than a select: an instance can hold far more accounts than a list
32
- could usefully carry. The ID is resolved on submit, so a typo is refused rather than
33
- minting a token bound to nothing. --}}
34
- {{> ui/form-field id="account" label="Account ID (optional)" value=values.account error=errors.account placeholder="Leave empty to allow all accounts" hint="A bound token only works for that one account. Requests made for any other account are refused."}}
31
+ {{!-- A search box rather than a select or free text: an instance can hold far more
32
+ accounts than a list could usefully carry, and an account id is the one thing
33
+ about an account nobody remembers. The ID is still resolved on submit, so a value
34
+ naming a deleted account is refused rather than minting a token bound to
35
+ nothing. --}}
36
+ {{> ui/account-picker id="account" label="Account (optional)" value=values.account selected=selectedAccount error=errors.account
37
+ placeholder="Leave empty to allow all accounts"
38
+ hint="A bound token only works for that one account. Requests made for any other account are refused."}}
35
39
 
36
40
  <div>
37
- <h6 class="mb-2 font-bold">Allowed scopes</h6>
38
-
41
+ <h6 class="mb-1 font-bold">Allowed scopes</h6>
42
+ <p class="text-base-content/60 text-sm mb-3">
43
+ Which surfaces this credential opens. Scopes are fixed the moment the token exists, so
44
+ a surface left out here cannot be added later.
45
+ </p>
46
+
47
+ {{!-- One line of plain words per row. The bracketed slug beside each was the only
48
+ description a reader got, and a slug is an identifier rather than an
49
+ explanation - "MCP" in particular says nothing about what the token would then
50
+ be able to reach, or that it is not REST API access. --}}
39
51
  <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
40
- <li class="flex items-center gap-2 p-4">
41
- <input type="checkbox" class="checkbox checkbox-sm or-else-all scope-entry"
42
- data-target="scope-list" id="scopesAll" data-scope="*" name="scopesAll" {{#if
43
- values.scopesAll}}checked{{/if}} />
44
- <label class="label-text grow p-0" for="scopesAll">All scopes</label>
45
- <div class="text-base-content/60 code-link">["*"]</div>
52
+ <li class="p-4">
53
+ <div class="flex items-center gap-2">
54
+ <input type="checkbox" class="checkbox checkbox-sm or-else-all scope-entry"
55
+ data-target="scope-list" id="scopesAll" data-scope="*" name="scopesAll" {{#if
56
+ values.scopesAll}}checked{{/if}} />
57
+ <label class="label-text grow p-0" for="scopesAll">All scopes</label>
58
+ <div class="text-base-content/60 code-link">["*"]</div>
59
+ </div>
60
+ <p class="helper-text ms-7">Every surface below, including any added in a later release.</p>
46
61
  </li>
47
62
 
48
- <li class="flex items-center gap-2 p-4">
49
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesAPI"
50
- name="scopesAPI" data-scope="api" {{#if values.scopesAPI}}checked{{/if}} />
51
- <label class="label-text grow p-0" for="scopesAPI">API</label>
52
- <div class="text-base-content/60 code-link">["api"]</div>
63
+ <li class="p-4">
64
+ <div class="flex items-center gap-2">
65
+ <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesAPI"
66
+ name="scopesAPI" data-scope="api" {{#if values.scopesAPI}}checked{{/if}} />
67
+ <label class="label-text grow p-0" for="scopesAPI">API</label>
68
+ <div class="text-base-content/60 code-link">["api"]</div>
69
+ </div>
70
+ <p class="helper-text ms-7">The REST API under <code>/v1</code>.</p>
53
71
  </li>
54
72
 
55
- {{!-- Nested inside the API row, not stacked in a card of its own. As two sibling
56
- cards the relationship had to be asserted in prose: a reader saw "Allowed
57
- scopes" and "Permissions" and had no reason to think the second was a
58
- subset of one row of the first. Here the indent says it. --}}
59
- <li id="permissionRow" class="p-4 hidden">
60
- <div class="border-s-2 border-base-content/10 ps-4 space-y-4">
61
- <div>
62
- <h6 class="mb-1 font-bold">Limit what the API token can do</h6>
63
- <p class="text-base-content/60 text-sm mb-3">
64
- By default this token can use the whole API. Restrict it to hand out a
65
- credential for a single job: an agent that reads mail but cannot delete
66
- it, or a service that can only send.
67
- </p>
68
-
69
- <div id="permissionToggle">
70
- {{> ui/checkbox id="permissionsEnabled" label="Restrict what this token can do" checked=values.permissionsEnabled error=errors.permissions noName=true}}
71
- </div>
72
- </div>
73
-
74
- <div id="permissionSection" class="space-y-5{{#unless values.permissionsEnabled}} hidden{{/unless}}">
75
-
76
- <div>
77
- <h6 class="mb-1 font-bold">Pick a preset</h6>
78
- <p class="text-base-content/60 text-sm mb-2">
79
- These cover the usual shapes. Adjust the details below if you need something else.
80
- </p>
81
- <div class="flex flex-wrap gap-2">
82
- {{#each permissionPresets}}
83
- <button type="button" class="btn btn-sm btn-soft permission-preset" data-actions="{{actionList}}"
84
- data-groups="{{groupList}}" title="{{title}}">{{label}}</button>
85
- {{/each}}
86
- </div>
87
- </div>
88
-
89
- {{!-- The whole point of the two axes is what they produce together, and a reader should
90
- not have to multiply four boxes by thirteen to find out. Saying what the token
91
- CANNOT do matters as much: that is the reassurance someone wants when handing out
92
- a restricted credential. --}}
93
- <div id="permissionOutcome" class="rounded-box border border-base-content/10 bg-base-200/40 p-4 text-sm space-y-1"></div>
94
-
95
- {{!-- Filled in by the script below whenever a scope or an axis changes. Holding a
96
- scope the permissions make unusable is legitimate, so this warns rather than
97
- refuses - but it should never be a surprise. What each surface requires is
98
- handed over as data, derived from the tables that enforce it, so this cannot
99
- describe rules that have since changed. --}}
100
- <div id="permissionScopeWarning" class="alert alert-soft alert-warning text-sm hidden"
101
- data-surfaces="{{permissionSurfacesJson}}"></div>
102
-
103
- <div>
104
- <h6 class="mb-2 font-bold">What it can do</h6>
105
- <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
106
- {{#each permissionActions}}
107
- <li class="flex items-center gap-2 p-4">
108
- {{> ui/checkbox id=inputId label=label checked=checked noName=true dataValue=value class="permission-axis permission-action"}}
109
- <div class="text-base-content/60 code-link ms-auto self-start">["{{value}}"]</div>
110
- </li>
111
- {{/each}}
112
- </ul>
113
- </div>
114
-
115
- <div>
116
- <h6 class="mb-2 font-bold">What it can reach</h6>
117
- <div class="space-y-3">
118
- {{#each permissionGroupClusters}}
119
- <div>
120
- <div class="text-base-content/60 text-xs uppercase tracking-wide mb-1">{{label}}</div>
121
- <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
122
- {{#each groups}}
123
- <li class="flex items-center gap-2 p-4">
124
- {{> ui/checkbox id=inputId label=label checked=checked hint=description noName=true dataValue=value class="permission-axis permission-group"}}
125
- <div class="text-base-content/60 code-link ms-auto self-start">["{{value}}"]</div>
126
- </li>
127
- {{/each}}
128
- </ul>
129
- </div>
130
- {{/each}}
131
- </div>
132
-
133
- {{!-- Rendered as a visibly refused option rather than omitted: leaving it out
134
- entirely reads as an oversight, and the reason is the point. --}}
135
- <div class="mt-3 alert alert-soft alert-warning text-sm">
136
- <span class="icon-[tabler--lock] size-5 shrink-0"></span>
137
- <span>
138
- Some endpoints are never available to a restricted token, whatever you select here:
139
- settings, OAuth2 applications, licensing, access tokens and stored account
140
- credentials. A token that could reach those could grant itself more.
141
- </span>
142
- </div>
143
- </div>
144
- </div>
73
+ <li class="p-4">
74
+ <div class="flex items-center gap-2">
75
+ <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesSMTP"
76
+ name="scopesSMTP" data-scope="smtp" {{#if values.scopesSMTP}}checked{{/if}} />
77
+ <label class="label-text grow p-0" for="scopesSMTP">SMTP</label>
78
+ <div class="text-base-content/60 code-link">["smtp"]</div>
145
79
  </div>
80
+ <p class="helper-text ms-7">Submit mail through EmailEngine's own SMTP server.</p>
146
81
  </li>
147
82
 
148
- <li class="flex items-center gap-2 p-4">
149
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesSMTP"
150
- name="scopesSMTP" data-scope="smtp" {{#if values.scopesSMTP}}checked{{/if}} />
151
- <label class="label-text grow p-0" for="scopesSMTP">SMTP</label>
152
- <div class="text-base-content/60 code-link">["smtp"]</div>
83
+ <li class="p-4">
84
+ <div class="flex items-center gap-2">
85
+ <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesImapProxy"
86
+ name="scopesImapProxy" data-scope="imap-proxy" {{#if values.scopesImapProxy}}checked{{/if}} />
87
+ <label class="label-text grow p-0" for="scopesImapProxy">IMAP Proxy</label>
88
+ <div class="text-base-content/60 code-link">["imap-proxy"]</div>
89
+ </div>
90
+ <p class="helper-text ms-7">Open connected mailboxes with an ordinary IMAP client.</p>
153
91
  </li>
154
92
 
155
- <li class="flex items-center gap-2 p-4">
156
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesImapProxy"
157
- name="scopesImapProxy" data-scope="imap-proxy" {{#if values.scopesImapProxy}}checked{{/if}} />
158
- <label class="label-text grow p-0" for="scopesImapProxy">IMAP Proxy</label>
159
- <div class="text-base-content/60 code-link">["imap-proxy"]</div>
93
+ <li class="p-4">
94
+ <div class="flex items-center gap-2">
95
+ <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesMetrics"
96
+ name="scopesMetrics" data-scope="metrics" {{#if values.scopesMetrics}}checked{{/if}} />
97
+ <label class="label-text grow p-0" for="scopesMetrics">Metrics</label>
98
+ <div class="text-base-content/60 code-link">["metrics"]</div>
99
+ </div>
100
+ <p class="helper-text ms-7">Read the Prometheus metrics endpoint and nothing else.</p>
160
101
  </li>
161
102
 
162
- <li class="flex items-center gap-2 p-4">
163
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesMetrics"
164
- name="scopesMetrics" data-scope="metrics" {{#if values.scopesMetrics}}checked{{/if}} />
165
- <label class="label-text grow p-0" for="scopesMetrics">Metrics</label>
166
- <div class="text-base-content/60 code-link">["metrics"]</div>
103
+ <li class="p-4">
104
+ <div class="flex items-center gap-2">
105
+ <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesMcp"
106
+ name="scopesMcp" data-scope="mcp" {{#if values.scopesMcp}}checked{{/if}} />
107
+ <label class="label-text grow p-0" for="scopesMcp">MCP
108
+ {{> ui/badge label="Beta" variant="info" soft=true class="badge-sm align-middle" icon="" elId=""}}</label>
109
+ <div class="text-base-content/60 code-link">["mcp"]</div>
110
+ </div>
111
+ <p class="helper-text ms-7">Let an AI agent call MCP tools at <code>/mcp</code>. This is not REST
112
+ API access - the same token is refused by <code>/v1</code>.</p>
113
+ {{!-- The endpoint is off by default, so an operator can otherwise mint a
114
+ credential for something that is not serving and only find out in the
115
+ client. Both halves of the gate are folded into mcpReady. Revealed by
116
+ ticking the box rather than standing on the page: MCP being off is not
117
+ news to someone provisioning a plain API token, and the default
118
+ selection ("All scopes") technically carries the mcp scope too. --}}
119
+ {{#unless mcpReady}}
120
+ <p id="mcpDisabledHint" class="helper-text ms-7 text-warning hidden">The MCP endpoint is not
121
+ enabled on this instance, so this token would have nothing to talk to. <a
122
+ href="/admin/config/mcp" class="link">Turn it on</a> first.</p>
123
+ {{/unless}}
167
124
  </li>
168
125
  </ul>
169
126
  </div>
@@ -171,6 +128,143 @@
171
128
  </div>
172
129
  </div>
173
130
 
131
+ {{!-- Its own card rather than a row nested under "API", which is where this used to live. Both
132
+ per-request surfaces carry a narrowing - the REST API resolves it per endpoint, the MCP
133
+ endpoint per tool call - so an editor anchored to the API checkbox opened underneath an
134
+ unticked box whenever MCP alone was selected, titled for a surface the token would not even
135
+ have. What ties it to the scopes now is #accessAppliesTo, which names the ticked scopes it
136
+ affects; that is stricter than an indent, which could only ever point at one of them.
137
+
138
+ The record itself stays single: one `permissions` object narrows whatever surface the
139
+ request arrives on. That is why this is one editor with two modes rather than a tab per
140
+ scope - separate panes would promise two records that cannot exist. --}}
141
+ <div id="accessCard" class="hidden" data-surfaces="{{permissionSurfacesJson}}" data-mcp-presets="{{json mcpAccessPresets}}">
142
+ {{#> ui/card bodyClass="space-y-4"}}
143
+
144
+ <div>
145
+ <h6 id="accessCardTitle" class="mb-1 font-bold">Access level</h6>
146
+ <p id="accessAppliesTo" class="text-base-content/60 text-sm"></p>
147
+ </div>
148
+
149
+ {{!-- MCP-only mode. The three levels are the ones the OAuth consent prompt and the MCP config
150
+ page already offer, from the same table through the same partial, because the same
151
+ credential minted from three places must not mean three different things. A 52-cell
152
+ matrix is not how anyone provisions an agent, so it is the fourth option rather than
153
+ the only one - and unlike the API editor there is no "restrict?" toggle: read-only is
154
+ the default, because an agent credential that starts unrestricted is the wrong way
155
+ round. --}}
156
+ {{!-- Labelled by the card heading rather than carrying a legend of its own, which would
157
+ repeat "Access level" directly under itself --}}
158
+ <fieldset id="mcpLevelBlock" class="hidden space-y-2" aria-labelledby="accessCardTitle">
159
+ {{> mcp_access_levels name="mcpAccess" idPrefix="mcpAccess_" selected="read"}}
160
+ {{> ui/radio id="mcpAccess_custom" name="mcpAccess" value="custom" label="Custom permissions"
161
+ hint="Choose the exact actions and sections yourself, starting from the level selected above."}}
162
+
163
+ {{!-- At the decision point, as on the MCP config page: the level chosen here is what
164
+ decides whether instructions hidden inside received mail can act --}}
165
+ <p class="text-base-content/60 text-sm">Email content flows into whatever model the connected client runs,
166
+ and instructions inside received mail can steer it - grant sending and deleting rights deliberately.</p>
167
+ </fieldset>
168
+
169
+ {{!-- API mode. Unrestricted by default, because an API token is the general-purpose
170
+ credential and narrowing it is the exception. --}}
171
+ <div id="apiLimitBlock" class="hidden">
172
+ <p class="text-base-content/60 text-sm mb-3">
173
+ By default this token can use the whole API. Restrict it to hand out a credential for a
174
+ single job: an agent that reads mail but cannot delete it, or a service that can only send.
175
+ </p>
176
+ {{> ui/checkbox id="permissionsEnabled" label="Restrict what this token can do" checked=values.permissionsEnabled error=errors.permissions noName=true}}
177
+ </div>
178
+
179
+ {{!-- The whole point of the two axes is what they produce together, and a reader should not
180
+ have to multiply four boxes by thirteen to find out. Saying what the token CANNOT do
181
+ matters as much: that is the reassurance someone wants when handing out a restricted
182
+ credential. Outside #permissionSection because the MCP levels need it too - picking
183
+ "Mail agent" should say what that is, not only reveal a matrix. --}}
184
+ <div id="permissionOutcome" class="rounded-box border border-base-content/10 bg-base-200/40 p-4 text-sm space-y-1 hidden">
185
+ <div id="permissionOutcomeText" class="space-y-1"></div>
186
+ {{!-- Its own element rather than more appended lines: the count is the same one the
187
+ MCP config generator and the consent prompt show, and it is painted by the
188
+ shared helper that owns the rule. --}}
189
+ {{> mcp_tool_count id="mcpToolCount" class="pt-1"}}
190
+ </div>
191
+
192
+ {{!-- Filled in by the script below whenever a scope or an axis changes. Holding a scope the
193
+ permissions make unusable is legitimate, so this warns rather than refuses - but it
194
+ should never be a surprise. What each surface requires is handed over as data, derived
195
+ from the tables that enforce it, so this cannot describe rules that have since
196
+ changed. --}}
197
+ <div id="permissionScopeWarning" class="alert alert-soft alert-warning text-sm hidden"></div>
198
+
199
+ <div id="permissionSection" class="space-y-5 hidden">
200
+
201
+ <div id="permissionPresetRow">
202
+ <h6 class="mb-1 font-bold">Pick a preset</h6>
203
+ <p class="text-base-content/60 text-sm mb-2">
204
+ These cover the usual shapes. Adjust the details below if you need something else.
205
+ </p>
206
+ <div class="flex flex-wrap gap-2">
207
+ {{#each permissionPresets}}
208
+ <button type="button" class="btn btn-sm btn-soft permission-preset" data-actions="{{actionList}}"
209
+ data-groups="{{groupList}}" title="{{title}}">{{label}}</button>
210
+ {{/each}}
211
+ </div>
212
+ </div>
213
+
214
+ <div>
215
+ <h6 class="mb-2 font-bold">What it can do</h6>
216
+ <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
217
+ {{#each permissionActions}}
218
+ <li class="flex items-center gap-2 p-4" data-axis-row="action:{{value}}">
219
+ {{> ui/checkbox id=inputId label=label checked=checked noName=true dataValue=value class="permission-axis permission-action"}}
220
+ <div class="text-base-content/60 code-link ms-auto self-start">["{{value}}"]</div>
221
+ </li>
222
+ {{/each}}
223
+ </ul>
224
+ </div>
225
+
226
+ <div>
227
+ <h6 class="mb-2 font-bold">What it can reach</h6>
228
+ <div class="space-y-3">
229
+ {{#each permissionGroupClusters}}
230
+ <div data-cluster="{{label}}">
231
+ <div class="text-base-content/60 text-xs uppercase tracking-wide mb-1">{{label}}</div>
232
+ <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
233
+ {{#each groups}}
234
+ <li class="flex items-center gap-2 p-4" data-axis-row="group:{{value}}">
235
+ {{> ui/checkbox id=inputId label=label checked=checked hint=description noName=true dataValue=value class="permission-axis permission-group"}}
236
+ <div class="text-base-content/60 code-link ms-auto self-start">["{{value}}"]</div>
237
+ </li>
238
+ {{/each}}
239
+ </ul>
240
+ </div>
241
+ {{/each}}
242
+ </div>
243
+
244
+ {{!-- Only rendered in MCP-only mode, where two thirds of the sections above would be
245
+ inert: ticking "Webhook routes" for a token that can only reach /mcp changes
246
+ nothing at all, so those rows are taken out rather than left as decisions with
247
+ no effect. --}}
248
+ <div id="permissionMcpScopeNote" class="mt-3 text-base-content/60 text-sm hidden">Only the sections the
249
+ MCP endpoint can reach are listed. The rest exist on the REST API, which a token scoped to MCP
250
+ cannot call at all.</div>
251
+
252
+ {{!-- Rendered as a visibly refused option rather than omitted: leaving it out
253
+ entirely reads as an oversight, and the reason is the point. --}}
254
+ <div class="mt-3 alert alert-soft alert-warning text-sm">
255
+ <span class="icon-[tabler--lock] size-5 shrink-0"></span>
256
+ <span>
257
+ Some endpoints are never available to a restricted token, whatever you select here:
258
+ settings, OAuth2 applications, licensing, access tokens and stored account
259
+ credentials. A token that could reach those could grant itself more.
260
+ </span>
261
+ </div>
262
+ </div>
263
+ </div>
264
+
265
+ {{/ui/card}}
266
+ </div>
267
+
174
268
  <div class="mb-6">
175
269
  {{> ui/btn label="Generate a token" type="submit" icon="icon-[tabler--key]"}}
176
270
  </div>
@@ -205,136 +299,241 @@
205
299
 
206
300
  let showTokenValueElm = document.getElementById('showTokenValue');
207
301
 
208
- // The permission axes only mean anything while the restriction is on, so the whole block is
209
- // hidden until then rather than shown greyed out - an axis you can read but not use invites
210
- // the reading that it applies.
302
+ // Read by the tool count as well as by the submit handler: binding a token to an account
303
+ // changes which MCP tools it is offered, so the field is an input to the editor and not
304
+ // only a payload field.
305
+ let accountElm = document.getElementById('account');
306
+
307
+ let accessCardElm = document.getElementById('accessCard');
308
+ let accessAppliesToElm = document.getElementById('accessAppliesTo');
309
+ let mcpLevelBlockElm = document.getElementById('mcpLevelBlock');
310
+ let apiLimitBlockElm = document.getElementById('apiLimitBlock');
211
311
  let permissionsEnabledElm = document.getElementById('permissionsEnabled');
212
312
  let permissionSectionElm = document.getElementById('permissionSection');
213
- let permissionRowElm = document.getElementById('permissionRow');
214
-
215
- // Permissions are resolved per endpoint on the REST API. Without API access there is no
216
- // setting here that helps: the remaining scopes are checked once against everything their
217
- // surface can do, so any restriction either changes nothing or leaves the token unable to do
218
- // the one thing it was issued for. Scopes are fixed once the token exists, so the row is
219
- // absent rather than disabled - and its absence needs no caption, because a section that
220
- // only appears under API is self-evidently about API.
313
+ let permissionPresetRowElm = document.getElementById('permissionPresetRow');
314
+ let permissionOutcomeElm = document.getElementById('permissionOutcome');
315
+ let permissionOutcomeTextElm = document.getElementById('permissionOutcomeText');
316
+ let mcpToolCountElm = document.getElementById('mcpToolCount');
317
+ let permissionWarningElm = document.getElementById('permissionScopeWarning');
318
+ let permissionMcpNoteElm = document.getElementById('permissionMcpScopeNote');
319
+
320
+ // Everything this editor reasons about is handed over as data on one element: what each
321
+ // surface requires, what each MCP tool dispatches under, and what each named access level
322
+ // mints. All three are derived server-side from the tables that enforce them rather than
323
+ // restated here, so a change to the rules cannot leave the page describing the old ones.
324
+ let surfaceRequirements = {};
325
+ for (let entry of JSON.parse(accessCardElm.dataset.surfaces || '[]')) {
326
+ surfaceRequirements[entry.scope] = {
327
+ label: entry.label,
328
+ // 'all': checked once at login, every grant required. 'any': checked per
329
+ // request, usable while a single grant pair stays allowed.
330
+ mode: entry.mode,
331
+ actions: entry.actionList.split(',').filter(value => value),
332
+ groups: entry.groupList.split(',').filter(value => value),
333
+ grants: entry.grantList.split(',').filter(value => value).map(pair => pair.split(':'))
334
+ };
335
+ }
336
+
337
+ let mcpAccessPresets = JSON.parse(accessCardElm.dataset.mcpPresets || '{}');
338
+ // What the mcp scope can reach at all, which is also what the "Full access" level means:
339
+ // that level stores no record, so the surface grant list is its own description.
340
+ let mcpCeiling = surfaceRequirements.mcp || { actions: [], groups: [], grants: [] };
341
+
342
+ let scopeElms = Array.from(document.querySelectorAll('.scope-entry'));
343
+ let selectedScopes = () => scopeElms.filter(elm => elm.checked && !elm.disabled).map(elm => elm.dataset.scope);
344
+
345
+ // Permissions are resolved per endpoint on the REST API and per tool call on the MCP
346
+ // endpoint, so both of those scopes can carry a narrowing. The login-time scopes (SMTP,
347
+ // IMAP proxy, Metrics) are checked once against everything their surface can do, so for
348
+ // them any restriction either changes nothing or leaves the token unable to do the one
349
+ // thing it was issued for. Scopes are fixed once the token exists, so the card is absent
350
+ // rather than disabled when no per-request scope is ticked.
221
351
  //
222
352
  // "All scopes" only disables the individual boxes, it does not tick them, so the API row can
223
353
  // be greyed while this is open. That reads correctly: API access is granted by "All", and
224
354
  // this is how to narrow it.
225
- let hasApiScope = () =>
226
- Array.from(document.querySelectorAll('.scope-entry')).some(
227
- elm => elm.checked && !elm.disabled && (elm.dataset.scope === '*' || elm.dataset.scope === 'api')
228
- );
355
+ let hasApiScope = () => selectedScopes().some(scope => ['*', 'api'].includes(scope));
356
+ let hasMcpScope = () => selectedScopes().some(scope => ['*', 'mcp'].includes(scope));
357
+ let narrowableScope = () => hasApiScope() || hasMcpScope();
358
+
359
+ // The two editor modes. A token that reaches the MCP endpoint and not the REST API is a
360
+ // different thing from an API token - it is an agent connector, provisioned by picking a
361
+ // named level, the way the OAuth consent prompt and the MCP config page already do it. Any
362
+ // selection that includes API access falls back to the matrix instead, because one
363
+ // permissions record covers both surfaces and the API side needs all thirteen sections.
364
+ let mcpLevelMode = () => hasMcpScope() && !hasApiScope();
365
+
366
+ let selectedMcpLevel = () => {
367
+ let elm = document.querySelector('input[name="mcpAccess"]:checked');
368
+ return (elm && elm.value) || 'read';
369
+ };
229
370
 
230
- let syncPermissionSection = () => {
231
- let apiScope = hasApiScope();
371
+ // Sections the MCP surface can never reach are disabled while the level editor is showing,
372
+ // so every read of the axes skips them. Ticking "Webhook routes" for a token that can only
373
+ // call MCP tools grants nothing, and a control with no effect is worse than an absent one.
374
+ let axisElms = selector => Array.from(document.querySelectorAll(selector)).filter(elm => !elm.disabled);
375
+ let tickedValues = selector => axisElms(selector).filter(elm => elm.checked).map(elm => elm.dataset.value);
232
376
 
233
- permissionRowElm.classList.toggle('hidden', !apiScope);
234
- permissionSectionElm.classList.toggle('hidden', !apiScope || !permissionsEnabledElm.checked);
235
- };
377
+ let labelFor = elm => document.querySelector('label[for="' + elm.id + '"]').textContent.trim();
236
378
 
237
- permissionsEnabledElm.addEventListener('change', () => {
238
- // Enabling with nothing ticked would post two empty allowlists, which grant nothing. Start
239
- // from everything selected so the first state is "no narrowing yet" and each untick is a
240
- // deliberate subtraction.
241
- if (permissionsEnabledElm.checked && !document.querySelector('.permission-axis:checked')) {
242
- for (let elm of document.querySelectorAll('.permission-axis')) {
243
- elm.checked = true;
379
+ // Slug to label, read off the rendered rows so the sentence below cannot name an axis by a
380
+ // second, hand-written label. Built once: it does not depend on what is ticked.
381
+ let axisLabels = { action: {}, group: {} };
382
+ for (let elm of document.querySelectorAll('.permission-axis')) {
383
+ axisLabels[elm.classList.contains('permission-action') ? 'action' : 'group'][elm.dataset.value] = labelFor(elm);
384
+ }
385
+ let allActions = Object.keys(axisLabels.action);
386
+ let labelsFor = (axis, values) => values.map(value => axisLabels[axis][value] || value);
387
+
388
+ let asList = values => (values.length > 1 ? values.slice(0, -1).join(', ') + ' and ' + values[values.length - 1] : values[0] || '');
389
+
390
+ // The one record the whole page reads: the outcome sentence, the scope warning, the tool
391
+ // count and the submit payload all resolve it rather than each reading the DOM their own
392
+ // way. A named MCP level answers from the access table itself, not from the axes it would
393
+ // tick, so a level mints here exactly what it mints on the consent prompt.
394
+ //
395
+ // `unrestricted` is the absence of a permissions record, which is a different answer from
396
+ // an empty one: it means the scopes are the only bound.
397
+ let effectiveRecord = () => {
398
+ if (mcpLevelMode()) {
399
+ let level = selectedMcpLevel();
400
+ if (level !== 'custom') {
401
+ let record = mcpAccessPresets[level];
402
+ if (record) {
403
+ return { actions: record.actions, groups: record.groups, unrestricted: false };
404
+ }
405
+ // The full level is the one that legitimately stores no record. Any other level
406
+ // missing from the table means the table did not load, and a missing preset must
407
+ // not quietly mint a wider credential than the level on screen promises - the
408
+ // MCP config page's generator refuses the same way, and the consent route
409
+ // defaults the same direction.
410
+ return {
411
+ actions: mcpCeiling.actions,
412
+ groups: mcpCeiling.groups,
413
+ unrestricted: true,
414
+ unknownLevel: !Object.prototype.hasOwnProperty.call(mcpAccessPresets, level)
415
+ };
244
416
  }
417
+ } else if (!permissionsEnabledElm.checked) {
418
+ return { actions: allActions, groups: Object.keys(axisLabels.group), unrestricted: true };
245
419
  }
246
- syncPermissionSection();
247
- });
248
420
 
249
- syncPermissionSection();
421
+ return { actions: tickedValues('.permission-action'), groups: tickedValues('.permission-group'), unrestricted: false };
422
+ };
250
423
 
251
- let permissionWarningElm = document.getElementById('permissionScopeWarning');
424
+ // Applies a permission record to the axes. Shared by the API presets and by the switch into
425
+ // "Custom permissions", so the boxes a preset shows are the boxes that preset mints.
426
+ let applyRecord = (actions, groups) => {
427
+ for (let elm of document.querySelectorAll('.permission-action')) {
428
+ elm.checked = actions.includes(elm.dataset.value);
429
+ }
430
+ for (let elm of document.querySelectorAll('.permission-group')) {
431
+ elm.checked = groups.includes(elm.dataset.value);
432
+ }
433
+ };
252
434
 
253
- // Derived server-side from SCOPE_OPERATIONS and the route map rather than restated here, so a
254
- // change to what a surface requires cannot leave this warning describing the old rules.
255
- let surfaceRequirements = {};
256
- for (let entry of JSON.parse(permissionWarningElm.dataset.surfaces || '[]')) {
257
- surfaceRequirements[entry.scope] = {
258
- label: entry.label,
259
- actions: entry.actionList.split(',').filter(value => value),
260
- groups: entry.groupList.split(',').filter(value => value)
261
- };
262
- }
263
- let permissionOutcomeElm = document.getElementById('permissionOutcome');
435
+ let syncAxisAvailability = () => {
436
+ let restrictToMcp = mcpLevelMode();
264
437
 
265
- let tickedLabels = selector =>
266
- Array.from(document.querySelectorAll(selector))
267
- .filter(elm => elm.checked)
268
- .map(elm => document.querySelector('label[for="' + elm.id + '"]').textContent.trim());
438
+ for (let elm of document.querySelectorAll('.permission-axis')) {
439
+ let axis = elm.classList.contains('permission-action') ? 'actions' : 'groups';
440
+ let reachable = !restrictToMcp || mcpCeiling[axis].includes(elm.dataset.value);
269
441
 
270
- let untickedLabels = selector =>
271
- Array.from(document.querySelectorAll(selector))
272
- .filter(elm => !elm.checked)
273
- .map(elm => document.querySelector('label[for="' + elm.id + '"]').textContent.trim());
442
+ // Disabled rather than unticked: flipping the scopes back has to restore the
443
+ // selection rather than quietly lose it, and a disabled box is skipped by every
444
+ // read, so an out-of-reach section cannot ride into the posted record.
445
+ elm.disabled = !reachable;
446
+ let row = elm.closest('[data-axis-row]');
447
+ if (row) {
448
+ row.classList.toggle('hidden', !reachable);
449
+ }
450
+ }
274
451
 
275
- let asList = values => (values.length > 1 ? values.slice(0, -1).join(', ') + ' and ' + values[values.length - 1] : values[0] || '');
452
+ // A cluster whose every section is out of reach is a heading over nothing
453
+ for (let cluster of document.querySelectorAll('[data-cluster]')) {
454
+ let visible = Array.from(cluster.querySelectorAll('[data-axis-row]')).some(row => !row.classList.contains('hidden'));
455
+ cluster.classList.toggle('hidden', !visible);
456
+ }
457
+
458
+ permissionMcpNoteElm.classList.toggle('hidden', !restrictToMcp);
459
+ };
276
460
 
277
- // Says what the two axes produce together. Without it a reader has to cross four boxes with
278
- // thirteen to work out what they just built - and the half that reassures, what the token
279
- // CANNOT do, is not visible anywhere at all.
461
+ // What the current selection produces, in words. Without it a reader has to cross four boxes
462
+ // with thirteen to work out what they just built - and the half that reassures, what the
463
+ // token CANNOT do, is not visible anywhere at all.
280
464
  let syncPermissionOutcome = () => {
281
- let actions = tickedLabels('.permission-action');
282
- let groups = tickedLabels('.permission-group');
283
- let deniedActions = untickedLabels('.permission-action');
465
+ let visible = narrowableScope() && (mcpLevelMode() || permissionsEnabledElm.checked);
284
466
 
285
- permissionOutcomeElm.replaceChildren();
467
+ permissionOutcomeTextElm.replaceChildren();
468
+ permissionOutcomeElm.classList.toggle('hidden', !visible);
469
+ if (!visible) {
470
+ window.uiMcpToolCount(mcpToolCountElm, null);
471
+ return;
472
+ }
286
473
 
287
- if (!actions.length || !groups.length) {
474
+ let record = effectiveRecord();
475
+
476
+ // The same count the MCP config generator and the consent prompt show, painted by the
477
+ // shared helper rather than restated here - it owns both filters, the permission record
478
+ // and the account binding. Null when the token does not carry the surface at all, so a
479
+ // stale count cannot survive a scope change.
480
+ window.uiMcpToolCount(mcpToolCountElm, hasMcpScope() ? Object.assign({ account: accountElm.value }, record) : null);
481
+
482
+ if (!record.unrestricted && (!record.actions.length || !record.groups.length)) {
288
483
  let line = document.createElement('div');
289
484
  line.className = 'text-warning';
290
485
  line.textContent = 'Nothing is selected yet, so this token would not be able to do anything.';
291
- permissionOutcomeElm.append(line);
486
+ permissionOutcomeTextElm.append(line);
292
487
  return;
293
488
  }
294
489
 
295
490
  let can = document.createElement('div');
296
491
  let canLabel = document.createElement('strong');
297
492
  canLabel.textContent = 'This token can ';
298
- can.append(canLabel, document.createTextNode(asList(actions).toLowerCase() + ' in ' + asList(groups) + '.'));
299
- permissionOutcomeElm.append(can);
493
+ can.append(
494
+ canLabel,
495
+ document.createTextNode(asList(labelsFor('action', record.actions)).toLowerCase() + ' in ' + asList(labelsFor('group', record.groups)) + '.')
496
+ );
497
+ permissionOutcomeTextElm.append(can);
300
498
 
499
+ let deniedActions = allActions.filter(value => !record.actions.includes(value));
301
500
  if (deniedActions.length) {
302
501
  let cannot = document.createElement('div');
303
502
  cannot.className = 'text-base-content/60';
304
- cannot.textContent = 'It cannot ' + asList(deniedActions).toLowerCase() + ', anywhere.';
305
- permissionOutcomeElm.append(cannot);
503
+ cannot.textContent = 'It cannot ' + asList(labelsFor('action', deniedActions)).toLowerCase() + ', anywhere.';
504
+ permissionOutcomeTextElm.append(cannot);
306
505
  }
307
506
 
308
507
  let rest = document.createElement('div');
309
508
  rest.className = 'text-base-content/60';
310
509
  rest.textContent = 'It cannot reach anything else, or read credentials and settings.';
311
- permissionOutcomeElm.append(rest);
510
+ permissionOutcomeTextElm.append(rest);
312
511
  };
313
512
 
314
513
  let syncPermissionWarning = () => {
315
- if (!permissionsEnabledElm.checked || !hasApiScope()) {
514
+ let record = effectiveRecord();
515
+
516
+ if (record.unrestricted || !narrowableScope()) {
316
517
  permissionWarningElm.classList.add('hidden');
317
518
  return;
318
519
  }
319
520
 
320
- let selectedScopes = Array.from(document.querySelectorAll('.scope-entry'))
321
- .filter(elm => elm.checked && !elm.disabled)
322
- .map(elm => elm.dataset.scope);
521
+ let scopes = selectedScopes();
323
522
 
324
523
  // "All scopes" carries every surface with it
325
- if (selectedScopes.includes('*')) {
326
- selectedScopes = Object.keys(surfaceRequirements);
524
+ if (scopes.includes('*')) {
525
+ scopes = Object.keys(surfaceRequirements);
327
526
  }
328
527
 
329
- let ticked = selector => Array.from(document.querySelectorAll(selector)).filter(elm => elm.checked).map(elm => elm.dataset.value);
330
- let actions = ticked('.permission-action');
331
- let groups = ticked('.permission-group');
332
-
333
- let blocked = selectedScopes
528
+ let blocked = scopes
334
529
  .filter(scope => surfaceRequirements[scope])
335
530
  .filter(scope => {
336
531
  let need = surfaceRequirements[scope];
337
- return !need.actions.every(value => actions.includes(value)) || !need.groups.every(value => groups.includes(value));
532
+ if (need.mode === 'any') {
533
+ // Per-request surface: usable while any one (action, group) pair survives
534
+ return !need.grants.some(([action, group]) => record.actions.includes(action) && record.groups.includes(group));
535
+ }
536
+ return !need.actions.every(value => record.actions.includes(value)) || !need.groups.every(value => record.groups.includes(value));
338
537
  })
339
538
  .map(scope => surfaceRequirements[scope].label);
340
539
 
@@ -350,37 +549,107 @@
350
549
  permissionWarningElm.classList.remove('hidden');
351
550
  };
352
551
 
353
- for (let elm of document.querySelectorAll('.permission-axis, .scope-entry')) {
354
- elm.addEventListener('change', () => {
355
- syncPermissionSection();
356
- syncPermissionWarning();
357
- syncPermissionOutcome();
358
- });
359
- }
360
- permissionsEnabledElm.addEventListener('change', () => {
552
+ // Names the scopes this editor actually affects. The old nesting asserted that relationship
553
+ // with an indent under the API checkbox, which stopped being true the moment a second scope
554
+ // carried a narrowing - and read as a lie whenever that checkbox was unticked.
555
+ let syncAccessHeader = () => {
556
+ let surfaces = [];
557
+ if (hasApiScope()) {
558
+ surfaces.push('REST API requests');
559
+ }
560
+ if (hasMcpScope()) {
561
+ surfaces.push('MCP tool calls');
562
+ }
563
+
564
+ accessAppliesToElm.textContent =
565
+ surfaces.length > 1
566
+ ? 'Applies to ' + surfaces.join(' and ') + '. One set of limits covers both surfaces.'
567
+ : 'Applies to ' + surfaces[0] + '.';
568
+ };
569
+
570
+ let syncAccessCard = () => {
571
+ let visible = narrowableScope();
572
+
573
+ accessCardElm.classList.toggle('hidden', !visible);
574
+ if (!visible) {
575
+ return;
576
+ }
577
+
578
+ let levelMode = mcpLevelMode();
579
+
580
+ syncAccessHeader();
581
+ mcpLevelBlockElm.classList.toggle('hidden', !levelMode);
582
+ apiLimitBlockElm.classList.toggle('hidden', levelMode);
583
+ syncAxisAvailability();
584
+
585
+ // The matrix is the detail view behind either mode: the "Custom permissions" level on
586
+ // one side, the restriction toggle on the other. The API presets are shapes for the
587
+ // REST API, so they stay out of the way in level mode, where the named levels above
588
+ // are the presets.
589
+ permissionSectionElm.classList.toggle('hidden', levelMode ? selectedMcpLevel() !== 'custom' : !permissionsEnabledElm.checked);
590
+ permissionPresetRowElm.classList.toggle('hidden', levelMode);
591
+ };
592
+
593
+ // Only rendered when the endpoint is off, and only shown once the box that needs it is
594
+ // ticked - the default selection carries the mcp scope with everything else, and warning
595
+ // about a disabled endpoint on a page nobody opened for MCP is noise.
596
+ let mcpDisabledHintElm = document.getElementById('mcpDisabledHint');
597
+ let scopesMcpElm = document.getElementById('scopesMcp');
598
+
599
+ let syncAll = () => {
600
+ syncAccessCard();
361
601
  syncPermissionWarning();
362
602
  syncPermissionOutcome();
363
- });
364
- syncPermissionWarning();
365
- syncPermissionOutcome();
366
603
 
367
- for (let button of document.querySelectorAll('.permission-preset')) {
368
- button.addEventListener('click', () => {
369
- let actions = (button.dataset.actions || '').split(',').filter(value => value);
370
- let groups = (button.dataset.groups || '').split(',').filter(value => value);
604
+ if (mcpDisabledHintElm) {
605
+ mcpDisabledHintElm.classList.toggle('hidden', !scopesMcpElm.checked || scopesMcpElm.disabled);
606
+ }
607
+ };
371
608
 
372
- for (let elm of document.querySelectorAll('.permission-action')) {
373
- elm.checked = actions.includes(elm.dataset.value);
609
+ permissionsEnabledElm.addEventListener('change', () => {
610
+ // Enabling with nothing ticked would post two empty allowlists, which grant nothing. Start
611
+ // from everything selected so the first state is "no narrowing yet" and each untick is a
612
+ // deliberate subtraction.
613
+ if (permissionsEnabledElm.checked && !document.querySelector('.permission-axis:checked')) {
614
+ for (let elm of document.querySelectorAll('.permission-axis')) {
615
+ elm.checked = true;
374
616
  }
375
- for (let elm of document.querySelectorAll('.permission-group')) {
376
- elm.checked = groups.includes(elm.dataset.value);
617
+ }
618
+ syncAll();
619
+ });
620
+
621
+ // The level the axes are seeded from when "Custom permissions" is picked, which is what its
622
+ // hint promises. Starts at the default selection rather than empty.
623
+ let lastNamedLevel = selectedMcpLevel();
624
+ for (let elm of document.querySelectorAll('input[name="mcpAccess"]')) {
625
+ elm.addEventListener('change', () => {
626
+ if (elm.value === 'custom') {
627
+ let record = mcpAccessPresets[lastNamedLevel];
628
+ applyRecord(record ? record.actions : mcpCeiling.actions, record ? record.groups : mcpCeiling.groups);
629
+ } else {
630
+ lastNamedLevel = elm.value;
377
631
  }
632
+ syncAll();
633
+ });
634
+ }
635
+
636
+ for (let elm of document.querySelectorAll('.permission-axis, .scope-entry')) {
637
+ elm.addEventListener('change', syncAll);
638
+ }
639
+
640
+ // Per keystroke, because what the binding costs an agent should be visible while the field
641
+ // is being filled in rather than only after it loses focus
642
+ accountElm.addEventListener('input', syncAll);
378
643
 
379
- syncPermissionWarning();
380
- syncPermissionOutcome();
644
+ for (let button of document.querySelectorAll('.permission-preset')) {
645
+ button.addEventListener('click', () => {
646
+ applyRecord((button.dataset.actions || '').split(',').filter(value => value), (button.dataset.groups || '').split(',').filter(value => value));
647
+ syncAll();
381
648
  });
382
649
  }
383
650
 
651
+ syncAll();
652
+
384
653
  document.getElementById('token-form').addEventListener('submit', e => {
385
654
  e.preventDefault()
386
655
 
@@ -388,16 +657,10 @@
388
657
  document.getElementById('description').value = description
389
658
 
390
659
  // Trimmed so the redirect below filters the listing on the same value that was posted
391
- let account = document.getElementById('account').value.trim();
392
- document.getElementById('account').value = account
393
-
394
- let collectAxis = selector =>
395
- Array.from(document.querySelectorAll(selector))
396
- .filter(elm => elm.checked)
397
- .map(elm => elm.dataset.value);
660
+ let account = accountElm.value.trim();
661
+ accountElm.value = account
398
662
 
399
663
  let scopes = [];
400
- let scopeElms = document.querySelectorAll('.scope-entry');
401
664
  for (let elm of scopeElms) {
402
665
  if (elm.checked && !elm.disabled) {
403
666
  scopes.push(elm.dataset.scope);
@@ -426,27 +689,35 @@
426
689
  document.getElementById('showTokenError').classList.add('hidden');
427
690
  uiModal.open('#showToken');
428
691
 
429
- // Sent only when the restriction is on. Omitting the field is what "not narrowed" means on
430
- // the record, so an unchecked box must not post an empty object - that is a different
431
- // answer, and the API refuses it.
432
- let permissions = permissionsEnabledElm.checked && hasApiScope()
433
- ? {
434
- actions: collectAxis('.permission-action'),
435
- groups: collectAxis('.permission-group')
436
- }
437
- : null;
692
+ // Omitting the field is what "not narrowed" means on the record, so an unchecked toggle -
693
+ // and the MCP "Full access" level, which the access table stores as null for exactly that
694
+ // reason - must not post an empty object. That is a different answer, and the API refuses
695
+ // it.
696
+ let record = effectiveRecord();
697
+ let permissions = record.unrestricted ? null : { actions: record.actions, groups: record.groups };
698
+
699
+ let refuse = message => {
700
+ document.getElementById('showTokenLoader').classList.add('hidden');
701
+ document.getElementById('showTokenContent').classList.add('hidden');
702
+ document.getElementById('showTokenError').classList.remove('hidden');
703
+ document.getElementById('showTokenError').textContent = message;
704
+ uiModal.open('#showToken');
705
+ };
706
+
707
+ // The access table failed to load, so the level on screen cannot be resolved to the
708
+ // record it promises. Refused rather than posted: what would go out is the absence of a
709
+ // narrowing, which is the widest answer there is.
710
+ if (record.unknownLevel) {
711
+ refuse('The access levels failed to load, so the selected level cannot be applied. Reload the page and try again.');
712
+ return;
713
+ }
438
714
 
439
715
  // Said here rather than left to the schema. tokenPermissionsSchema refuses an empty axis
440
716
  // too, but a joi rejection reaches this page as a bare "HTTP error! status: 400", which
441
717
  // tells the reader nothing about the box they left unticked.
442
718
  if (permissions && (!permissions.actions.length || !permissions.groups.length)) {
443
719
  let missing = !permissions.actions.length ? 'action' : 'section';
444
- document.getElementById('showTokenLoader').classList.add('hidden');
445
- document.getElementById('showTokenContent').classList.add('hidden');
446
- document.getElementById('showTokenError').classList.remove('hidden');
447
- document.getElementById('showTokenError').textContent =
448
- `Select at least one ${missing}. A restriction that allows nothing would create a token that cannot make any request.`;
449
- uiModal.open('#showToken');
720
+ refuse(`Select at least one ${missing}. A restriction that allows nothing would create a token that cannot make any request.`);
450
721
  return;
451
722
  }
452
723