emailengine-app 2.79.1 → 2.79.3
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.
- package/.github/workflows/deploy.yml +92 -39
- package/.github/workflows/release.yaml +94 -34
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +85 -0
- package/bin/emailengine.js +8 -1
- package/config/default.toml +6 -0
- package/copy-static-files.sh +23 -2
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +138 -18
- package/lib/api-routes/account-routes.js +13 -1
- package/lib/api-routes/index.js +12 -0
- package/lib/api-routes/mailbox-routes.js +6 -0
- package/lib/api-routes/mcp-oauth-routes.js +259 -0
- package/lib/api-routes/mcp-routes.js +172 -0
- package/lib/api-routes/message-routes.js +125 -4
- package/lib/api-routes/outbox-routes.js +7 -0
- package/lib/api-routes/permission-map.js +97 -1
- package/lib/api-routes/route-helpers.js +16 -4
- package/lib/api-routes/route-metadata.js +24 -4
- package/lib/api-routes/submit-routes.js +41 -0
- package/lib/api-routes/template-routes.js +7 -0
- package/lib/api-routes/token-routes.js +4 -2
- package/lib/consts.js +30 -1
- package/lib/email-client/base-client.js +235 -163
- package/lib/email-client/gmail-client.js +99 -22
- package/lib/email-client/imap/mailbox.js +140 -66
- package/lib/email-client/imap-client.js +74 -68
- package/lib/email-client/outlook-client.js +29 -14
- package/lib/enum-descriptions.js +2 -1
- package/lib/field-usage.js +17 -1
- package/lib/logger.js +43 -3
- package/lib/lua/s-list-accounts.lua +5 -2
- package/lib/mcp/index.js +29 -0
- package/lib/mcp/inject.js +70 -0
- package/lib/mcp/json-schema.js +120 -0
- package/lib/mcp/listen.js +171 -0
- package/lib/mcp/oauth.js +324 -0
- package/lib/mcp/protocol.js +489 -0
- package/lib/mcp/resources.js +139 -0
- package/lib/mcp/tools.js +655 -0
- package/lib/openapi/index.js +3 -1
- package/lib/response-stream.js +52 -21
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +24 -3
- package/lib/token-permission-view.js +104 -8
- package/lib/tokens.js +34 -5
- package/lib/tools.js +96 -0
- package/lib/ui-routes/account-routes.js +43 -1
- package/lib/ui-routes/admin-config-routes.js +114 -1
- package/lib/ui-routes/admin-entities-routes.js +54 -5
- package/lib/ui-routes/auth-routes.js +13 -0
- package/lib/ui-routes/mcp-consent-routes.js +330 -0
- package/lib/ui-routes/route-helpers.js +116 -1
- package/lib/utils/network.js +9 -1
- package/lib/web-safe-html.js +61 -0
- package/lib/webhooks.js +3 -8
- package/package.json +15 -14
- package/sbom.json +1 -1
- package/scripts/README.md +25 -0
- package/scripts/build-icon.js +77 -0
- package/server.js +21 -9
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +98 -0
- package/static/emailengine.ico +0 -0
- package/static/js/ui.js +465 -1
- package/static/licenses.html +85 -135
- package/translations/messages.pot +103 -103
- package/views/config/mcp.hbs +361 -0
- package/views/config/oauth/index.hbs +7 -0
- package/views/layout/prompt.hbs +62 -0
- package/views/mcp/authorize.hbs +136 -0
- package/views/partials/head_assets.hbs +3 -3
- package/views/partials/mcp_access_levels.hbs +13 -0
- package/views/partials/mcp_account_limit.hbs +14 -0
- package/views/partials/mcp_tool_count.hbs +19 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/account-picker.hbs +59 -0
- package/views/partials/ui/code-block.hbs +26 -0
- package/views/partials/ui/menu-item.hbs +5 -0
- package/views/partials/ui/radio.hbs +41 -0
- package/views/partials/ui/tab.hbs +15 -10
- package/views/partials/ui/tabs.hbs +8 -5
- package/views/templates/template.hbs +4 -3
- package/views/tokens/index.hbs +8 -2
- package/views/tokens/new.hbs +514 -243
- package/winconf.js +148 -48
- package/workers/api.js +198 -48
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Converts joi schemas into the JSON Schema (2020-12 dialect) shape MCP tool definitions carry.
|
|
4
|
+
//
|
|
5
|
+
// Reuses the OpenAPI SchemaConverter from lib/openapi/joi-schema.js rather than walking joi's
|
|
6
|
+
// describe() output a second time: that converter is the one place the repo reads joi schemas,
|
|
7
|
+
// and a second reader would drift from it. The converter is asked to inline everything
|
|
8
|
+
// (useDefinitions: false, so no #/components/schemas refs can appear), and the OpenAPI 3.0
|
|
9
|
+
// idioms in its output are then rewritten into their JSON Schema equivalents:
|
|
10
|
+
//
|
|
11
|
+
// - `nullable: true` becomes `type: [..., "null"]` (and null joins an enum when one exists)
|
|
12
|
+
// - the singular `example` becomes the standard `examples` array
|
|
13
|
+
// - the `x-*` vendor extensions (x-meta, x-constraint, x-format, x-convert) are dropped -
|
|
14
|
+
// they carry joi rules for the API reference renderer, which no MCP client reads, and the
|
|
15
|
+
// spec reserves x-mcp-header for transport behavior, so unknown x- keys are noise at best.
|
|
16
|
+
// One of them is not renderer detail though: `x-meta.enumDescriptions` says what each value
|
|
17
|
+
// of an enum MEANS, which is the difference between a model picking a value and guessing
|
|
18
|
+
// one. It is folded into the description before the key goes, so the meanings survive in the
|
|
19
|
+
// one field every client shows.
|
|
20
|
+
//
|
|
21
|
+
// Everything else the converter emits (properties, required, enum, anyOf, minimum/maxLength and
|
|
22
|
+
// friends) is already valid 2020-12.
|
|
23
|
+
|
|
24
|
+
const { SchemaConverter } = require('../openapi/joi-schema');
|
|
25
|
+
|
|
26
|
+
function toJsonSchema(node) {
|
|
27
|
+
if (Array.isArray(node)) {
|
|
28
|
+
return node.map(entry => toJsonSchema(entry));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (!node || typeof node !== 'object') {
|
|
32
|
+
return node;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const result = {};
|
|
36
|
+
|
|
37
|
+
// Collected before the loop drops the key it lives on, and appended after the description is
|
|
38
|
+
// known - the two can arrive in either order.
|
|
39
|
+
const enumDescriptions = node['x-meta'] && node['x-meta'].enumDescriptions;
|
|
40
|
+
|
|
41
|
+
for (const [key, value] of Object.entries(node)) {
|
|
42
|
+
if (/^x-/.test(key)) {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
switch (key) {
|
|
47
|
+
case 'nullable':
|
|
48
|
+
// handled below, once `type` and `enum` are known
|
|
49
|
+
continue;
|
|
50
|
+
|
|
51
|
+
case 'example':
|
|
52
|
+
result.examples = [value];
|
|
53
|
+
continue;
|
|
54
|
+
|
|
55
|
+
case 'properties': {
|
|
56
|
+
const mapped = {};
|
|
57
|
+
for (const [property, schema] of Object.entries(value)) {
|
|
58
|
+
mapped[property] = toJsonSchema(schema);
|
|
59
|
+
}
|
|
60
|
+
result[key] = mapped;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The only nesting keywords the converter emits: alternatives and .when() collapse
|
|
65
|
+
// into anyOf, array items stay items. Nothing produces allOf/oneOf/not.
|
|
66
|
+
case 'items':
|
|
67
|
+
case 'anyOf':
|
|
68
|
+
result[key] = toJsonSchema(value);
|
|
69
|
+
continue;
|
|
70
|
+
|
|
71
|
+
default:
|
|
72
|
+
result[key] = value;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (enumDescriptions && typeof enumDescriptions === 'object') {
|
|
77
|
+
// Only the values this schema actually offers, in the order it offers them, so a shared
|
|
78
|
+
// table describing more values than one field accepts cannot widen it in the prose
|
|
79
|
+
const described = (Array.isArray(result.enum) ? result.enum : Object.keys(enumDescriptions))
|
|
80
|
+
.filter(value => enumDescriptions[value])
|
|
81
|
+
.map(value => `"${value}" - ${enumDescriptions[value]}`);
|
|
82
|
+
|
|
83
|
+
if (described.length) {
|
|
84
|
+
result.description = `${result.description ? `${result.description}. ` : ''}${described.join('; ')}`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (node.nullable === true) {
|
|
89
|
+
if (typeof result.type === 'string') {
|
|
90
|
+
result.type = [result.type, 'null'];
|
|
91
|
+
} else if (Array.isArray(result.anyOf)) {
|
|
92
|
+
// alternatives().allow(null): the converter parks nullable next to anyOf, where
|
|
93
|
+
// there is no type keyword to widen - null becomes one more accepted branch
|
|
94
|
+
result.anyOf = result.anyOf.concat({ type: 'null' });
|
|
95
|
+
}
|
|
96
|
+
if (Array.isArray(result.enum) && !result.enum.includes(null)) {
|
|
97
|
+
result.enum = result.enum.concat(null);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Converts a compiled joi schema into a JSON Schema object for an MCP tool definition.
|
|
106
|
+
*
|
|
107
|
+
* @param {Object} schema - a joi schema
|
|
108
|
+
* @returns {Object|undefined} JSON Schema, or undefined when the schema documents nothing
|
|
109
|
+
*/
|
|
110
|
+
function joiToJsonSchema(schema) {
|
|
111
|
+
if (!schema || typeof schema.describe !== 'function') {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const converted = new SchemaConverter().convert(schema, { useDefinitions: false });
|
|
116
|
+
|
|
117
|
+
return converted ? toJsonSchema(converted) : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = { joiToJsonSchema };
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// subscriptions/listen: the long-lived notification stream of the modern (2026-07-28) protocol
|
|
4
|
+
// revision, bridged from the account state-change fanout that already feeds /v1/changes and the
|
|
5
|
+
// admin dashboard.
|
|
6
|
+
//
|
|
7
|
+
// What is honored, and why only this: `resourceSubscriptions` on account resource URIs
|
|
8
|
+
// (emailengine://account/{id}), delivered as notifications/resources/updated whenever that
|
|
9
|
+
// account's state changes. The other filter fields are omitted from the acknowledgment, which
|
|
10
|
+
// per the spec means "not honored": the tool list is static for the life of the worker, so
|
|
11
|
+
// toolsListChanged would never fire, and prompts do not exist here.
|
|
12
|
+
//
|
|
13
|
+
// Authorization is per subscribed account, enforced by injecting GET /v1/account/{account} with
|
|
14
|
+
// the caller's own credential at accept time - a URI the credential cannot read is silently
|
|
15
|
+
// dropped from the acknowledged subset, exactly as the spec expects unsupported entries to be.
|
|
16
|
+
// This deliberately reuses the REST enforcement rather than inventing a subscription-specific
|
|
17
|
+
// rule; the acknowledgment tells the client what survived.
|
|
18
|
+
//
|
|
19
|
+
// Every stream lives in the API worker that accepted it. The main thread already fans account
|
|
20
|
+
// state changes out to every API worker for the admin SSE feed, so with multiple API workers
|
|
21
|
+
// each one feeds its own streams and nothing needs affinity.
|
|
22
|
+
|
|
23
|
+
const { openSseStream } = require('../response-stream');
|
|
24
|
+
const { apiInject } = require('./inject');
|
|
25
|
+
const { accountUri, parseAccountUri } = require('./resources');
|
|
26
|
+
|
|
27
|
+
// Live MCP listen streams in this worker. Deliberately not the change-feed registry in
|
|
28
|
+
// lib/response-stream.js: these streams carry JSON-RPC frames, and the two fanouts must not
|
|
29
|
+
// receive each other's messages.
|
|
30
|
+
const mcpListenStreams = new Set();
|
|
31
|
+
|
|
32
|
+
const META_SUBSCRIPTION_ID = 'io.modelcontextprotocol/subscriptionId';
|
|
33
|
+
|
|
34
|
+
// Accept-time authorization injects one full API request per subscribed URI - token read,
|
|
35
|
+
// permission check, account read - so a listen request is an amplifier by construction. Three
|
|
36
|
+
// bounds keep it one: how many URIs a request may name, how many of those checks run at once,
|
|
37
|
+
// and how many streams a single credential may hold open.
|
|
38
|
+
//
|
|
39
|
+
// The stream cap counts what THIS worker holds, because that is what the registry below can see -
|
|
40
|
+
// with EENGINE_WORKERS_API above 1 a credential can hold the cap on each of them. That is the
|
|
41
|
+
// right bound anyway: the cost this limits is per-worker (the registry walk on every fanout, the
|
|
42
|
+
// sockets on that process), and nothing here needs an instance-wide count.
|
|
43
|
+
const MAX_RESOURCE_SUBSCRIPTIONS = 20;
|
|
44
|
+
const AUTH_CHECK_CONCURRENCY = 5;
|
|
45
|
+
const MAX_STREAMS_PER_CREDENTIAL = 4;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The credential a stream belongs to, for the per-credential stream cap. Token records are keyed
|
|
49
|
+
* by their hash; the `preauth` caller of the disableTokens mode has no record and shares one
|
|
50
|
+
* bucket, which is correct - it is one anonymous caller as far as this instance can tell.
|
|
51
|
+
*/
|
|
52
|
+
function credentialId(request) {
|
|
53
|
+
return (request.auth && request.auth.artifacts && request.auth.artifacts.id) || 'preauth';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Whether this credential may open another listen stream on this worker.
|
|
58
|
+
*/
|
|
59
|
+
function canOpenListenStream(request) {
|
|
60
|
+
const id = credentialId(request);
|
|
61
|
+
let open = 0;
|
|
62
|
+
for (const stream of mcpListenStreams) {
|
|
63
|
+
if (stream.mcpSubscription && stream.mcpSubscription.credentialId === id) {
|
|
64
|
+
open++;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return open < MAX_STREAMS_PER_CREDENTIAL;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Validates a requested notification filter against what the caller may actually see.
|
|
72
|
+
*
|
|
73
|
+
* @returns {Promise<Object>} the acknowledged filter subset
|
|
74
|
+
*/
|
|
75
|
+
async function acceptFilter({ server, request, filter }) {
|
|
76
|
+
const accepted = {};
|
|
77
|
+
|
|
78
|
+
const requested = Array.isArray(filter.resourceSubscriptions) ? filter.resourceSubscriptions.slice(0, MAX_RESOURCE_SUBSCRIPTIONS) : [];
|
|
79
|
+
|
|
80
|
+
const accounts = [...new Set(requested.map(uri => parseAccountUri(uri)).filter(Boolean))];
|
|
81
|
+
|
|
82
|
+
// Independent yes/no checks about separate accounts, so they run concurrently - serialized,
|
|
83
|
+
// a broad subscription would pay one full request pipeline per URI in connect latency. In
|
|
84
|
+
// batches rather than all at once: every check is a full injected request, and one client
|
|
85
|
+
// should not be able to put twenty of those in flight with a single POST.
|
|
86
|
+
const uris = [];
|
|
87
|
+
for (let pos = 0; pos < accounts.length; pos += AUTH_CHECK_CONCURRENCY) {
|
|
88
|
+
const batch = accounts.slice(pos, pos + AUTH_CHECK_CONCURRENCY);
|
|
89
|
+
const admitted = await Promise.all(
|
|
90
|
+
batch.map(async account => {
|
|
91
|
+
const res = await apiInject({ server, request, method: 'get', url: `/v1/account/${encodeURIComponent(account)}` });
|
|
92
|
+
return res.statusCode < 400 ? accountUri(account) : null;
|
|
93
|
+
})
|
|
94
|
+
);
|
|
95
|
+
uris.push(...admitted.filter(Boolean));
|
|
96
|
+
}
|
|
97
|
+
if (uris.length) {
|
|
98
|
+
accepted.resourceSubscriptions = uris;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return accepted;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Opens the SSE response stream for an accepted subscriptions/listen request.
|
|
106
|
+
*
|
|
107
|
+
* @param {Object} opts
|
|
108
|
+
* @param {Object} opts.h - Hapi response toolkit
|
|
109
|
+
* @param {Object} opts.request - the /mcp request, for the credential the stream is counted under
|
|
110
|
+
* @param {*} opts.subscriptionId - the JSON-RPC id of the subscriptions/listen request
|
|
111
|
+
* @param {Object} opts.accepted - the acknowledged filter subset from acceptFilter()
|
|
112
|
+
* @returns {Object} Hapi response
|
|
113
|
+
*/
|
|
114
|
+
function openListenStream({ h, request, subscriptionId, accepted }) {
|
|
115
|
+
const { stream, response } = openSseStream(h, {
|
|
116
|
+
registry: mcpListenStreams,
|
|
117
|
+
onOpen: opened =>
|
|
118
|
+
opened.sendMessage({
|
|
119
|
+
jsonrpc: '2.0',
|
|
120
|
+
method: 'notifications/subscriptions/acknowledged',
|
|
121
|
+
params: {
|
|
122
|
+
_meta: { [META_SUBSCRIPTION_ID]: subscriptionId },
|
|
123
|
+
notifications: accepted
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
stream.mcpSubscription = {
|
|
129
|
+
id: subscriptionId,
|
|
130
|
+
credentialId: credentialId(request),
|
|
131
|
+
resourceUris: new Set(accepted.resourceSubscriptions || [])
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
return response;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Fans one account state-change event out to the listen streams that subscribed to it.
|
|
139
|
+
* Called from the API worker's 'change' message handler, alongside the admin feed fanout.
|
|
140
|
+
*/
|
|
141
|
+
function publishAccountChange(data, logger) {
|
|
142
|
+
if (!mcpListenStreams.size || !data || !data.account) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const uri = accountUri(data.account);
|
|
147
|
+
|
|
148
|
+
for (const stream of mcpListenStreams) {
|
|
149
|
+
const subscription = stream.mcpSubscription;
|
|
150
|
+
if (!subscription || !subscription.resourceUris.has(uri)) {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
stream.sendMessage({
|
|
156
|
+
jsonrpc: '2.0',
|
|
157
|
+
method: 'notifications/resources/updated',
|
|
158
|
+
params: {
|
|
159
|
+
_meta: { [META_SUBSCRIPTION_ID]: subscription.id },
|
|
160
|
+
uri
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
} catch (err) {
|
|
164
|
+
if (logger) {
|
|
165
|
+
logger.warn({ msg: 'Failed to publish MCP resource update', err, account: data.account });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
module.exports = { acceptFilter, openListenStream, publishAccountChange, canOpenListenStream, MAX_STREAMS_PER_CREDENTIAL, MAX_RESOURCE_SUBSCRIPTIONS };
|
package/lib/mcp/oauth.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The minimal OAuth 2.1 authorization server behind the MCP endpoint.
|
|
4
|
+
//
|
|
5
|
+
// It exists for exactly one flow: an MCP client that cannot be configured with a static access
|
|
6
|
+
// token (claude.ai web connectors and similar) discovers this server through the protected
|
|
7
|
+
// resource metadata, registers itself as a public client, sends the operator's browser to the
|
|
8
|
+
// admin consent page, and exchanges the resulting code for an EmailEngine access token with the
|
|
9
|
+
// `mcp` scope. Every credential this issues is an ordinary access token: visible on the admin
|
|
10
|
+
// tokens page, revocable there, and bounded by SURFACE_GRANTS.mcp like any other mcp-scoped
|
|
11
|
+
// token. There are no refresh tokens and no expiry by default - revocation is the lifecycle.
|
|
12
|
+
//
|
|
13
|
+
// What is implemented, spec-wise: OAuth 2.0 Dynamic Client Registration (RFC 7591, open
|
|
14
|
+
// registration for public clients only, rate limited per IP), authorization code + PKCE S256
|
|
15
|
+
// (OAuth 2.1 - PKCE is mandatory, `plain` is not accepted), single-use codes with a short TTL,
|
|
16
|
+
// exact-match redirect URIs, RFC 8707 resource validation against this instance's canonical
|
|
17
|
+
// MCP resource, and the RFC 9207 `iss` authorization-response parameter. Client secrets do not
|
|
18
|
+
// exist here: `token_endpoint_auth_method` is always `none`, which is what PKCE is for.
|
|
19
|
+
|
|
20
|
+
const crypto = require('crypto');
|
|
21
|
+
|
|
22
|
+
const { redis } = require('../db');
|
|
23
|
+
const { REDIS_PREFIX } = require('../consts');
|
|
24
|
+
const msgpack = require('../msgpack');
|
|
25
|
+
const tokens = require('../tokens');
|
|
26
|
+
const settings = require('../settings');
|
|
27
|
+
const { constantTimeEqual } = require('../tools');
|
|
28
|
+
const { mcpFeatureEnabled } = require('./index');
|
|
29
|
+
const { LOOPBACK_HOSTNAMES } = require('./protocol');
|
|
30
|
+
|
|
31
|
+
// Registered clients and pending codes are throwaway state, not configuration: an unused client
|
|
32
|
+
// registration disappears after this long, and re-registering is one unauthenticated call. The
|
|
33
|
+
// TTL is refreshed whenever the client starts an authorization, so an actively used client id
|
|
34
|
+
// stays stable.
|
|
35
|
+
const CLIENT_TTL = 30 * 24 * 3600;
|
|
36
|
+
|
|
37
|
+
// An authorization code is redeemed within seconds in a working flow; ten minutes is the
|
|
38
|
+
// conventional upper bound.
|
|
39
|
+
const CODE_TTL = 10 * 60;
|
|
40
|
+
|
|
41
|
+
// How many redirect URIs one registration may carry. Consumed by the registration route's joi
|
|
42
|
+
// schema too, so the validation layer and the policy here cannot drift apart.
|
|
43
|
+
const MAX_REDIRECT_URIS = 10;
|
|
44
|
+
|
|
45
|
+
const clientKey = clientId => `${REDIS_PREFIX}mcp:oauth:client:${clientId}`;
|
|
46
|
+
const codeKey = code => `${REDIS_PREFIX}mcp:oauth:code:${code}`;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Whether the OAuth flow is available at all: the MCP endpoint must be live, the feature
|
|
50
|
+
* enabled, and a serviceUrl configured - the metadata documents have to name a canonical origin,
|
|
51
|
+
* which a request-derived address cannot provide.
|
|
52
|
+
*
|
|
53
|
+
* @returns {Promise<String|false>} the canonical origin, or false
|
|
54
|
+
*/
|
|
55
|
+
async function oauthOrigin() {
|
|
56
|
+
if (!mcpFeatureEnabled) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// One HMGET for the three settings the answer depends on, not three serialized reads - this
|
|
61
|
+
// runs on every discovery request and on every /mcp 401
|
|
62
|
+
const stored = await settings.getMulti('mcpEnabled', 'mcpOAuthEnabled', 'serviceUrl');
|
|
63
|
+
if (!stored.mcpEnabled || !stored.mcpOAuthEnabled || !stored.serviceUrl) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
return new URL(stored.serviceUrl).origin;
|
|
69
|
+
} catch (err) {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function mcpResource(origin) {
|
|
75
|
+
return `${origin}/mcp`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A redirect URI a public MCP client may register: https anywhere, http only on the loopback
|
|
80
|
+
* (native clients binding a local callback port), or a private-use scheme (desktop apps).
|
|
81
|
+
* Schemes that execute in a browser context are refused outright.
|
|
82
|
+
*/
|
|
83
|
+
function isAcceptableRedirectUri(value) {
|
|
84
|
+
if (typeof value !== 'string' || value.length > 2048) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
let url;
|
|
89
|
+
try {
|
|
90
|
+
url = new URL(value);
|
|
91
|
+
} catch (err) {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (url.hash) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
switch (url.protocol) {
|
|
100
|
+
case 'https:':
|
|
101
|
+
return true;
|
|
102
|
+
case 'http:':
|
|
103
|
+
return LOOPBACK_HOSTNAMES.includes(url.hostname);
|
|
104
|
+
case 'javascript:':
|
|
105
|
+
case 'data:':
|
|
106
|
+
case 'file:':
|
|
107
|
+
case 'blob:':
|
|
108
|
+
case 'vbscript:':
|
|
109
|
+
return false;
|
|
110
|
+
default:
|
|
111
|
+
// Anything else is treated as a private-use scheme (com.example.app:/callback,
|
|
112
|
+
// RFC 8252 territory). The URL parser already guarantees scheme syntax, so beyond
|
|
113
|
+
// the browser-context schemes named above there is nothing left to filter.
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Registers a public client (RFC 7591).
|
|
120
|
+
*
|
|
121
|
+
* @param {Object} opts
|
|
122
|
+
* @param {Array} opts.redirectUris
|
|
123
|
+
* @param {String} [opts.clientName]
|
|
124
|
+
* @returns {Promise<Object>} the stored client record
|
|
125
|
+
*/
|
|
126
|
+
async function registerClient({ redirectUris, clientName }) {
|
|
127
|
+
const uris = [].concat(redirectUris || []);
|
|
128
|
+
|
|
129
|
+
if (!uris.length || uris.length > MAX_REDIRECT_URIS) {
|
|
130
|
+
throw oauthFailure('invalid_redirect_uri', `redirect_uris must list 1-${MAX_REDIRECT_URIS} redirect URIs`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Any unacceptable URI fails the whole registration (RFC 7591 3.2.2). Silently registering
|
|
134
|
+
// the acceptable subset was tried first, and it just moved the failure to authorize time,
|
|
135
|
+
// where the client sees a generic error page instead of which URI was refused and why.
|
|
136
|
+
const refused = uris.find(uri => !isAcceptableRedirectUri(uri));
|
|
137
|
+
if (refused !== undefined) {
|
|
138
|
+
throw oauthFailure(
|
|
139
|
+
'invalid_redirect_uri',
|
|
140
|
+
`Unacceptable redirect URI (must be https, loopback http, or a private-use scheme): ${String(refused).slice(0, 256)}`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const client = {
|
|
145
|
+
client_id: crypto.randomBytes(16).toString('hex'),
|
|
146
|
+
client_id_issued_at: Math.floor(Date.now() / 1000),
|
|
147
|
+
redirect_uris: uris,
|
|
148
|
+
token_endpoint_auth_method: 'none',
|
|
149
|
+
grant_types: ['authorization_code'],
|
|
150
|
+
response_types: ['code'],
|
|
151
|
+
client_name: (clientName || '').toString().slice(0, 256) || undefined
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
await redis.set(clientKey(client.client_id), msgpack.encode(client), 'EX', CLIENT_TTL);
|
|
155
|
+
|
|
156
|
+
return client;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function getClient(clientId) {
|
|
160
|
+
if (!/^[0-9a-f]{32}$/.test(clientId || '')) {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const encoded = await redis.getBuffer(clientKey(clientId));
|
|
165
|
+
if (!encoded) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
return msgpack.decode(encoded);
|
|
171
|
+
} catch (err) {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// A client that reached the consent page is in active use; keep its registration alive
|
|
177
|
+
async function touchClient(clientId) {
|
|
178
|
+
await redis.expire(clientKey(clientId), CLIENT_TTL);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Trailing slashes carry no meaning for a resource identifier, so every comparison below runs
|
|
182
|
+
// on the stripped form
|
|
183
|
+
function normalizeResource(resource) {
|
|
184
|
+
return typeof resource === 'string' ? resource.replace(/\/+$/, '') : resource;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Validates the resource indicator (RFC 8707) against this instance's canonical MCP resource.
|
|
189
|
+
* Absent is tolerated for interoperability; a present value has to name this instance.
|
|
190
|
+
*/
|
|
191
|
+
function isAcceptableResource(resource, origin) {
|
|
192
|
+
if (resource === undefined || resource === null || resource === '') {
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
if (typeof resource !== 'string') {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const normalized = normalizeResource(resource);
|
|
200
|
+
|
|
201
|
+
return normalized === mcpResource(origin) || normalized === origin;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Mints a single-use authorization code after the admin approved the consent page.
|
|
206
|
+
*
|
|
207
|
+
* @param {Object} opts - clientId, redirectUri, codeChallenge, resource, account (optional
|
|
208
|
+
* binding for the token), description (for the admin tokens listing)
|
|
209
|
+
* @returns {Promise<String>} the code
|
|
210
|
+
*/
|
|
211
|
+
async function createAuthorizationCode(opts) {
|
|
212
|
+
const code = crypto.randomBytes(32).toString('base64url');
|
|
213
|
+
|
|
214
|
+
const record = {
|
|
215
|
+
clientId: opts.clientId,
|
|
216
|
+
redirectUri: opts.redirectUri,
|
|
217
|
+
codeChallenge: opts.codeChallenge,
|
|
218
|
+
resource: opts.resource || null,
|
|
219
|
+
account: opts.account || null,
|
|
220
|
+
// The narrowing the operator approved, applied to the token this code mints. Absent
|
|
221
|
+
// means unnarrowed within the mcp scope, the same shape the admin generator posts.
|
|
222
|
+
permissions: opts.permissions || null,
|
|
223
|
+
description: opts.description,
|
|
224
|
+
created: Date.now()
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
await redis.set(codeKey(code), msgpack.encode(record), 'EX', CODE_TTL);
|
|
228
|
+
|
|
229
|
+
return code;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function oauthFailure(error, description) {
|
|
233
|
+
const err = new Error(description);
|
|
234
|
+
err.oauthError = error;
|
|
235
|
+
return err;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function verifyPkce(codeVerifier, codeChallenge) {
|
|
239
|
+
// RFC 7636 verifier alphabet and length, then S256
|
|
240
|
+
if (typeof codeVerifier !== 'string' || codeVerifier.length < 43 || codeVerifier.length > 128 || !/^[A-Za-z0-9\-._~]+$/.test(codeVerifier)) {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const digest = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
|
|
245
|
+
|
|
246
|
+
return constantTimeEqual(digest, codeChallenge);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* The token endpoint's whole job: redeem a code for an access token.
|
|
251
|
+
*
|
|
252
|
+
* @param {Object} opts - code, clientId, redirectUri, codeVerifier, resource, origin, ip
|
|
253
|
+
* @returns {Promise<Object>} OAuth token response body
|
|
254
|
+
*/
|
|
255
|
+
async function redeemAuthorizationCode({ code, clientId, redirectUri, codeVerifier, resource, origin, ip }) {
|
|
256
|
+
if (typeof code !== 'string' || code.length > 256) {
|
|
257
|
+
throw oauthFailure('invalid_grant', 'Unknown authorization code');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Single use by construction: whoever gets the record, gets it deleted
|
|
261
|
+
const encoded = await redis.getdelBuffer(codeKey(code));
|
|
262
|
+
if (!encoded) {
|
|
263
|
+
throw oauthFailure('invalid_grant', 'Unknown or expired authorization code');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
let record;
|
|
267
|
+
try {
|
|
268
|
+
record = msgpack.decode(encoded);
|
|
269
|
+
} catch (err) {
|
|
270
|
+
throw oauthFailure('invalid_grant', 'Unknown or expired authorization code');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (record.clientId !== clientId) {
|
|
274
|
+
throw oauthFailure('invalid_grant', 'Authorization code was issued to another client');
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (record.redirectUri !== redirectUri) {
|
|
278
|
+
throw oauthFailure('invalid_grant', 'redirect_uri does not match the authorization request');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (!verifyPkce(codeVerifier, record.codeChallenge)) {
|
|
282
|
+
throw oauthFailure('invalid_grant', 'PKCE verification failed');
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (!isAcceptableResource(resource, origin)) {
|
|
286
|
+
throw oauthFailure('invalid_target', 'The resource parameter does not name this server');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// RFC 8707: a code issued for a resource named at authorization time is redeemed for that
|
|
290
|
+
// same resource. Absence stays tolerated on either side for interoperability - only one
|
|
291
|
+
// resource exists on this server, so this catches client confusion, not a privilege step.
|
|
292
|
+
if (resource && record.resource && normalizeResource(resource) !== normalizeResource(record.resource)) {
|
|
293
|
+
throw oauthFailure('invalid_target', 'The resource parameter does not match the authorization request');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const token = await tokens.provision({
|
|
297
|
+
account: record.account || undefined,
|
|
298
|
+
description: record.description,
|
|
299
|
+
scopes: ['mcp'],
|
|
300
|
+
permissions: record.permissions || undefined,
|
|
301
|
+
ip,
|
|
302
|
+
metadata: JSON.stringify({ issuer: 'mcp-oauth', client: record.clientId })
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
access_token: token,
|
|
307
|
+
token_type: 'Bearer',
|
|
308
|
+
scope: 'mcp'
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
module.exports = {
|
|
313
|
+
oauthOrigin,
|
|
314
|
+
mcpResource,
|
|
315
|
+
registerClient,
|
|
316
|
+
getClient,
|
|
317
|
+
touchClient,
|
|
318
|
+
isAcceptableRedirectUri,
|
|
319
|
+
isAcceptableResource,
|
|
320
|
+
createAuthorizationCode,
|
|
321
|
+
redeemAuthorizationCode,
|
|
322
|
+
verifyPkce,
|
|
323
|
+
MAX_REDIRECT_URIS
|
|
324
|
+
};
|