emailengine-app 2.79.0 → 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 (110) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +79 -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 +137 -19
  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 +101 -1
  15. package/lib/api-routes/route-helpers.js +87 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/settings-routes.js +37 -14
  18. package/lib/api-routes/submit-routes.js +41 -0
  19. package/lib/api-routes/template-routes.js +7 -0
  20. package/lib/api-routes/token-routes.js +292 -122
  21. package/lib/arf-detect.js +17 -4
  22. package/lib/bounce-detect.js +28 -17
  23. package/lib/consts.js +36 -1
  24. package/lib/db.js +6 -0
  25. package/lib/email-client/base-client.js +102 -117
  26. package/lib/email-client/gmail-client.js +91 -29
  27. package/lib/email-client/imap/mailbox.js +175 -101
  28. package/lib/email-client/imap-client.js +49 -2
  29. package/lib/email-client/outlook-client.js +20 -24
  30. package/lib/enum-descriptions.js +2 -1
  31. package/lib/field-usage.js +17 -1
  32. package/lib/lua/h-set-new-mark.lua +36 -0
  33. package/lib/lua/s-list-accounts.lua +5 -2
  34. package/lib/mcp/index.js +29 -0
  35. package/lib/mcp/inject.js +70 -0
  36. package/lib/mcp/json-schema.js +120 -0
  37. package/lib/mcp/listen.js +171 -0
  38. package/lib/mcp/oauth.js +324 -0
  39. package/lib/mcp/protocol.js +489 -0
  40. package/lib/mcp/resources.js +139 -0
  41. package/lib/mcp/tools.js +655 -0
  42. package/lib/message-port-stream.js +84 -1
  43. package/lib/oauth2-apps.js +84 -15
  44. package/lib/openapi/build-document.js +5 -1
  45. package/lib/openapi/index.js +3 -1
  46. package/lib/response-stream.js +52 -21
  47. package/lib/routes-ui.js +4 -0
  48. package/lib/schemas.js +26 -5
  49. package/lib/settings.js +23 -9
  50. package/lib/token-audit-log.js +32 -9
  51. package/lib/token-permission-view.js +104 -8
  52. package/lib/tokens.js +194 -68
  53. package/lib/tools.js +96 -0
  54. package/lib/ui-routes/account-routes.js +55 -6
  55. package/lib/ui-routes/admin-config-routes.js +114 -1
  56. package/lib/ui-routes/admin-entities-routes.js +103 -19
  57. package/lib/ui-routes/auth-routes.js +13 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  59. package/lib/ui-routes/oauth-config-routes.js +7 -7
  60. package/lib/ui-routes/route-helpers.js +143 -1
  61. package/lib/ui-routes/suppression-list-routes.js +14 -9
  62. package/lib/utils/decode-headers.js +42 -0
  63. package/lib/utils/header-map.js +48 -0
  64. package/lib/utils/network.js +9 -1
  65. package/lib/utils/unsafe-key.js +59 -0
  66. package/lib/web-safe-html.js +61 -0
  67. package/lib/webhook-routing.js +6 -2
  68. package/lib/webhooks.js +31 -8
  69. package/package.json +9 -8
  70. package/sbom.json +1 -1
  71. package/scripts/README.md +25 -0
  72. package/scripts/build-icon.js +77 -0
  73. package/server.js +39 -17
  74. package/static/css/flyonui.css +1 -1
  75. package/static/css/src/app.tailwind.css +98 -0
  76. package/static/emailengine.ico +0 -0
  77. package/static/js/ui.js +465 -1
  78. package/static/licenses.html +42 -22
  79. package/translations/messages.pot +57 -57
  80. package/views/accounts/account.hbs +8 -8
  81. package/views/accounts/browse.hbs +1 -1
  82. package/views/accounts/edit.hbs +2 -2
  83. package/views/config/mcp.hbs +361 -0
  84. package/views/config/oauth/index.hbs +7 -0
  85. package/views/gateways/edit.hbs +1 -1
  86. package/views/gateways/gateway.hbs +2 -2
  87. package/views/gateways/index.hbs +7 -7
  88. package/views/layout/prompt.hbs +62 -0
  89. package/views/mcp/authorize.hbs +136 -0
  90. package/views/partials/accounts_table.hbs +7 -7
  91. package/views/partials/head_assets.hbs +3 -3
  92. package/views/partials/mcp_access_levels.hbs +13 -0
  93. package/views/partials/mcp_account_limit.hbs +14 -0
  94. package/views/partials/mcp_tool_count.hbs +19 -0
  95. package/views/partials/side_menu.hbs +1 -0
  96. package/views/partials/ui/account-picker.hbs +59 -0
  97. package/views/partials/ui/code-block.hbs +26 -0
  98. package/views/partials/ui/menu-item.hbs +5 -0
  99. package/views/partials/ui/radio.hbs +41 -0
  100. package/views/partials/ui/tab.hbs +15 -10
  101. package/views/partials/ui/tabs.hbs +8 -5
  102. package/views/suppression-lists/list.hbs +1 -1
  103. package/views/templates/index.hbs +2 -2
  104. package/views/templates/template.hbs +5 -4
  105. package/views/tokens/index.hbs +30 -4
  106. package/views/tokens/new.hbs +517 -239
  107. package/winconf.js +148 -48
  108. package/workers/api.js +239 -95
  109. package/workers/imap.js +65 -72
  110. package/workers/webhooks.js +21 -1
