@terreno/api 57.16.2 → 57.18.0
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/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
package/dist/githubAuth.js
CHANGED
|
@@ -4,7 +4,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.addGitHubAuthRoutes = exports.setupGitHubAuth = exports.githubUserPlugin = void 0;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
7
8
|
const express_1 = require("express");
|
|
9
|
+
const luxon_1 = require("luxon");
|
|
8
10
|
const passport_1 = __importDefault(require("passport"));
|
|
9
11
|
const passport_github2_1 = require("passport-github2");
|
|
10
12
|
const auth_1 = require("./auth");
|
|
@@ -39,6 +41,175 @@ const githubUserPlugin = (schema) => {
|
|
|
39
41
|
});
|
|
40
42
|
};
|
|
41
43
|
exports.githubUserPlugin = githubUserPlugin;
|
|
44
|
+
/** Cookie that binds a GitHub OAuth flow to the browser that started it. */
|
|
45
|
+
const GITHUB_STATE_COOKIE = "terreno_github_oauth_state";
|
|
46
|
+
/** How long a started GitHub OAuth flow stays valid. */
|
|
47
|
+
const GITHUB_STATE_TTL_MINUTES = 10;
|
|
48
|
+
const STATE_VERIFY_FAILURE = { message: "Unable to verify authorization request state." };
|
|
49
|
+
// Link targets read from verified state, keyed by request so no request input can set one.
|
|
50
|
+
const verifiedLinkTargets = new WeakMap();
|
|
51
|
+
const getStateSecret = () => {
|
|
52
|
+
const secret = process.env.SESSION_SECRET || process.env.TOKEN_SECRET;
|
|
53
|
+
if (!secret) {
|
|
54
|
+
throw new errors_1.APIError({
|
|
55
|
+
status: 500,
|
|
56
|
+
title: "SESSION_SECRET or TOKEN_SECRET must be set for GitHub OAuth.",
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return secret;
|
|
60
|
+
};
|
|
61
|
+
const signStatePayload = (payload) => {
|
|
62
|
+
return (0, node_crypto_1.createHmac)("sha256", getStateSecret()).update(payload).digest("base64url");
|
|
63
|
+
};
|
|
64
|
+
const safeEqual = (a, b) => {
|
|
65
|
+
const aBuffer = Buffer.from(a);
|
|
66
|
+
const bBuffer = Buffer.from(b);
|
|
67
|
+
if (aBuffer.length !== bBuffer.length) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return (0, node_crypto_1.timingSafeEqual)(aBuffer, bBuffer);
|
|
71
|
+
};
|
|
72
|
+
const readCookie = (req, name) => {
|
|
73
|
+
const header = req.headers?.cookie;
|
|
74
|
+
if (!header) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
for (const part of header.split(";")) {
|
|
78
|
+
const [rawName, ...rest] = part.trim().split("=");
|
|
79
|
+
if (rawName === name) {
|
|
80
|
+
try {
|
|
81
|
+
return decodeURIComponent(rest.join("="));
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return undefined;
|
|
89
|
+
};
|
|
90
|
+
const parseStateCookie = (raw) => {
|
|
91
|
+
if (!raw) {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
const [payload, signature, ...extra] = raw.split(".");
|
|
95
|
+
if (!payload || !signature || extra.length > 0) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
if (!safeEqual(signature, signStatePayload(payload))) {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
103
|
+
if (!parsed || typeof parsed !== "object") {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
const { expiresAt, linkUserId, nonce } = parsed;
|
|
107
|
+
if (typeof expiresAt !== "number" || typeof nonce !== "string") {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
if (linkUserId !== undefined && typeof linkUserId !== "string") {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
return { expiresAt, linkUserId, nonce };
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const isHttpsUrl = (value) => {
|
|
120
|
+
try {
|
|
121
|
+
return new URL(value).protocol === "https:";
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* passport-oauth2 state store backed by a signed, HttpOnly, SameSite=Lax cookie. `store` issues a
|
|
129
|
+
* nonce for the `state` parameter and records it (and the link target for /auth/github/link) in
|
|
130
|
+
* the cookie; `verify` accepts the callback only when the cookie is intact, unexpired, and holds
|
|
131
|
+
* the same nonce. The cookie is single use.
|
|
132
|
+
*/
|
|
133
|
+
const createSignedCookieStateStore = (callbackURL) => {
|
|
134
|
+
const callbackIsHttps = isHttpsUrl(callbackURL);
|
|
135
|
+
const cookieOptions = (req) => ({
|
|
136
|
+
httpOnly: true,
|
|
137
|
+
path: "/",
|
|
138
|
+
sameSite: "lax",
|
|
139
|
+
secure: callbackIsHttps ?? req.secure,
|
|
140
|
+
});
|
|
141
|
+
return {
|
|
142
|
+
store: (req, state, _meta, callback) => {
|
|
143
|
+
if (!req.res) {
|
|
144
|
+
callback(new Error("GitHub OAuth state requires an Express response"));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
const linkUserId = state && typeof state === "object" && "linkUserId" in state
|
|
148
|
+
? String(state.linkUserId)
|
|
149
|
+
: undefined;
|
|
150
|
+
const nonce = (0, node_crypto_1.randomBytes)(24).toString("base64url");
|
|
151
|
+
const record = {
|
|
152
|
+
expiresAt: luxon_1.DateTime.now().plus({ minutes: GITHUB_STATE_TTL_MINUTES }).toMillis(),
|
|
153
|
+
nonce,
|
|
154
|
+
...(linkUserId ? { linkUserId } : {}),
|
|
155
|
+
};
|
|
156
|
+
const payload = Buffer.from(JSON.stringify(record)).toString("base64url");
|
|
157
|
+
req.res.cookie(GITHUB_STATE_COOKIE, `${payload}.${signStatePayload(payload)}`, {
|
|
158
|
+
...cookieOptions(req),
|
|
159
|
+
maxAge: GITHUB_STATE_TTL_MINUTES * 60 * 1000,
|
|
160
|
+
});
|
|
161
|
+
callback(null, nonce);
|
|
162
|
+
},
|
|
163
|
+
verify: (req, providedState, _meta, callback) => {
|
|
164
|
+
const record = parseStateCookie(readCookie(req, GITHUB_STATE_COOKIE));
|
|
165
|
+
req.res?.clearCookie(GITHUB_STATE_COOKIE, cookieOptions(req));
|
|
166
|
+
if (!record || typeof providedState !== "string") {
|
|
167
|
+
callback(null, false, STATE_VERIFY_FAILURE);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (record.expiresAt <= luxon_1.DateTime.now().toMillis()) {
|
|
171
|
+
callback(null, false, STATE_VERIFY_FAILURE);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (!safeEqual(record.nonce, providedState)) {
|
|
175
|
+
callback(null, false, STATE_VERIFY_FAILURE);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (record.linkUserId) {
|
|
179
|
+
verifiedLinkTargets.set(req, record.linkUserId);
|
|
180
|
+
}
|
|
181
|
+
callback(null, true);
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
// http(s) targets compare by origin; custom schemes compare by scheme plus authority.
|
|
186
|
+
const returnToKey = (value) => {
|
|
187
|
+
let url;
|
|
188
|
+
try {
|
|
189
|
+
url = new URL(value);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
if (url.protocol === "http:" || url.protocol === "https:") {
|
|
195
|
+
return url.origin.toLowerCase();
|
|
196
|
+
}
|
|
197
|
+
if (!url.host || url.username || url.password) {
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
return `${url.protocol}//${url.host}`.toLowerCase();
|
|
201
|
+
};
|
|
202
|
+
/** Whether `value` is a redirect target the operator allowed in `allowedReturnTo`. */
|
|
203
|
+
const isAllowedReturnTo = (value, allowed) => {
|
|
204
|
+
if (typeof value !== "string" || !allowed?.length) {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
const key = returnToKey(value);
|
|
208
|
+
if (!key) {
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
return allowed.some((entry) => returnToKey(entry) === key);
|
|
212
|
+
};
|
|
42
213
|
/**
|
|
43
214
|
* Sets up GitHub OAuth authentication strategy.
|
|
44
215
|
* Call this after setupAuth() in your server initialization.
|
|
@@ -51,42 +222,44 @@ const setupGitHubAuth = (_app, userModel, githubOptions) => {
|
|
|
51
222
|
clientSecret: githubOptions.clientSecret,
|
|
52
223
|
passReqToCallback: true,
|
|
53
224
|
scope,
|
|
225
|
+
store: createSignedCookieStateStore(githubOptions.callbackURL),
|
|
54
226
|
}, async (req, accessToken, refreshToken, profile, done) => {
|
|
55
227
|
try {
|
|
56
|
-
|
|
228
|
+
// The link target comes only from state issued by /auth/github/link, never from an
|
|
229
|
+
// ambient session or token on the callback request.
|
|
230
|
+
const linkUserId = verifiedLinkTargets.get(req);
|
|
231
|
+
const linkUser = linkUserId ? await userModel.findById(linkUserId) : null;
|
|
232
|
+
if (linkUserId && !linkUser) {
|
|
233
|
+
return done(new errors_1.APIError({ status: 404, title: "User not found" }));
|
|
234
|
+
}
|
|
57
235
|
// If custom handler provided, use it
|
|
58
236
|
if (githubOptions.findOrCreateUser) {
|
|
59
|
-
const user = await githubOptions.findOrCreateUser(profile, accessToken, refreshToken,
|
|
237
|
+
const user = await githubOptions.findOrCreateUser(profile, accessToken, refreshToken, (linkUser ?? undefined));
|
|
60
238
|
return done(null, user);
|
|
61
239
|
}
|
|
62
240
|
// Default implementation
|
|
63
241
|
const githubId = profile.id;
|
|
64
242
|
// Check if user with this GitHub ID already exists
|
|
65
243
|
const existingGitHubUser = await (0, plugins_1.findOneOrNoneFor)(userModel, { githubId });
|
|
66
|
-
// Case 1:
|
|
67
|
-
if (
|
|
244
|
+
// Case 1: The user who started /auth/github/link is linking their GitHub account
|
|
245
|
+
if (linkUser) {
|
|
68
246
|
if (!githubOptions.allowAccountLinking) {
|
|
69
247
|
return done(new errors_1.APIError({ status: 400, title: "Account linking is disabled" }));
|
|
70
248
|
}
|
|
71
249
|
if (existingGitHubUser &&
|
|
72
|
-
existingGitHubUser._id.toString() !==
|
|
250
|
+
existingGitHubUser._id.toString() !== linkUser._id.toString()) {
|
|
73
251
|
return done(new errors_1.APIError({
|
|
74
252
|
status: 400,
|
|
75
253
|
title: "This GitHub account is already linked to another user",
|
|
76
254
|
}));
|
|
77
255
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
userWithGitHub.githubAvatarUrl = profile.photos?.[0]?.value;
|
|
86
|
-
await user.save();
|
|
87
|
-
return done(null, user);
|
|
88
|
-
}
|
|
89
|
-
return done(new errors_1.APIError({ status: 404, title: "User not found" }));
|
|
256
|
+
const userWithGitHub = linkUser;
|
|
257
|
+
userWithGitHub.githubId = githubId;
|
|
258
|
+
userWithGitHub.githubUsername = profile.username;
|
|
259
|
+
userWithGitHub.githubProfileUrl = profile.profileUrl;
|
|
260
|
+
userWithGitHub.githubAvatarUrl = profile.photos?.[0]?.value;
|
|
261
|
+
await linkUser.save();
|
|
262
|
+
return done(null, linkUser);
|
|
90
263
|
}
|
|
91
264
|
// Case 2: User with this GitHub ID exists - log them in
|
|
92
265
|
if (existingGitHubUser) {
|
|
@@ -146,34 +319,54 @@ const addGitHubAuthRoutes = (app, userModel, githubOptions, authOptions) => {
|
|
|
146
319
|
const router = (0, express_1.Router)();
|
|
147
320
|
// Initiate GitHub OAuth flow
|
|
148
321
|
router.get("/github", (req, _res, next) => {
|
|
149
|
-
// Store
|
|
322
|
+
// Store an allowlisted return URL in the session for the redirect after auth
|
|
150
323
|
const returnTo = req.query.returnTo;
|
|
151
|
-
if (returnTo) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
324
|
+
if (returnTo === undefined || returnTo === "") {
|
|
325
|
+
return next();
|
|
326
|
+
}
|
|
327
|
+
if (!githubOptions.allowedReturnTo?.length) {
|
|
328
|
+
logger_1.logger.warn("[github] Ignoring returnTo because githubAuth.allowedReturnTo is not set");
|
|
329
|
+
return next();
|
|
330
|
+
}
|
|
331
|
+
if (!isAllowedReturnTo(returnTo, githubOptions.allowedReturnTo)) {
|
|
332
|
+
return next(new errors_1.APIError({ status: 400, title: "returnTo is not an allowed redirect target" }));
|
|
155
333
|
}
|
|
156
|
-
|
|
334
|
+
const reqWithSession = req;
|
|
335
|
+
reqWithSession.session = reqWithSession.session ?? {};
|
|
336
|
+
reqWithSession.session.returnTo = returnTo;
|
|
337
|
+
return next();
|
|
157
338
|
}, passport_1.default.authenticate("github", { session: false }));
|
|
158
339
|
// GitHub OAuth callback
|
|
159
340
|
router.get("/github/callback", passport_1.default.authenticate("github", {
|
|
160
341
|
failureRedirect: "/auth/github/failure",
|
|
161
342
|
session: false,
|
|
162
343
|
}), async (req, res) => {
|
|
344
|
+
if ((0, auth_1.isUserDisabled)(req.user)) {
|
|
345
|
+
logger_1.logger.warn(`[github] Refusing GitHub login for disabled user ${req.user?._id}`);
|
|
346
|
+
return res.status(401).json({ status: 401, title: "User is disabled" });
|
|
347
|
+
}
|
|
163
348
|
try {
|
|
164
349
|
const tokens = await (0, auth_1.generateTokens)(req.user, authOptions);
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
350
|
+
const session = req.session;
|
|
351
|
+
const returnTo = session?.returnTo;
|
|
352
|
+
if (session && returnTo !== undefined) {
|
|
353
|
+
delete session.returnTo;
|
|
354
|
+
}
|
|
355
|
+
// Redirect only to an allowlisted target, with tokens in the fragment so they stay out
|
|
356
|
+
// of server logs and Referer headers
|
|
357
|
+
if (returnTo && isAllowedReturnTo(returnTo, githubOptions.allowedReturnTo)) {
|
|
169
358
|
const url = new URL(returnTo);
|
|
170
|
-
|
|
359
|
+
const fragment = new URLSearchParams({ token: tokens.token ?? "" });
|
|
171
360
|
if (tokens.refreshToken) {
|
|
172
|
-
|
|
361
|
+
fragment.set("refreshToken", tokens.refreshToken);
|
|
173
362
|
}
|
|
174
|
-
|
|
363
|
+
fragment.set("userId", req.user?._id ? String(req.user._id) : "");
|
|
364
|
+
url.hash = fragment.toString();
|
|
175
365
|
return res.redirect(url.toString());
|
|
176
366
|
}
|
|
367
|
+
if (returnTo) {
|
|
368
|
+
logger_1.logger.warn("[github] Not redirecting to a returnTo outside githubAuth.allowedReturnTo");
|
|
369
|
+
}
|
|
177
370
|
// Otherwise return JSON response
|
|
178
371
|
return res.json({
|
|
179
372
|
data: {
|
|
@@ -204,7 +397,13 @@ const addGitHubAuthRoutes = (app, userModel, githubOptions, authOptions) => {
|
|
|
204
397
|
req.user = user;
|
|
205
398
|
next();
|
|
206
399
|
})(req, res, next);
|
|
207
|
-
},
|
|
400
|
+
}, (req, res, next) => {
|
|
401
|
+
// Record the bearer-authenticated user in the signed state as the only link target.
|
|
402
|
+
passport_1.default.authenticate("github", {
|
|
403
|
+
session: false,
|
|
404
|
+
state: { linkUserId: String(req.user?._id) },
|
|
405
|
+
})(req, res, next);
|
|
406
|
+
});
|
|
208
407
|
// Unlink GitHub from user account
|
|
209
408
|
router.delete("/github/unlink", passport_1.default.authenticate("jwt", { session: false }), async (req, res) => {
|
|
210
409
|
if (!req.user) {
|
package/dist/index.d.ts
CHANGED
|
@@ -24,7 +24,9 @@ export { FRAMEWORK_MODEL_PUBLIC_NAMES, type FrameworkModelCompiledName, type Fra
|
|
|
24
24
|
export * from "./githubAuth";
|
|
25
25
|
export * from "./httpClient";
|
|
26
26
|
export * from "./logger";
|
|
27
|
-
export { extractUserFromHeaders, type MCPAuthContext } from "./mcp/auth";
|
|
27
|
+
export { extractAuthFromHeaders, extractUserFromHeaders, type MCPAuthContext, type MCPAuthResult, } from "./mcp/auth";
|
|
28
|
+
export { addMcpOAuthRoutes, type McpOAuthRoutesOptions } from "./mcp/oauth";
|
|
29
|
+
export { buildAuthorizationServerMetadata, buildProtectedResourceMetadata, type McpOAuthAppOption, type McpOAuthOptions, type ResolvedMcpOAuthOptions, resolveMcpOAuthOption, sendMcpOAuthChallenge, } from "./mcp/oauthMetadata";
|
|
28
30
|
export type { MCPCustomTool } from "./mcp/registry";
|
|
29
31
|
export { clearMCPRegistry, getMCPRegistry, registerMCPModel, registerMCPTool, updateMCPRegistryOptions, } from "./mcp/registry";
|
|
30
32
|
export { generateInputSchema, generateToolDescription } from "./mcp/schemaGenerator";
|
|
@@ -41,6 +43,10 @@ export * from "./migrations/schemaCatalog";
|
|
|
41
43
|
export * from "./migrations/types";
|
|
42
44
|
export * from "./models/consentForm";
|
|
43
45
|
export * from "./models/consentResponse";
|
|
46
|
+
export { McpOAuthAuthorization } from "./models/mcpOAuthAuthorization";
|
|
47
|
+
export { McpOAuthClient } from "./models/mcpOAuthClient";
|
|
48
|
+
export { McpOAuthRevokedFamily } from "./models/mcpOAuthRevokedFamily";
|
|
49
|
+
export { McpOAuthFamilyRevokedError, McpOAuthToken } from "./models/mcpOAuthToken";
|
|
44
50
|
export * from "./models/mcpServiceToken";
|
|
45
51
|
export * from "./models/notification";
|
|
46
52
|
export * from "./models/notificationPreference";
|
|
@@ -82,6 +88,7 @@ export * from "./rbac/scopes";
|
|
|
82
88
|
export * from "./rbac/statements";
|
|
83
89
|
export * from "./rbac/types";
|
|
84
90
|
export * from "./rbac/userPlugin";
|
|
91
|
+
export { assertCanWriteTargetUser, assertCanWriteUserIdentity, isRbacUserModelName, isWriteKeyForField, USER_IDENTITY_FIELDS, USER_UPDATE_IDENTITY_ACTION, } from "./rbac/userWriteGuards";
|
|
85
92
|
export { type AuthorizedEmitEntry, emitPayloadToAuthorizedRoom, emitSyncDeltaForChange, startChangeStreamWatcher, stopChangeStreamWatcher, } from "./realtime/changeStreamWatcher";
|
|
86
93
|
export { matchesQuery } from "./realtime/queryMatcher";
|
|
87
94
|
export { addQuerySubscription, clearQueryStore, computeQueryId, getQuerySubscriptionsForCollection, removeAllSocketQueries, removeQuerySubscription, } from "./realtime/queryStore";
|
|
@@ -118,6 +125,7 @@ export * from "./terrenoPlugin";
|
|
|
118
125
|
export * from "./transformers";
|
|
119
126
|
export * from "./types/consentForm";
|
|
120
127
|
export * from "./types/consentResponse";
|
|
128
|
+
export type { McpOAuthAuthorizationDocument, McpOAuthAuthorizationStatus, McpOAuthClientDocument, McpOAuthRevokedFamilyDocument, McpOAuthTokenDocument, } from "./types/mcpOAuth";
|
|
121
129
|
export * from "./utils";
|
|
122
130
|
export * from "./versionCheckPlugin";
|
|
123
131
|
export type { WebhookClaimArgs, WebhookClaimResult, WebhookIdempotencyStore, } from "./webhooks/idempotency/memoryStore";
|
package/dist/index.js
CHANGED
|
@@ -14,9 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
18
|
-
exports.
|
|
19
|
-
exports.z = exports.WebhooksApp = void 0;
|
|
17
|
+
exports.assertAllowed = exports.DEFAULT_WINDOW_MS = exports.DEFAULT_AUTH_MAX = exports.DEFAULT_API_MAX = exports.createRouteRateLimitMiddleware = exports.notificationsBeforeSend = exports.NotificationsApp = exports.getNotificationService = exports.createNotificationService = exports.configureNotificationService = exports.McpOAuthToken = exports.McpOAuthFamilyRevokedError = exports.McpOAuthRevokedFamily = exports.McpOAuthClient = exports.McpOAuthAuthorization = exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.resolveMcpServiceTokensOption = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.addMcpServiceTokenRoutes = exports.mountMCPServer = exports.generateToolDescription = exports.generateInputSchema = exports.updateMCPRegistryOptions = exports.registerMCPTool = exports.registerMCPModel = exports.getMCPRegistry = exports.clearMCPRegistry = exports.sendMcpOAuthChallenge = exports.resolveMcpOAuthOption = exports.buildProtectedResourceMetadata = exports.buildAuthorizationServerMetadata = exports.addMcpOAuthRoutes = exports.extractUserFromHeaders = exports.extractAuthFromHeaders = exports.publicFrameworkModelName = exports.FRAMEWORK_MODEL_PUBLIC_NAMES = exports.resetAuditRecorderForTests = exports.recordAuditEvent = exports.persistEnqueuedAuditEvent = exports.maybeRecordAdminAudit = exports.isAuditRecorderInstalled = exports.flushAuditRecorderForTests = exports.persistRbacAuditToAuditEvent = exports.createCloudTasksAuditEnqueue = exports.auditEnqueueFromEnv = exports.AUDIT_SECRET_HEADER = exports.createAuditEventModel = exports.AuditApp = void 0;
|
|
18
|
+
exports.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.updateRealtimeRegistryOptions = exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitPayloadToAuthorizedRoom = exports.USER_UPDATE_IDENTITY_ACTION = exports.USER_IDENTITY_FIELDS = exports.isWriteKeyForField = exports.isRbacUserModelName = exports.assertCanWriteUserIdentity = exports.assertCanWriteTargetUser = exports.rbacRouter = exports.terrenoDefaultRoles = exports.READ_ONLY_ROLE_PERMISSIONS = exports.organizationOperatorRole = exports.expandRolePermissions = exports.createRbacRoleModel = exports.ORG_ADMIN_PERMISSION_BUNDLE = exports.membershipOrgAdminPermissionSource = exports.MEMBERSHIP_ORG_ADMIN_PERMISSION_SOURCE_NAME = exports.backfillAdmins = exports.recordRbacAudit = exports.createRbacAuditModel = void 0;
|
|
19
|
+
exports.z = exports.WebhooksApp = exports.twilioSignature = exports.stripeSignature = exports.sendgridEventSignature = exports.hmacSignature = exports.createMemoryIdempotencyStore = exports.stripAdminBodyFields = exports.scrubAdminFields = exports.adminBodyFieldsToStrip = exports.SYSTEM_FIELD_PATHS = exports.nestDottedFieldDescriptions = exports.modelDescriptionToOpenApiSpec = exports.modelDescriptionToAdminFields = exports.fieldDescriptionToZodType = exports.fieldDescriptionToOpenApiProperty = exports.fieldDescriptionToAdminMeta = exports.describeModelForRouter = exports.describeModel = void 0;
|
|
20
20
|
__exportStar(require("./actions"), exports);
|
|
21
21
|
__exportStar(require("./adminTypes"), exports);
|
|
22
22
|
__exportStar(require("./api"), exports);
|
|
@@ -58,7 +58,15 @@ __exportStar(require("./githubAuth"), exports);
|
|
|
58
58
|
__exportStar(require("./httpClient"), exports);
|
|
59
59
|
__exportStar(require("./logger"), exports);
|
|
60
60
|
var auth_1 = require("./mcp/auth");
|
|
61
|
+
Object.defineProperty(exports, "extractAuthFromHeaders", { enumerable: true, get: function () { return auth_1.extractAuthFromHeaders; } });
|
|
61
62
|
Object.defineProperty(exports, "extractUserFromHeaders", { enumerable: true, get: function () { return auth_1.extractUserFromHeaders; } });
|
|
63
|
+
var oauth_1 = require("./mcp/oauth");
|
|
64
|
+
Object.defineProperty(exports, "addMcpOAuthRoutes", { enumerable: true, get: function () { return oauth_1.addMcpOAuthRoutes; } });
|
|
65
|
+
var oauthMetadata_1 = require("./mcp/oauthMetadata");
|
|
66
|
+
Object.defineProperty(exports, "buildAuthorizationServerMetadata", { enumerable: true, get: function () { return oauthMetadata_1.buildAuthorizationServerMetadata; } });
|
|
67
|
+
Object.defineProperty(exports, "buildProtectedResourceMetadata", { enumerable: true, get: function () { return oauthMetadata_1.buildProtectedResourceMetadata; } });
|
|
68
|
+
Object.defineProperty(exports, "resolveMcpOAuthOption", { enumerable: true, get: function () { return oauthMetadata_1.resolveMcpOAuthOption; } });
|
|
69
|
+
Object.defineProperty(exports, "sendMcpOAuthChallenge", { enumerable: true, get: function () { return oauthMetadata_1.sendMcpOAuthChallenge; } });
|
|
62
70
|
var registry_1 = require("./mcp/registry");
|
|
63
71
|
Object.defineProperty(exports, "clearMCPRegistry", { enumerable: true, get: function () { return registry_1.clearMCPRegistry; } });
|
|
64
72
|
Object.defineProperty(exports, "getMCPRegistry", { enumerable: true, get: function () { return registry_1.getMCPRegistry; } });
|
|
@@ -87,6 +95,15 @@ __exportStar(require("./migrations/schemaCatalog"), exports);
|
|
|
87
95
|
__exportStar(require("./migrations/types"), exports);
|
|
88
96
|
__exportStar(require("./models/consentForm"), exports);
|
|
89
97
|
__exportStar(require("./models/consentResponse"), exports);
|
|
98
|
+
var mcpOAuthAuthorization_1 = require("./models/mcpOAuthAuthorization");
|
|
99
|
+
Object.defineProperty(exports, "McpOAuthAuthorization", { enumerable: true, get: function () { return mcpOAuthAuthorization_1.McpOAuthAuthorization; } });
|
|
100
|
+
var mcpOAuthClient_1 = require("./models/mcpOAuthClient");
|
|
101
|
+
Object.defineProperty(exports, "McpOAuthClient", { enumerable: true, get: function () { return mcpOAuthClient_1.McpOAuthClient; } });
|
|
102
|
+
var mcpOAuthRevokedFamily_1 = require("./models/mcpOAuthRevokedFamily");
|
|
103
|
+
Object.defineProperty(exports, "McpOAuthRevokedFamily", { enumerable: true, get: function () { return mcpOAuthRevokedFamily_1.McpOAuthRevokedFamily; } });
|
|
104
|
+
var mcpOAuthToken_1 = require("./models/mcpOAuthToken");
|
|
105
|
+
Object.defineProperty(exports, "McpOAuthFamilyRevokedError", { enumerable: true, get: function () { return mcpOAuthToken_1.McpOAuthFamilyRevokedError; } });
|
|
106
|
+
Object.defineProperty(exports, "McpOAuthToken", { enumerable: true, get: function () { return mcpOAuthToken_1.McpOAuthToken; } });
|
|
90
107
|
__exportStar(require("./models/mcpServiceToken"), exports);
|
|
91
108
|
__exportStar(require("./models/notification"), exports);
|
|
92
109
|
__exportStar(require("./models/notificationPreference"), exports);
|
|
@@ -149,6 +166,13 @@ __exportStar(require("./rbac/scopes"), exports);
|
|
|
149
166
|
__exportStar(require("./rbac/statements"), exports);
|
|
150
167
|
__exportStar(require("./rbac/types"), exports);
|
|
151
168
|
__exportStar(require("./rbac/userPlugin"), exports);
|
|
169
|
+
var userWriteGuards_1 = require("./rbac/userWriteGuards");
|
|
170
|
+
Object.defineProperty(exports, "assertCanWriteTargetUser", { enumerable: true, get: function () { return userWriteGuards_1.assertCanWriteTargetUser; } });
|
|
171
|
+
Object.defineProperty(exports, "assertCanWriteUserIdentity", { enumerable: true, get: function () { return userWriteGuards_1.assertCanWriteUserIdentity; } });
|
|
172
|
+
Object.defineProperty(exports, "isRbacUserModelName", { enumerable: true, get: function () { return userWriteGuards_1.isRbacUserModelName; } });
|
|
173
|
+
Object.defineProperty(exports, "isWriteKeyForField", { enumerable: true, get: function () { return userWriteGuards_1.isWriteKeyForField; } });
|
|
174
|
+
Object.defineProperty(exports, "USER_IDENTITY_FIELDS", { enumerable: true, get: function () { return userWriteGuards_1.USER_IDENTITY_FIELDS; } });
|
|
175
|
+
Object.defineProperty(exports, "USER_UPDATE_IDENTITY_ACTION", { enumerable: true, get: function () { return userWriteGuards_1.USER_UPDATE_IDENTITY_ACTION; } });
|
|
152
176
|
var changeStreamWatcher_1 = require("./realtime/changeStreamWatcher");
|
|
153
177
|
Object.defineProperty(exports, "emitPayloadToAuthorizedRoom", { enumerable: true, get: function () { return changeStreamWatcher_1.emitPayloadToAuthorizedRoom; } });
|
|
154
178
|
Object.defineProperty(exports, "emitSyncDeltaForChange", { enumerable: true, get: function () { return changeStreamWatcher_1.emitSyncDeltaForChange; } });
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { CollectionRecord } from "../collectionRegistry";
|
|
2
|
+
import type { MCPToolDefinition } from "./toolGenerator";
|
|
3
|
+
/** MCP tools for every modelRouter action that sets `mcp`, across all registered routers. */
|
|
4
|
+
export declare const generateActionTools: (records: CollectionRecord[]) => MCPToolDefinition[];
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateActionTools = void 0;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const actions_1 = require("../actions");
|
|
6
|
+
const docLoader_1 = require("../docLoader");
|
|
7
|
+
const errors_1 = require("../errors");
|
|
8
|
+
const createMCPRequest_1 = require("./createMCPRequest");
|
|
9
|
+
const handlers_1 = require("./handlers");
|
|
10
|
+
const toolExecution_1 = require("./toolExecution");
|
|
11
|
+
/**
|
|
12
|
+
* Stands in for `res` during an MCP call. MCP returns the handler's value as the tool result,
|
|
13
|
+
* so a handler that writes to `res` has nowhere to send it; failing loudly beats a silent drop.
|
|
14
|
+
*/
|
|
15
|
+
const createMCPResponseStub = (toolName) => {
|
|
16
|
+
return new Proxy({}, {
|
|
17
|
+
get: (_target, property) => {
|
|
18
|
+
// Inspectors and promise checks probe symbols; only real field access is an error.
|
|
19
|
+
if (typeof property === "symbol") {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
throw new errors_1.APIError({
|
|
23
|
+
code: "mcp-action-touched-response",
|
|
24
|
+
detail: `The action behind MCP tool "${toolName}" read res.${property}. Return a value instead of writing to res, or leave mcp off this action.`,
|
|
25
|
+
status: 500,
|
|
26
|
+
title: "Action used res during an MCP call",
|
|
27
|
+
});
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
const ID_SCHEMA = zod_1.z.string().describe("Id of the document to run the action on");
|
|
32
|
+
/** `{id}` merged with the body (POST) or query (GET) schema; collection actions have no id. */
|
|
33
|
+
const buildActionInputSchema = (scope, config) => {
|
|
34
|
+
const idShape = scope === "instance" ? { id: ID_SCHEMA } : {};
|
|
35
|
+
const argsSchema = config.method === "GET" ? config.query : config.body;
|
|
36
|
+
if (!argsSchema) {
|
|
37
|
+
// No schema: REST forwards the raw body, so the tool accepts any extra arguments too.
|
|
38
|
+
return zod_1.z.looseObject(idShape);
|
|
39
|
+
}
|
|
40
|
+
// safeExtend keeps refinements on the action's schema; registration checked it is an object.
|
|
41
|
+
return argsSchema.safeExtend(idShape);
|
|
42
|
+
};
|
|
43
|
+
/** Expected refusals carry no cause, so the audit log records them as warnings. */
|
|
44
|
+
const toolErrorFromException = (error) => {
|
|
45
|
+
if (!(0, errors_1.isAPIError)(error)) {
|
|
46
|
+
return (0, handlers_1.errorResult)((0, handlers_1.errorMessage)(error), error);
|
|
47
|
+
}
|
|
48
|
+
const fieldErrors = error.meta?.fields;
|
|
49
|
+
const fields = fieldErrors
|
|
50
|
+
? Object.entries(fieldErrors)
|
|
51
|
+
.map(([field, message]) => `${field}: ${message}`)
|
|
52
|
+
.join("; ")
|
|
53
|
+
: undefined;
|
|
54
|
+
const message = fields ? `${error.title} (${fields})` : error.title;
|
|
55
|
+
return (error.status ?? 500) < 500 ? (0, handlers_1.errorResult)(message) : (0, handlers_1.errorResult)(message, error);
|
|
56
|
+
};
|
|
57
|
+
const isAuthenticationRequired = (entry, user) => {
|
|
58
|
+
return !user && !(entry.config.allowAnonymous ?? entry.options.allowAnonymous);
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Run an action the way REST does: pre-document permissions, load the document and re-check
|
|
62
|
+
* (instance actions), then the handler. The MCP server already validated `args` against the
|
|
63
|
+
* action's zod schema, so the parsed values go to the handler as-is.
|
|
64
|
+
*/
|
|
65
|
+
const runActionTool = async (entry, toolName, args, user) => {
|
|
66
|
+
const { config, model, options, scope } = entry;
|
|
67
|
+
if (isAuthenticationRequired(entry, user)) {
|
|
68
|
+
return (0, handlers_1.errorResult)("Permission denied: authentication required");
|
|
69
|
+
}
|
|
70
|
+
// Only instance tools add `id`; a collection action's own schema may define one for its body.
|
|
71
|
+
const { id, ...instanceInput } = args;
|
|
72
|
+
const input = scope === "instance" ? instanceInput : args;
|
|
73
|
+
const isGet = config.method === "GET";
|
|
74
|
+
const req = (0, createMCPRequest_1.createMCPRequest)({
|
|
75
|
+
body: isGet ? {} : input,
|
|
76
|
+
params: scope === "instance" ? { id: String(id) } : {},
|
|
77
|
+
query: isGet ? input : {},
|
|
78
|
+
user,
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
await (0, actions_1.runActionPermissions)(config, scope, model, req, undefined, options.accessControl, options.access);
|
|
82
|
+
let doc;
|
|
83
|
+
if (scope === "instance") {
|
|
84
|
+
doc = await (0, docLoader_1.loadDocOr404)(model, String(id), options.populatePaths);
|
|
85
|
+
req.obj = doc;
|
|
86
|
+
await (0, actions_1.runActionPermissions)(config, scope, model, req, doc, options.accessControl, options.access);
|
|
87
|
+
}
|
|
88
|
+
const ctx = {
|
|
89
|
+
body: req.body,
|
|
90
|
+
doc,
|
|
91
|
+
query: req.query,
|
|
92
|
+
req,
|
|
93
|
+
res: createMCPResponseStub(toolName),
|
|
94
|
+
user: req.user,
|
|
95
|
+
};
|
|
96
|
+
const result = scope === "instance"
|
|
97
|
+
? await config.handler(ctx)
|
|
98
|
+
: await config.handler(ctx);
|
|
99
|
+
return (0, handlers_1.textResult)(JSON.stringify(result ?? null));
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
return toolErrorFromException(error);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const isDisabled = (config) => {
|
|
106
|
+
return config.permissions !== undefined && config.permissions.length === 0 && !config.access;
|
|
107
|
+
};
|
|
108
|
+
const listMCPActions = (record) => {
|
|
109
|
+
const { model, options } = record;
|
|
110
|
+
const entries = [];
|
|
111
|
+
const scopes = [
|
|
112
|
+
["instance", options.instanceActions],
|
|
113
|
+
["collection", options.collectionActions],
|
|
114
|
+
];
|
|
115
|
+
for (const [scope, actions] of scopes) {
|
|
116
|
+
for (const [actionName, config] of Object.entries(actions ?? {})) {
|
|
117
|
+
if (config.mcp && !isDisabled(config)) {
|
|
118
|
+
entries.push({ actionName, config, model, options, scope });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return entries;
|
|
123
|
+
};
|
|
124
|
+
const describeAction = (entry) => {
|
|
125
|
+
const { actionName, config, model, scope } = entry;
|
|
126
|
+
const base = config.mcp?.description ??
|
|
127
|
+
config.description ??
|
|
128
|
+
config.summary ??
|
|
129
|
+
`Run the ${actionName} action on ${model.modelName}`;
|
|
130
|
+
return scope === "instance" ? `${base} (pass the ${model.modelName} id as "id")` : base;
|
|
131
|
+
};
|
|
132
|
+
/** MCP tools for every modelRouter action that sets `mcp`, across all registered routers. */
|
|
133
|
+
const generateActionTools = (records) => {
|
|
134
|
+
const tools = [];
|
|
135
|
+
for (const record of records) {
|
|
136
|
+
for (const entry of listMCPActions(record)) {
|
|
137
|
+
const toolName = entry.config.mcp?.name;
|
|
138
|
+
const zodSchema = buildActionInputSchema(entry.scope, entry.config);
|
|
139
|
+
tools.push({
|
|
140
|
+
description: describeAction(entry),
|
|
141
|
+
handler: (args, user) => (0, toolExecution_1.executeTool)({
|
|
142
|
+
labels: {
|
|
143
|
+
mcpAction: entry.actionName,
|
|
144
|
+
mcpModel: entry.model.modelName,
|
|
145
|
+
mcpTool: toolName,
|
|
146
|
+
},
|
|
147
|
+
run: () => runActionTool(entry, toolName, args, user),
|
|
148
|
+
user,
|
|
149
|
+
}),
|
|
150
|
+
inputSchema: (0, zod_1.toJSONSchema)(zodSchema),
|
|
151
|
+
name: toolName,
|
|
152
|
+
zodSchema,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return tools;
|
|
157
|
+
};
|
|
158
|
+
exports.generateActionTools = generateActionTools;
|
package/dist/mcp/auth.d.ts
CHANGED
|
@@ -1,12 +1,42 @@
|
|
|
1
1
|
import type { User, UserModel } from "../auth";
|
|
2
2
|
import type { BetterAuthInstance } from "../betterAuthSetup";
|
|
3
|
+
import type { RequestCredential } from "../requestContext";
|
|
3
4
|
export interface MCPAuthContext {
|
|
4
5
|
userModel: UserModel;
|
|
5
6
|
betterAuth?: BetterAuthInstance;
|
|
6
7
|
mcpServiceTokens?: boolean;
|
|
8
|
+
/** Accept `mcpat_` OAuth access tokens issued by the MCP OAuth server. */
|
|
9
|
+
mcpOAuth?: boolean;
|
|
7
10
|
}
|
|
11
|
+
/** The authenticated user plus the credential type that proved it. */
|
|
12
|
+
export interface MCPAuthResult {
|
|
13
|
+
credential: RequestCredential;
|
|
14
|
+
/** Scopes granted to an MCP OAuth access token; unset for other credentials. */
|
|
15
|
+
scopes?: string[];
|
|
16
|
+
user: User;
|
|
17
|
+
}
|
|
18
|
+
/** The user's credential generation; a password reset or session revocation increments it. */
|
|
19
|
+
export declare const userTokenEpoch: (user: unknown) => number;
|
|
20
|
+
/**
|
|
21
|
+
* True when a credential minted under `issuedEpoch` predates the user's current tokenEpoch.
|
|
22
|
+
* A credential stored before the field existed counts as epoch 0, as a refresh token without
|
|
23
|
+
* `te` does.
|
|
24
|
+
*/
|
|
25
|
+
export declare const isCredentialEpochStale: (issuedEpoch: number | undefined, user: unknown) => boolean;
|
|
26
|
+
export declare const bearerFromHeaders: (headers: Record<string, string | string[] | undefined>) => {
|
|
27
|
+
authorization?: string;
|
|
28
|
+
token?: string;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Resolve the caller and the credential type from raw headers using whichever auth providers
|
|
32
|
+
* are configured, mirroring authenticateMiddleware behavior: `mcp_` service tokens and `mcpat_`
|
|
33
|
+
* OAuth access tokens first (each is a distinct credential type), then a Better Auth session,
|
|
34
|
+
* then a Terreno JWT.
|
|
35
|
+
*/
|
|
36
|
+
export declare const extractAuthFromHeaders: (headers: Record<string, string | string[] | undefined>, context: MCPAuthContext) => Promise<MCPAuthResult | undefined>;
|
|
8
37
|
/**
|
|
9
38
|
* Extract user from raw headers using whichever auth provider is configured.
|
|
10
39
|
* Works with both JWT and Better Auth, mirroring authenticateMiddleware behavior.
|
|
40
|
+
* Use {@link extractAuthFromHeaders} when the credential type matters.
|
|
11
41
|
*/
|
|
12
42
|
export declare const extractUserFromHeaders: (headers: Record<string, string | string[] | undefined>, context: MCPAuthContext) => Promise<User | undefined>;
|