@@ -21,7 +21,6 @@
21
21
  {{else}}
22
22
  <form method="post" id="token-form" action="/admin/tokens/new">
23
23
  <input type="hidden" name="crumb" value="{{crumb}}" />
24
- <input type="hidden" id="account" name="account" value="{{values.account}}" />
25
24
 
26
25
  <div class="card bg-base-100 shadow-md mb-6">
27
26
 
@@ -29,137 +28,99 @@
29
28
 
30
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."}}
31
30
 
32
- <div>
33
- <h6 class="mb-2 font-bold">Allowed scopes</h6>
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."}}
34
39
 
40
+ <div>
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. --}}
35
51
  <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
36
- <li class="flex items-center gap-2 p-4">
37
- <input type="checkbox" class="checkbox checkbox-sm or-else-all scope-entry"
38
- data-target="scope-list" id="scopesAll" data-scope="*" name="scopesAll" {{#if
39
- values.scopesAll}}checked{{/if}} />
40
- <label class="label-text grow p-0" for="scopesAll">All scopes</label>
41
- <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>
42
61
  </li>
43
62
 
44
- <li class="flex items-center gap-2 p-4">
45
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesAPI"
46
- name="scopesAPI" data-scope="api" {{#if values.scopesAPI}}checked{{/if}} />
47
- <label class="label-text grow p-0" for="scopesAPI">API</label>
48
- <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>
49
71
  </li>
50
72
 
51
- {{!-- Nested inside the API row, not stacked in a card of its own. As two sibling
52
- cards the relationship had to be asserted in prose: a reader saw "Allowed
53
- scopes" and "Permissions" and had no reason to think the second was a
54
- subset of one row of the first. Here the indent says it. --}}
55
- <li id="permissionRow" class="p-4 hidden">
56
- <div class="border-s-2 border-base-content/10 ps-4 space-y-4">
57
- <div>
58
- <h6 class="mb-1 font-bold">Limit what the API token can do</h6>
59
- <p class="text-base-content/60 text-sm mb-3">
60
- By default this token can use the whole API. Restrict it to hand out a
61
- credential for a single job: an agent that reads mail but cannot delete
62
- it, or a service that can only send.
63
- </p>
64
-
65
- <div id="permissionToggle">
66
- {{> ui/checkbox id="permissionsEnabled" label="Restrict what this token can do" checked=values.permissionsEnabled error=errors.permissions noName=true}}
67
- </div>
68
- </div>
69
-
70
- <div id="permissionSection" class="space-y-5{{#unless values.permissionsEnabled}} hidden{{/unless}}">
71
-
72
- <div>
73
- <h6 class="mb-1 font-bold">Pick a preset</h6>
74
- <p class="text-base-content/60 text-sm mb-2">
75
- These cover the usual shapes. Adjust the details below if you need something else.
76
- </p>
77
- <div class="flex flex-wrap gap-2">
78
- {{#each permissionPresets}}
79
- <button type="button" class="btn btn-sm btn-soft permission-preset" data-actions="{{actionList}}"
80
- data-groups="{{groupList}}" title="{{title}}">{{label}}</button>
81
- {{/each}}
82
- </div>
83
- </div>
84
-
85
- {{!-- The whole point of the two axes is what they produce together, and a reader should
86
- not have to multiply four boxes by thirteen to find out. Saying what the token
87
- CANNOT do matters as much: that is the reassurance someone wants when handing out
88
- a restricted credential. --}}
89
- <div id="permissionOutcome" class="rounded-box border border-base-content/10 bg-base-200/40 p-4 text-sm space-y-1"></div>
90
-
91
- {{!-- Filled in by the script below whenever a scope or an axis changes. Holding a
92
- scope the permissions make unusable is legitimate, so this warns rather than
93
- refuses - but it should never be a surprise. What each surface requires is
94
- handed over as data, derived from the tables that enforce it, so this cannot
95
- describe rules that have since changed. --}}
96
- <div id="permissionScopeWarning" class="alert alert-soft alert-warning text-sm hidden"
97
- data-surfaces="{{permissionSurfacesJson}}"></div>
98
-
99
- <div>
100
- <h6 class="mb-2 font-bold">What it can do</h6>
101
- <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
102
- {{#each permissionActions}}
103
- <li class="flex items-center gap-2 p-4">
104
- {{> ui/checkbox id=inputId label=label checked=checked noName=true dataValue=value class="permission-axis permission-action"}}
105
- <div class="text-base-content/60 code-link ms-auto self-start">["{{value}}"]</div>
106
- </li>
107
- {{/each}}
108
- </ul>
109
- </div>
110
-
111
- <div>
112
- <h6 class="mb-2 font-bold">What it can reach</h6>
113
- <div class="space-y-3">
114
- {{#each permissionGroupClusters}}
115
- <div>
116
- <div class="text-base-content/60 text-xs uppercase tracking-wide mb-1">{{label}}</div>
117
- <ul class="divide-y divide-base-content/10 rounded-box border border-base-content/10">
118
- {{#each groups}}
119
- <li class="flex items-center gap-2 p-4">
120
- {{> ui/checkbox id=inputId label=label checked=checked hint=description noName=true dataValue=value class="permission-axis permission-group"}}
121
- <div class="text-base-content/60 code-link ms-auto self-start">["{{value}}"]</div>
122
- </li>
123
- {{/each}}
124
- </ul>
125
- </div>
126
- {{/each}}
127
- </div>
128
-
129
- {{!-- Rendered as a visibly refused option rather than omitted: leaving it out
130
- entirely reads as an oversight, and the reason is the point. --}}
131
- <div class="mt-3 alert alert-soft alert-warning text-sm">
132
- <span class="icon-[tabler--lock] size-5 shrink-0"></span>
133
- <span>
134
- Some endpoints are never available to a restricted token, whatever you select here:
135
- settings, OAuth2 applications, licensing, access tokens and stored account
136
- credentials. A token that could reach those could grant itself more.
137
- </span>
138
- </div>
139
- </div>
140
- </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>
141
79
  </div>
80
+ <p class="helper-text ms-7">Submit mail through EmailEngine's own SMTP server.</p>
142
81
  </li>
143
82
 
144
- <li class="flex items-center gap-2 p-4">
145
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesSMTP"
146
- name="scopesSMTP" data-scope="smtp" {{#if values.scopesSMTP}}checked{{/if}} />
147
- <label class="label-text grow p-0" for="scopesSMTP">SMTP</label>
148
- <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>
149
91
  </li>
150
92
 
151
- <li class="flex items-center gap-2 p-4">
152
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesImapProxy"
153
- name="scopesImapProxy" data-scope="imap-proxy" {{#if values.scopesImapProxy}}checked{{/if}} />
154
- <label class="label-text grow p-0" for="scopesImapProxy">IMAP Proxy</label>
155
- <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>
156
101
  </li>
157
102
 
158
- <li class="flex items-center gap-2 p-4">
159
- <input type="checkbox" class="checkbox checkbox-sm scope-entry scope-list" id="scopesMetrics"
160
- name="scopesMetrics" data-scope="metrics" {{#if values.scopesMetrics}}checked{{/if}} />
161
- <label class="label-text grow p-0" for="scopesMetrics">Metrics</label>
162
- <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}}
163
124
  </li>
164
125
  </ul>
165
126
  </div>
@@ -167,6 +128,143 @@
167
128
  </div>
168
129
  </div>
169
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
+
170
268
  <div class="mb-6">
171
269
  {{> ui/btn label="Generate a token" type="submit" icon="icon-[tabler--key]"}}
172
270
  </div>
@@ -201,136 +299,241 @@
201
299
 
202
300
  let showTokenValueElm = document.getElementById('showTokenValue');
203
301
 
204
- // The permission axes only mean anything while the restriction is on, so the whole block is
205
- // hidden until then rather than shown greyed out - an axis you can read but not use invites
206
- // 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');
207
311
  let permissionsEnabledElm = document.getElementById('permissionsEnabled');
208
312
  let permissionSectionElm = document.getElementById('permissionSection');
209
- let permissionRowElm = document.getElementById('permissionRow');
210
-
211
- // Permissions are resolved per endpoint on the REST API. Without API access there is no
212
- // setting here that helps: the remaining scopes are checked once against everything their
213
- // surface can do, so any restriction either changes nothing or leaves the token unable to do
214
- // the one thing it was issued for. Scopes are fixed once the token exists, so the row is
215
- // absent rather than disabled - and its absence needs no caption, because a section that
216
- // 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.
217
351
  //
218
352
  // "All scopes" only disables the individual boxes, it does not tick them, so the API row can
219
353
  // be greyed while this is open. That reads correctly: API access is granted by "All", and
220
354
  // this is how to narrow it.
221
- let hasApiScope = () =>
222
- Array.from(document.querySelectorAll('.scope-entry')).some(
223
- elm => elm.checked && !elm.disabled && (elm.dataset.scope === '*' || elm.dataset.scope === 'api')
224
- );
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
+ };
225
370
 
226
- let syncPermissionSection = () => {
227
- 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);
228
376
 
229
- permissionRowElm.classList.toggle('hidden', !apiScope);
230
- permissionSectionElm.classList.toggle('hidden', !apiScope || !permissionsEnabledElm.checked);
231
- };
377
+ let labelFor = elm => document.querySelector('label[for="' + elm.id + '"]').textContent.trim();
232
378
 
233
- permissionsEnabledElm.addEventListener('change', () => {
234
- // Enabling with nothing ticked would post two empty allowlists, which grant nothing. Start
235
- // from everything selected so the first state is "no narrowing yet" and each untick is a
236
- // deliberate subtraction.
237
- if (permissionsEnabledElm.checked && !document.querySelector('.permission-axis:checked')) {
238
- for (let elm of document.querySelectorAll('.permission-axis')) {
239
- 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
+ };
240
416
  }
417
+ } else if (!permissionsEnabledElm.checked) {
418
+ return { actions: allActions, groups: Object.keys(axisLabels.group), unrestricted: true };
241
419
  }
242
- syncPermissionSection();
243
- });
244
420
 
245
- syncPermissionSection();
421
+ return { actions: tickedValues('.permission-action'), groups: tickedValues('.permission-group'), unrestricted: false };
422
+ };
246
423
 
247
- 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
+ };
248
434
 
249
- // Derived server-side from SCOPE_OPERATIONS and the route map rather than restated here, so a
250
- // change to what a surface requires cannot leave this warning describing the old rules.
251
- let surfaceRequirements = {};
252
- for (let entry of JSON.parse(permissionWarningElm.dataset.surfaces || '[]')) {
253
- surfaceRequirements[entry.scope] = {
254
- label: entry.label,
255
- actions: entry.actionList.split(',').filter(value => value),
256
- groups: entry.groupList.split(',').filter(value => value)
257
- };
258
- }
259
- let permissionOutcomeElm = document.getElementById('permissionOutcome');
435
+ let syncAxisAvailability = () => {
436
+ let restrictToMcp = mcpLevelMode();
260
437
 
261
- let tickedLabels = selector =>
262
- Array.from(document.querySelectorAll(selector))
263
- .filter(elm => elm.checked)
264
- .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);
265
441
 
266
- let untickedLabels = selector =>
267
- Array.from(document.querySelectorAll(selector))
268
- .filter(elm => !elm.checked)
269
- .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
+ }
270
451
 
271
- 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
+ }
272
457
 
273
- // Says what the two axes produce together. Without it a reader has to cross four boxes with
274
- // thirteen to work out what they just built - and the half that reassures, what the token
275
- // CANNOT do, is not visible anywhere at all.
458
+ permissionMcpNoteElm.classList.toggle('hidden', !restrictToMcp);
459
+ };
460
+
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.
276
464
  let syncPermissionOutcome = () => {
277
- let actions = tickedLabels('.permission-action');
278
- let groups = tickedLabels('.permission-group');
279
- let deniedActions = untickedLabels('.permission-action');
465
+ let visible = narrowableScope() && (mcpLevelMode() || permissionsEnabledElm.checked);
280
466
 
281
- permissionOutcomeElm.replaceChildren();
467
+ permissionOutcomeTextElm.replaceChildren();
468
+ permissionOutcomeElm.classList.toggle('hidden', !visible);
469
+ if (!visible) {
470
+ window.uiMcpToolCount(mcpToolCountElm, null);
471
+ return;
472
+ }
473
+
474
+ let record = effectiveRecord();
282
475
 
283
- if (!actions.length || !groups.length) {
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)) {
284
483
  let line = document.createElement('div');
285
484
  line.className = 'text-warning';
286
485
  line.textContent = 'Nothing is selected yet, so this token would not be able to do anything.';
287
- permissionOutcomeElm.append(line);
486
+ permissionOutcomeTextElm.append(line);
288
487
  return;
289
488
  }
290
489
 
291
490
  let can = document.createElement('div');
292
491
  let canLabel = document.createElement('strong');
293
492
  canLabel.textContent = 'This token can ';
294
- can.append(canLabel, document.createTextNode(asList(actions).toLowerCase() + ' in ' + asList(groups) + '.'));
295
- 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);
296
498
 
499
+ let deniedActions = allActions.filter(value => !record.actions.includes(value));
297
500
  if (deniedActions.length) {
298
501
  let cannot = document.createElement('div');
299
502
  cannot.className = 'text-base-content/60';
300
- cannot.textContent = 'It cannot ' + asList(deniedActions).toLowerCase() + ', anywhere.';
301
- permissionOutcomeElm.append(cannot);
503
+ cannot.textContent = 'It cannot ' + asList(labelsFor('action', deniedActions)).toLowerCase() + ', anywhere.';
504
+ permissionOutcomeTextElm.append(cannot);
302
505
  }
303
506
 
304
507
  let rest = document.createElement('div');
305
508
  rest.className = 'text-base-content/60';
306
509
  rest.textContent = 'It cannot reach anything else, or read credentials and settings.';
307
- permissionOutcomeElm.append(rest);
510
+ permissionOutcomeTextElm.append(rest);
308
511
  };
309
512
 
310
513
  let syncPermissionWarning = () => {
311
- if (!permissionsEnabledElm.checked || !hasApiScope()) {
514
+ let record = effectiveRecord();
515
+
516
+ if (record.unrestricted || !narrowableScope()) {
312
517
  permissionWarningElm.classList.add('hidden');
313
518
  return;
314
519
  }
315
520
 
316
- let selectedScopes = Array.from(document.querySelectorAll('.scope-entry'))
317
- .filter(elm => elm.checked && !elm.disabled)
318
- .map(elm => elm.dataset.scope);
521
+ let scopes = selectedScopes();
319
522
 
320
523
  // "All scopes" carries every surface with it
321
- if (selectedScopes.includes('*')) {
322
- selectedScopes = Object.keys(surfaceRequirements);
524
+ if (scopes.includes('*')) {
525
+ scopes = Object.keys(surfaceRequirements);
323
526
  }
324
527
 
325
- let ticked = selector => Array.from(document.querySelectorAll(selector)).filter(elm => elm.checked).map(elm => elm.dataset.value);
326
- let actions = ticked('.permission-action');
327
- let groups = ticked('.permission-group');
328
-
329
- let blocked = selectedScopes
528
+ let blocked = scopes
330
529
  .filter(scope => surfaceRequirements[scope])
331
530
  .filter(scope => {
332
531
  let need = surfaceRequirements[scope];
333
- 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));
334
537
  })
335
538
  .map(scope => surfaceRequirements[scope].label);
336
539
 
@@ -346,50 +549,118 @@
346
549
  permissionWarningElm.classList.remove('hidden');
347
550
  };
348
551
 
349
- for (let elm of document.querySelectorAll('.permission-axis, .scope-entry')) {
350
- elm.addEventListener('change', () => {
351
- syncPermissionSection();
352
- syncPermissionWarning();
353
- syncPermissionOutcome();
354
- });
355
- }
356
- 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();
357
601
  syncPermissionWarning();
358
602
  syncPermissionOutcome();
359
- });
360
- syncPermissionWarning();
361
- syncPermissionOutcome();
362
603
 
363
- for (let button of document.querySelectorAll('.permission-preset')) {
364
- button.addEventListener('click', () => {
365
- let actions = (button.dataset.actions || '').split(',').filter(value => value);
366
- let groups = (button.dataset.groups || '').split(',').filter(value => value);
604
+ if (mcpDisabledHintElm) {
605
+ mcpDisabledHintElm.classList.toggle('hidden', !scopesMcpElm.checked || scopesMcpElm.disabled);
606
+ }
607
+ };
367
608
 
368
- for (let elm of document.querySelectorAll('.permission-action')) {
369
- 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;
370
616
  }
371
- for (let elm of document.querySelectorAll('.permission-group')) {
372
- 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;
373
631
  }
632
+ syncAll();
633
+ });
634
+ }
635
+
636
+ for (let elm of document.querySelectorAll('.permission-axis, .scope-entry')) {
637
+ elm.addEventListener('change', syncAll);
638
+ }
374
639
 
375
- syncPermissionWarning();
376
- syncPermissionOutcome();
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);
643
+
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();
377
648
  });
378
649
  }
379
650
 
651
+ syncAll();
652
+
380
653
  document.getElementById('token-form').addEventListener('submit', e => {
381
654
  e.preventDefault()
382
655
 
383
656
  let description = document.getElementById('description').value.trim();
384
657
  document.getElementById('description').value = description
385
658
 
386
- let collectAxis = selector =>
387
- Array.from(document.querySelectorAll(selector))
388
- .filter(elm => elm.checked)
389
- .map(elm => elm.dataset.value);
659
+ // Trimmed so the redirect below filters the listing on the same value that was posted
660
+ let account = accountElm.value.trim();
661
+ accountElm.value = account
390
662
 
391
663
  let scopes = [];
392
- let scopeElms = document.querySelectorAll('.scope-entry');
393
664
  for (let elm of scopeElms) {
394
665
  if (elm.checked && !elm.disabled) {
395
666
  scopes.push(elm.dataset.scope);
@@ -409,7 +680,6 @@
409
680
  showTokenValueElm.value = '';
410
681
 
411
682
  if (wasShown) {
412
- let account = document.getElementById('account').value || '';
413
683
  location.assign("/admin/tokens" + (account ? '?account=' + encodeURIComponent(account) : ''));
414
684
  }
415
685
  }, { once: true });
@@ -419,27 +689,35 @@
419
689
  document.getElementById('showTokenError').classList.add('hidden');
420
690
  uiModal.open('#showToken');
421
691
 
422
- // Sent only when the restriction is on. Omitting the field is what "not narrowed" means on
423
- // the record, so an unchecked box must not post an empty object - that is a different
424
- // answer, and the API refuses it.
425
- let permissions = permissionsEnabledElm.checked && hasApiScope()
426
- ? {
427
- actions: collectAxis('.permission-action'),
428
- groups: collectAxis('.permission-group')
429
- }
430
- : 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
+ }
431
714
 
432
715
  // Said here rather than left to the schema. tokenPermissionsSchema refuses an empty axis
433
716
  // too, but a joi rejection reaches this page as a bare "HTTP error! status: 400", which
434
717
  // tells the reader nothing about the box they left unticked.
435
718
  if (permissions && (!permissions.actions.length || !permissions.groups.length)) {
436
719
  let missing = !permissions.actions.length ? 'action' : 'section';
437
- document.getElementById('showTokenLoader').classList.add('hidden');
438
- document.getElementById('showTokenContent').classList.add('hidden');
439
- document.getElementById('showTokenError').classList.remove('hidden');
440
- document.getElementById('showTokenError').textContent =
441
- `Select at least one ${missing}. A restriction that allows nothing would create a token that cannot make any request.`;
442
- uiModal.open('#showToken');
720
+ refuse(`Select at least one ${missing}. A restriction that allows nothing would create a token that cannot make any request.`);
443
721
  return;
444
722
  }
445
723
 
@@ -447,7 +725,7 @@
447
725
  description,
448
726
  scopes,
449
727
  permissions,
450
- account: document.getElementById('account').value || ''
728
+ account
451
729
  }).then(data => {
452
730
 
453
731
  if (!data.success) {