@terreno/api 57.19.2 → 57.21.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/CHANGELOG.md +443 -0
- package/biome.jsonc +1 -0
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.d.ts +3 -3
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/frameworkModelNames.d.ts +4 -0
- package/dist/frameworkModelNames.js +4 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.js +29 -3
- package/dist/mcp/adminTracking.d.ts +28 -0
- package/dist/mcp/adminTracking.js +80 -0
- package/dist/mcp/auth.d.ts +6 -0
- package/dist/mcp/auth.js +12 -2
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +48 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +55 -4
- package/dist/models/mcpRequestLog.d.ts +2 -0
- package/dist/models/mcpRequestLog.js +73 -0
- package/dist/models/mcpServiceToken.js +4 -0
- package/dist/models/mcpToolSetting.d.ts +2 -0
- package/dist/models/mcpToolSetting.js +119 -0
- package/dist/models/versionConfig.d.ts +2 -0
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/auditModel.d.ts +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +16 -0
- package/dist/terrenoApp.js +18 -0
- package/dist/tests/models.d.ts +22 -22
- package/dist/tests/models.js +15 -1
- package/dist/tests/testHelper.d.ts +6 -12
- package/dist/tests.d.ts +1 -0
- package/dist/tests.js +3 -1
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpAdmin.d.ts +58 -0
- package/dist/types/mcpAdmin.js +2 -0
- package/dist/types/mcpOAuth.d.ts +37 -2
- package/dist/types/mcpServiceToken.d.ts +2 -0
- package/e2e/smoke.ts +193 -0
- package/package.json +10 -5
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/adminModelRouter.test.ts +8 -6
- package/src/api.arrayOperations.test.ts +102 -22
- package/src/api.hooks.test.ts +12 -11
- package/src/api.query.test.ts +2 -2
- package/src/api.test.ts +8 -7
- package/src/api.ts +41 -10
- package/src/audit/auditApp.test.ts +1 -1
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/cloudTasksEnqueue.test.ts +19 -14
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/auth.test.ts +21 -7
- package/src/authRecovery.test.ts +33 -10
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/authVerification.test.ts +7 -7
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +490 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +846 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +115 -57
- package/src/betterAuthSetup.ts +457 -38
- package/src/collectionRegistry.test.ts +4 -4
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/frameworkModelNames.test.ts +8 -0
- package/src/frameworkModelNames.ts +4 -0
- package/src/githubAuth.test.ts +11 -11
- package/src/index.ts +38 -0
- package/src/isolated/migrateCliConnect.isolated.ts +3 -2
- package/src/mcp/actionTools.test.ts +11 -5
- package/src/mcp/adminTracking.test.ts +272 -0
- package/src/mcp/adminTracking.ts +104 -0
- package/src/mcp/auth.ts +18 -2
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/mcp/server.ts +67 -4
- package/src/mcp/serviceTokens.test.ts +2 -1
- package/src/mcp/toolGenerator.test.ts +9 -5
- package/src/migrations/cli.test.ts +15 -14
- package/src/migrations/cli.ts +1 -1
- package/src/migrations/generate.test.ts +2 -2
- package/src/migrations/load.test.ts +1 -1
- package/src/migrations/lock.test.ts +8 -3
- package/src/migrations/runner.test.ts +16 -5
- package/src/migrations/schemaCatalog.test.ts +4 -1
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.test.ts +42 -0
- package/src/models/mcpOAuthToken.ts +62 -5
- package/src/models/mcpRequestLog.ts +81 -0
- package/src/models/mcpServiceToken.test.ts +23 -0
- package/src/models/mcpServiceToken.ts +10 -0
- package/src/models/mcpToolSetting.test.ts +69 -0
- package/src/models/mcpToolSetting.ts +138 -0
- package/src/models/versionConfig.ts +2 -0
- package/src/notifications/notificationsApp.test.ts +5 -8
- package/src/notifiers/slackWebApi.test.ts +30 -8
- package/src/openApi.test.ts +4 -4
- package/src/openApiValidator.test.ts +3 -3
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgPermissions.test.ts +2 -2
- package/src/orgs/orgPlugin.test.ts +4 -3
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgSecurityDefects.test.ts +3 -1
- package/src/orgs/organizationSettings.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +104 -3
- package/src/orgs/orgsApp.ts +69 -28
- package/src/permissions.test.ts +2 -2
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
- package/src/rbac/access.ts +4 -1
- package/src/rbac/assertAllowed.test.ts +1 -1
- package/src/rbac/auditModel.ts +10 -2
- package/src/rbac/realtimeAccess.test.ts +3 -2
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +56 -5
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/realtime/realtime.test.ts +35 -31
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/scrubAdminFields.test.ts +1 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/sync/adminWindowMutation.test.ts +4 -3
- package/src/sync/executors.test.ts +1 -1
- package/src/sync/scripts/compactTombstones.test.ts +4 -3
- package/src/sync/sync.test.ts +1 -1
- package/src/sync/syncPhaseC.test.ts +14 -11
- package/src/sync/syncRoutes.test.ts +8 -8
- package/src/sync/syncSeqPlugin.test.ts +1 -2
- package/src/sync/syncSocket.test.ts +5 -4
- package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
- package/src/terrenoApp.migrations.test.ts +8 -7
- package/src/terrenoApp.ts +34 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +189 -0
- package/src/tests/bunSetup.ts +1 -1
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +23 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/tests/testEnv.ts +7 -0
- package/src/tests.ts +1 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpAdmin.ts +80 -0
- package/src/types/mcpOAuth.ts +44 -3
- package/src/types/mcpServiceToken.ts +5 -0
- package/src/webhooks/verifiers/hmac.test.ts +1 -1
- package/tsconfig.typecheck.json +14 -0
package/dist/errors.js
CHANGED
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.passthroughOrWrapWrite = exports.passthroughOrWrap = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
|
|
36
|
+
exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.passthroughOrWrapWrite = exports.passthroughOrWrap = exports.bodyParserErrorToAPIError = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
|
|
37
37
|
// https://jsonapi.org/format/#errors
|
|
38
38
|
const Sentry = __importStar(require("@sentry/bun"));
|
|
39
39
|
const mongoose_1 = __importStar(require("mongoose"));
|
|
@@ -394,6 +394,43 @@ const mongooseErrorToAPIError = (err) => {
|
|
|
394
394
|
return null;
|
|
395
395
|
};
|
|
396
396
|
exports.mongooseErrorToAPIError = mongooseErrorToAPIError;
|
|
397
|
+
// Stable titles for the client errors body-parser (express.json / express.urlencoded) raises
|
|
398
|
+
// before a route runs. The parser's own status and message are kept; only the title is mapped.
|
|
399
|
+
const BODY_PARSER_ERROR_TITLES = {
|
|
400
|
+
"charset.unsupported": "Unsupported request body encoding",
|
|
401
|
+
"encoding.unsupported": "Unsupported request body encoding",
|
|
402
|
+
"entity.parse.failed": "Malformed request body",
|
|
403
|
+
"entity.too.large": "Request body too large",
|
|
404
|
+
"parameters.too.many": "Request body too large",
|
|
405
|
+
"request.aborted": "Request body incomplete",
|
|
406
|
+
"request.size.invalid": "Request body incomplete",
|
|
407
|
+
};
|
|
408
|
+
const isBodyParserClientError = (err) => {
|
|
409
|
+
const candidate = err;
|
|
410
|
+
return (typeof candidate.type === "string" &&
|
|
411
|
+
candidate.expose === true &&
|
|
412
|
+
typeof candidate.status === "number" &&
|
|
413
|
+
candidate.status >= 400 &&
|
|
414
|
+
candidate.status < 500);
|
|
415
|
+
};
|
|
416
|
+
/**
|
|
417
|
+
* Converts a body-parser client error (malformed JSON, oversized body, unsupported charset) into
|
|
418
|
+
* an APIError with the parser's 4xx status. Returns null for anything else, including parser
|
|
419
|
+
* errors body-parser marks as not exposable (server faults).
|
|
420
|
+
*/
|
|
421
|
+
const bodyParserErrorToAPIError = (err) => {
|
|
422
|
+
if (!isBodyParserClientError(err)) {
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
return new APIError({
|
|
426
|
+
cause: err,
|
|
427
|
+
detail: err.message,
|
|
428
|
+
disableExternalErrorTracking: true,
|
|
429
|
+
status: err.status,
|
|
430
|
+
title: BODY_PARSER_ERROR_TITLES[err.type] ?? "Invalid request body",
|
|
431
|
+
});
|
|
432
|
+
};
|
|
433
|
+
exports.bodyParserErrorToAPIError = bodyParserErrorToAPIError;
|
|
397
434
|
/**
|
|
398
435
|
* Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
|
|
399
436
|
* An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
|
|
@@ -452,7 +489,9 @@ const logAndCaptureAPIError = (err) => {
|
|
|
452
489
|
});
|
|
453
490
|
};
|
|
454
491
|
const apiErrorMiddleware = (err, _req, res, next) => {
|
|
455
|
-
const apiError = (0, exports.isAPIError)(err)
|
|
492
|
+
const apiError = (0, exports.isAPIError)(err)
|
|
493
|
+
? err
|
|
494
|
+
: ((0, exports.mongooseErrorToAPIError)(err) ?? (0, exports.bodyParserErrorToAPIError)(err));
|
|
456
495
|
if (!apiError) {
|
|
457
496
|
next(err);
|
|
458
497
|
return;
|
package/dist/expressServer.js
CHANGED
|
@@ -68,8 +68,9 @@ const SENSITIVE_KEY_FRAGMENTS = [
|
|
|
68
68
|
"verifier",
|
|
69
69
|
];
|
|
70
70
|
// Matched as whole words of a key, so `code` covers OAuth and verification codes without
|
|
71
|
-
// matching unrelated words that merely contain the letters.
|
|
72
|
-
|
|
71
|
+
// matching unrelated words that merely contain the letters. `note` and `reason` are free text
|
|
72
|
+
// that can hold PHI, such as a provisional consent signer's note or a void reason.
|
|
73
|
+
const SENSITIVE_KEY_WORDS = new Set(["code", "note", "otp", "pin", "reason"]);
|
|
73
74
|
const keyWords = (key) => {
|
|
74
75
|
return key
|
|
75
76
|
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
@@ -9,7 +9,11 @@ export declare const FRAMEWORK_MODEL_PUBLIC_NAMES: {
|
|
|
9
9
|
readonly TerrenoInboxNotification: "Notification";
|
|
10
10
|
readonly TerrenoJob: "Job";
|
|
11
11
|
readonly TerrenoJobSchedule: "JobSchedule";
|
|
12
|
+
readonly TerrenoMcpOAuthClient: "McpOAuthClient";
|
|
13
|
+
readonly TerrenoMcpOAuthToken: "McpOAuthToken";
|
|
14
|
+
readonly TerrenoMcpRequestLog: "McpRequestLog";
|
|
12
15
|
readonly TerrenoMcpServiceToken: "McpServiceToken";
|
|
16
|
+
readonly TerrenoMcpToolSetting: "McpToolSetting";
|
|
13
17
|
readonly TerrenoMembership: "Membership";
|
|
14
18
|
readonly TerrenoNotificationPreference: "NotificationPreference";
|
|
15
19
|
readonly TerrenoOrganization: "Organization";
|
|
@@ -12,7 +12,11 @@ exports.FRAMEWORK_MODEL_PUBLIC_NAMES = {
|
|
|
12
12
|
TerrenoInboxNotification: "Notification",
|
|
13
13
|
TerrenoJob: "Job",
|
|
14
14
|
TerrenoJobSchedule: "JobSchedule",
|
|
15
|
+
TerrenoMcpOAuthClient: "McpOAuthClient",
|
|
16
|
+
TerrenoMcpOAuthToken: "McpOAuthToken",
|
|
17
|
+
TerrenoMcpRequestLog: "McpRequestLog",
|
|
15
18
|
TerrenoMcpServiceToken: "McpServiceToken",
|
|
19
|
+
TerrenoMcpToolSetting: "McpToolSetting",
|
|
16
20
|
TerrenoMembership: "Membership",
|
|
17
21
|
TerrenoNotificationPreference: "NotificationPreference",
|
|
18
22
|
TerrenoOrganization: "Organization",
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
|
+
export { ISSUE_SIGN_IN_LINK_PERMISSION } from "./accountSecurity/accessActions";
|
|
2
|
+
export * from "./accountSecurity/accountSecurityApp";
|
|
3
|
+
export * from "./accountSecurity/accountSecurityService";
|
|
4
|
+
export { suspendMembershipAction } from "./accountSecurity/membershipActions";
|
|
5
|
+
export { createOrgSecurityAuthorizer, mountOrgSecurityRoutes, type OrgRecoveryOptions, } from "./accountSecurity/orgSecurityRoutes";
|
|
6
|
+
export { createSecurityEventsPlugin, recordSelfSecurityAction, } from "./accountSecurity/securityEventHooks";
|
|
7
|
+
export * from "./accountSecurity/securityEvents";
|
|
8
|
+
export * from "./accountSecurity/securityNotifications";
|
|
1
9
|
export * from "./actions";
|
|
2
10
|
export * from "./adminTypes";
|
|
3
11
|
export * from "./api";
|
|
4
12
|
export { AuditApp, type AuditAppOptions } from "./audit/auditApp";
|
|
5
|
-
export { type AuditEventDocument, type AuditEventModel, type AuditEventOperation, type AuditEventSource, type AuditEventVerb, createAuditEventModel, } from "./audit/auditEventModel";
|
|
13
|
+
export { AUDIT_EVENT_SOURCES, type AuditEventDocument, type AuditEventModel, type AuditEventOperation, type AuditEventSource, type AuditEventVerb, createAuditEventModel, } from "./audit/auditEventModel";
|
|
6
14
|
export { AUDIT_SECRET_HEADER, auditEnqueueFromEnv, type CloudTasksAuditEnqueueOptions, createCloudTasksAuditEnqueue, } from "./audit/cloudTasksEnqueue";
|
|
7
15
|
export { persistRbacAuditToAuditEvent } from "./audit/rbacSink";
|
|
8
16
|
export { type AuditEnqueue, type AuditEventWrite, type AuditRecorderOptions, flushAuditRecorderForTests, isAuditRecorderInstalled, type ModelRouterAuditConfig, type ModelRouterAuditOptions, maybeRecordAdminAudit, persistEnqueuedAuditEvent, recordAuditEvent, resetAuditRecorderForTests, } from "./audit/record";
|
|
@@ -11,12 +19,16 @@ export * from "./authRecovery";
|
|
|
11
19
|
export * from "./authTokens";
|
|
12
20
|
export * from "./betterAuth";
|
|
13
21
|
export * from "./betterAuthApp";
|
|
22
|
+
export * from "./betterAuthChallengeHeaders";
|
|
23
|
+
export * from "./betterAuthFeatures";
|
|
24
|
+
export * from "./betterAuthMethods";
|
|
14
25
|
export * from "./betterAuthSetup";
|
|
15
26
|
export * from "./browserLogsRoute";
|
|
16
27
|
export * from "./config";
|
|
17
28
|
export * from "./configurationApp";
|
|
18
29
|
export * from "./configurationPlugin";
|
|
19
30
|
export * from "./consentApp";
|
|
31
|
+
export { type ConsentStatus, type ConsentStatusForm, type ConsentStatusProvisional, type ConsentStatusRow, type ConsentStatusSigner, getConsentStatuses, type ResolveConsentForms, } from "./consentStatus";
|
|
20
32
|
export * from "./envConfigurationPlugin";
|
|
21
33
|
export * from "./errors";
|
|
22
34
|
export * from "./expressServer";
|
|
@@ -24,6 +36,7 @@ export { FRAMEWORK_MODEL_PUBLIC_NAMES, type FrameworkModelCompiledName, type Fra
|
|
|
24
36
|
export * from "./githubAuth";
|
|
25
37
|
export * from "./httpClient";
|
|
26
38
|
export * from "./logger";
|
|
39
|
+
export { type McpRequestLogAppOption, type ResolvedMcpRequestLogOptions, resolveMcpRequestLogOption, } from "./mcp/adminTracking";
|
|
27
40
|
export { extractAuthFromHeaders, extractUserFromHeaders, type MCPAuthContext, type MCPAuthResult, } from "./mcp/auth";
|
|
28
41
|
export { addMcpOAuthRoutes, type McpOAuthRoutesOptions } from "./mcp/oauth";
|
|
29
42
|
export { buildAuthorizationServerMetadata, buildProtectedResourceMetadata, type McpOAuthAppOption, type McpOAuthOptions, type ResolvedMcpOAuthOptions, resolveMcpOAuthOption, sendMcpOAuthChallenge, } from "./mcp/oauthMetadata";
|
|
@@ -47,7 +60,9 @@ export { McpOAuthAuthorization } from "./models/mcpOAuthAuthorization";
|
|
|
47
60
|
export { McpOAuthClient } from "./models/mcpOAuthClient";
|
|
48
61
|
export { McpOAuthRevokedFamily } from "./models/mcpOAuthRevokedFamily";
|
|
49
62
|
export { McpOAuthFamilyRevokedError, McpOAuthToken } from "./models/mcpOAuthToken";
|
|
63
|
+
export { McpRequestLog } from "./models/mcpRequestLog";
|
|
50
64
|
export * from "./models/mcpServiceToken";
|
|
65
|
+
export { McpToolSetting } from "./models/mcpToolSetting";
|
|
51
66
|
export * from "./models/notification";
|
|
52
67
|
export * from "./models/notificationPreference";
|
|
53
68
|
export * from "./models/versionConfig";
|
|
@@ -125,7 +140,8 @@ export * from "./terrenoPlugin";
|
|
|
125
140
|
export * from "./transformers";
|
|
126
141
|
export * from "./types/consentForm";
|
|
127
142
|
export * from "./types/consentResponse";
|
|
128
|
-
export type
|
|
143
|
+
export type * from "./types/mcpAdmin";
|
|
144
|
+
export type { McpOAuthAuthorizationDocument, McpOAuthAuthorizationStatus, McpOAuthClientDocument, McpOAuthConfidentialClientOptions, McpOAuthRevokedFamilyDocument, McpOAuthTokenDocument, McpOAuthTokenEndpointAuthMethod, } from "./types/mcpOAuth";
|
|
129
145
|
export * from "./utils";
|
|
130
146
|
export * from "./versionCheckPlugin";
|
|
131
147
|
export type { WebhookClaimArgs, WebhookClaimResult, WebhookIdempotencyStore, } from "./webhooks/idempotency/memoryStore";
|
package/dist/index.js
CHANGED
|
@@ -14,15 +14,30 @@ 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 = 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;
|
|
17
|
+
exports.McpRequestLog = 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.resolveMcpRequestLogOption = exports.publicFrameworkModelName = exports.FRAMEWORK_MODEL_PUBLIC_NAMES = exports.getConsentStatuses = 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.AUDIT_EVENT_SOURCES = exports.AuditApp = exports.recordSelfSecurityAction = exports.createSecurityEventsPlugin = exports.mountOrgSecurityRoutes = exports.createOrgSecurityAuthorizer = exports.suspendMembershipAction = exports.ISSUE_SIGN_IN_LINK_PERMISSION = void 0;
|
|
18
|
+
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 = 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.McpToolSetting = 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 = 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 = void 0;
|
|
20
|
+
var accessActions_1 = require("./accountSecurity/accessActions");
|
|
21
|
+
Object.defineProperty(exports, "ISSUE_SIGN_IN_LINK_PERMISSION", { enumerable: true, get: function () { return accessActions_1.ISSUE_SIGN_IN_LINK_PERMISSION; } });
|
|
22
|
+
__exportStar(require("./accountSecurity/accountSecurityApp"), exports);
|
|
23
|
+
__exportStar(require("./accountSecurity/accountSecurityService"), exports);
|
|
24
|
+
var membershipActions_1 = require("./accountSecurity/membershipActions");
|
|
25
|
+
Object.defineProperty(exports, "suspendMembershipAction", { enumerable: true, get: function () { return membershipActions_1.suspendMembershipAction; } });
|
|
26
|
+
var orgSecurityRoutes_1 = require("./accountSecurity/orgSecurityRoutes");
|
|
27
|
+
Object.defineProperty(exports, "createOrgSecurityAuthorizer", { enumerable: true, get: function () { return orgSecurityRoutes_1.createOrgSecurityAuthorizer; } });
|
|
28
|
+
Object.defineProperty(exports, "mountOrgSecurityRoutes", { enumerable: true, get: function () { return orgSecurityRoutes_1.mountOrgSecurityRoutes; } });
|
|
29
|
+
var securityEventHooks_1 = require("./accountSecurity/securityEventHooks");
|
|
30
|
+
Object.defineProperty(exports, "createSecurityEventsPlugin", { enumerable: true, get: function () { return securityEventHooks_1.createSecurityEventsPlugin; } });
|
|
31
|
+
Object.defineProperty(exports, "recordSelfSecurityAction", { enumerable: true, get: function () { return securityEventHooks_1.recordSelfSecurityAction; } });
|
|
32
|
+
__exportStar(require("./accountSecurity/securityEvents"), exports);
|
|
33
|
+
__exportStar(require("./accountSecurity/securityNotifications"), exports);
|
|
20
34
|
__exportStar(require("./actions"), exports);
|
|
21
35
|
__exportStar(require("./adminTypes"), exports);
|
|
22
36
|
__exportStar(require("./api"), exports);
|
|
23
37
|
var auditApp_1 = require("./audit/auditApp");
|
|
24
38
|
Object.defineProperty(exports, "AuditApp", { enumerable: true, get: function () { return auditApp_1.AuditApp; } });
|
|
25
39
|
var auditEventModel_1 = require("./audit/auditEventModel");
|
|
40
|
+
Object.defineProperty(exports, "AUDIT_EVENT_SOURCES", { enumerable: true, get: function () { return auditEventModel_1.AUDIT_EVENT_SOURCES; } });
|
|
26
41
|
Object.defineProperty(exports, "createAuditEventModel", { enumerable: true, get: function () { return auditEventModel_1.createAuditEventModel; } });
|
|
27
42
|
var cloudTasksEnqueue_1 = require("./audit/cloudTasksEnqueue");
|
|
28
43
|
Object.defineProperty(exports, "AUDIT_SECRET_HEADER", { enumerable: true, get: function () { return cloudTasksEnqueue_1.AUDIT_SECRET_HEADER; } });
|
|
@@ -42,12 +57,17 @@ __exportStar(require("./authRecovery"), exports);
|
|
|
42
57
|
__exportStar(require("./authTokens"), exports);
|
|
43
58
|
__exportStar(require("./betterAuth"), exports);
|
|
44
59
|
__exportStar(require("./betterAuthApp"), exports);
|
|
60
|
+
__exportStar(require("./betterAuthChallengeHeaders"), exports);
|
|
61
|
+
__exportStar(require("./betterAuthFeatures"), exports);
|
|
62
|
+
__exportStar(require("./betterAuthMethods"), exports);
|
|
45
63
|
__exportStar(require("./betterAuthSetup"), exports);
|
|
46
64
|
__exportStar(require("./browserLogsRoute"), exports);
|
|
47
65
|
__exportStar(require("./config"), exports);
|
|
48
66
|
__exportStar(require("./configurationApp"), exports);
|
|
49
67
|
__exportStar(require("./configurationPlugin"), exports);
|
|
50
68
|
__exportStar(require("./consentApp"), exports);
|
|
69
|
+
var consentStatus_1 = require("./consentStatus");
|
|
70
|
+
Object.defineProperty(exports, "getConsentStatuses", { enumerable: true, get: function () { return consentStatus_1.getConsentStatuses; } });
|
|
51
71
|
__exportStar(require("./envConfigurationPlugin"), exports);
|
|
52
72
|
__exportStar(require("./errors"), exports);
|
|
53
73
|
__exportStar(require("./expressServer"), exports);
|
|
@@ -57,6 +77,8 @@ Object.defineProperty(exports, "publicFrameworkModelName", { enumerable: true, g
|
|
|
57
77
|
__exportStar(require("./githubAuth"), exports);
|
|
58
78
|
__exportStar(require("./httpClient"), exports);
|
|
59
79
|
__exportStar(require("./logger"), exports);
|
|
80
|
+
var adminTracking_1 = require("./mcp/adminTracking");
|
|
81
|
+
Object.defineProperty(exports, "resolveMcpRequestLogOption", { enumerable: true, get: function () { return adminTracking_1.resolveMcpRequestLogOption; } });
|
|
60
82
|
var auth_1 = require("./mcp/auth");
|
|
61
83
|
Object.defineProperty(exports, "extractAuthFromHeaders", { enumerable: true, get: function () { return auth_1.extractAuthFromHeaders; } });
|
|
62
84
|
Object.defineProperty(exports, "extractUserFromHeaders", { enumerable: true, get: function () { return auth_1.extractUserFromHeaders; } });
|
|
@@ -104,7 +126,11 @@ Object.defineProperty(exports, "McpOAuthRevokedFamily", { enumerable: true, get:
|
|
|
104
126
|
var mcpOAuthToken_1 = require("./models/mcpOAuthToken");
|
|
105
127
|
Object.defineProperty(exports, "McpOAuthFamilyRevokedError", { enumerable: true, get: function () { return mcpOAuthToken_1.McpOAuthFamilyRevokedError; } });
|
|
106
128
|
Object.defineProperty(exports, "McpOAuthToken", { enumerable: true, get: function () { return mcpOAuthToken_1.McpOAuthToken; } });
|
|
129
|
+
var mcpRequestLog_1 = require("./models/mcpRequestLog");
|
|
130
|
+
Object.defineProperty(exports, "McpRequestLog", { enumerable: true, get: function () { return mcpRequestLog_1.McpRequestLog; } });
|
|
107
131
|
__exportStar(require("./models/mcpServiceToken"), exports);
|
|
132
|
+
var mcpToolSetting_1 = require("./models/mcpToolSetting");
|
|
133
|
+
Object.defineProperty(exports, "McpToolSetting", { enumerable: true, get: function () { return mcpToolSetting_1.McpToolSetting; } });
|
|
108
134
|
__exportStar(require("./models/notification"), exports);
|
|
109
135
|
__exportStar(require("./models/notificationPreference"), exports);
|
|
110
136
|
__exportStar(require("./models/versionConfig"), exports);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { McpRequestLogOutcome } from "../types/mcpAdmin";
|
|
2
|
+
import type { MCPAuthResult } from "./auth";
|
|
3
|
+
import type { MCPToolDefinition } from "./toolGenerator";
|
|
4
|
+
/** `true` is `{enabled: true}`. Rows keep metadata only and expire after `retentionDays`. */
|
|
5
|
+
export type McpRequestLogAppOption = boolean | {
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
retentionDays?: number;
|
|
8
|
+
};
|
|
9
|
+
export interface ResolvedMcpRequestLogOptions {
|
|
10
|
+
retentionDays: number;
|
|
11
|
+
}
|
|
12
|
+
export declare const resolveMcpRequestLogOption: (option: McpRequestLogAppOption | undefined) => ResolvedMcpRequestLogOptions | undefined;
|
|
13
|
+
export interface McpToolCallRecord {
|
|
14
|
+
auth?: MCPAuthResult;
|
|
15
|
+
durationMs: number;
|
|
16
|
+
errorName?: string;
|
|
17
|
+
outcome: McpRequestLogOutcome;
|
|
18
|
+
toolName: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Write one request-log row without blocking or failing the tool call. A failed write is
|
|
22
|
+
* logged at debug level and dropped.
|
|
23
|
+
*/
|
|
24
|
+
export declare const recordMcpToolCall: (record: McpToolCallRecord, options: ResolvedMcpRequestLogOptions) => void;
|
|
25
|
+
/** Register every tool in `McpToolSetting` so admins can see and switch them. */
|
|
26
|
+
export declare const syncMcpToolSettings: (tools: MCPToolDefinition[]) => Promise<void>;
|
|
27
|
+
/** Tools an admin left on. A tool without a settings row counts as on. */
|
|
28
|
+
export declare const filterEnabledMcpTools: (tools: MCPToolDefinition[]) => Promise<MCPToolDefinition[]>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.filterEnabledMcpTools = exports.syncMcpToolSettings = exports.recordMcpToolCall = exports.resolveMcpRequestLogOption = void 0;
|
|
7
|
+
const luxon_1 = require("luxon");
|
|
8
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
9
|
+
const errors_1 = require("../errors");
|
|
10
|
+
const logger_1 = require("../logger");
|
|
11
|
+
const mcpRequestLog_1 = require("../models/mcpRequestLog");
|
|
12
|
+
const mcpToolSetting_1 = require("../models/mcpToolSetting");
|
|
13
|
+
const registry_1 = require("./registry");
|
|
14
|
+
const DEFAULT_REQUEST_LOG_RETENTION_DAYS = 30;
|
|
15
|
+
const resolveMcpRequestLogOption = (option) => {
|
|
16
|
+
if (option === true) {
|
|
17
|
+
return { retentionDays: DEFAULT_REQUEST_LOG_RETENTION_DAYS };
|
|
18
|
+
}
|
|
19
|
+
if (!option || typeof option !== "object" || option.enabled !== true) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
const retentionDays = option.retentionDays ?? DEFAULT_REQUEST_LOG_RETENTION_DAYS;
|
|
23
|
+
if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
|
|
24
|
+
throw new errors_1.APIError({
|
|
25
|
+
code: "mcp-request-log-misconfigured",
|
|
26
|
+
detail: `mcpRequestLog.retentionDays must be a positive number, got ${retentionDays}`,
|
|
27
|
+
status: 500,
|
|
28
|
+
title: "MCP request log is misconfigured",
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return { retentionDays };
|
|
32
|
+
};
|
|
33
|
+
exports.resolveMcpRequestLogOption = resolveMcpRequestLogOption;
|
|
34
|
+
const toObjectId = (value) => {
|
|
35
|
+
if (!value || !mongoose_1.default.isValidObjectId(value)) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
return new mongoose_1.default.Types.ObjectId(value);
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Write one request-log row without blocking or failing the tool call. A failed write is
|
|
42
|
+
* logged at debug level and dropped.
|
|
43
|
+
*/
|
|
44
|
+
const recordMcpToolCall = (record, options) => {
|
|
45
|
+
const { auth } = record;
|
|
46
|
+
void mcpRequestLog_1.McpRequestLog.create({
|
|
47
|
+
credential: auth?.credential,
|
|
48
|
+
durationMs: Math.round(record.durationMs),
|
|
49
|
+
errorName: record.errorName,
|
|
50
|
+
expiresAt: luxon_1.DateTime.now().plus({ days: options.retentionDays }).toJSDate(),
|
|
51
|
+
oauthClientId: auth?.oauthClientId,
|
|
52
|
+
oauthFamilyId: auth?.oauthFamilyId,
|
|
53
|
+
outcome: record.outcome,
|
|
54
|
+
serviceTokenId: toObjectId(auth?.serviceTokenId),
|
|
55
|
+
toolName: record.toolName,
|
|
56
|
+
userId: toObjectId(auth?.user?.id ? String(auth.user.id) : undefined),
|
|
57
|
+
}).catch((error) => {
|
|
58
|
+
logger_1.logger.debug(`[mcp] Request log write failed: ${String(error)}`);
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
exports.recordMcpToolCall = recordMcpToolCall;
|
|
62
|
+
/** Register every tool in `McpToolSetting` so admins can see and switch them. */
|
|
63
|
+
const syncMcpToolSettings = async (tools) => {
|
|
64
|
+
const customNames = new Set((0, registry_1.getMCPCustomTools)().map((tool) => tool.name));
|
|
65
|
+
await mcpToolSetting_1.McpToolSetting.syncRegistered(tools.map((tool) => ({
|
|
66
|
+
description: tool.description,
|
|
67
|
+
name: tool.name,
|
|
68
|
+
source: (customNames.has(tool.name) ? "custom" : "model"),
|
|
69
|
+
})));
|
|
70
|
+
};
|
|
71
|
+
exports.syncMcpToolSettings = syncMcpToolSettings;
|
|
72
|
+
/** Tools an admin left on. A tool without a settings row counts as on. */
|
|
73
|
+
const filterEnabledMcpTools = async (tools) => {
|
|
74
|
+
const disabled = await mcpToolSetting_1.McpToolSetting.disabledNames();
|
|
75
|
+
if (disabled.size === 0) {
|
|
76
|
+
return tools;
|
|
77
|
+
}
|
|
78
|
+
return tools.filter((tool) => !disabled.has(tool.name));
|
|
79
|
+
};
|
|
80
|
+
exports.filterEnabledMcpTools = filterEnabledMcpTools;
|
package/dist/mcp/auth.d.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface MCPAuthContext {
|
|
|
11
11
|
/** The authenticated user plus the credential type that proved it. */
|
|
12
12
|
export interface MCPAuthResult {
|
|
13
13
|
credential: RequestCredential;
|
|
14
|
+
/** OAuth client id for an MCP OAuth access token. Never a secret. */
|
|
15
|
+
oauthClientId?: string;
|
|
16
|
+
/** OAuth rotation-chain id for an MCP OAuth access token. Never a secret. */
|
|
17
|
+
oauthFamilyId?: string;
|
|
18
|
+
/** `McpServiceToken` document id for a service token. Never the token or its hash. */
|
|
19
|
+
serviceTokenId?: string;
|
|
14
20
|
/** Scopes granted to an MCP OAuth access token; unset for other credentials. */
|
|
15
21
|
scopes?: string[];
|
|
16
22
|
user: User;
|
package/dist/mcp/auth.js
CHANGED
|
@@ -66,7 +66,11 @@ const authenticateServiceToken = async (token, userModel) => {
|
|
|
66
66
|
void mcpServiceToken_1.McpServiceToken.updateOne({ _id: serviceToken._id }, { $set: { lastUsedAt: luxon_1.DateTime.now().toJSDate() } }).catch((error) => {
|
|
67
67
|
logger_1.logger.debug(`MCP service token last-used update failed: ${error}`);
|
|
68
68
|
});
|
|
69
|
-
return {
|
|
69
|
+
return {
|
|
70
|
+
credential: "mcp-service-token",
|
|
71
|
+
serviceTokenId: String(serviceToken._id),
|
|
72
|
+
user: activeUser,
|
|
73
|
+
};
|
|
70
74
|
};
|
|
71
75
|
const authenticateOAuthAccessToken = async (token, userModel) => {
|
|
72
76
|
const accessToken = await mcpOAuthToken_1.McpOAuthToken.verifyAccessToken(token);
|
|
@@ -84,7 +88,13 @@ const authenticateOAuthAccessToken = async (token, userModel) => {
|
|
|
84
88
|
return undefined;
|
|
85
89
|
}
|
|
86
90
|
const scopes = (accessToken.scope ?? "").split(" ").filter((scope) => scope.length > 0);
|
|
87
|
-
return {
|
|
91
|
+
return {
|
|
92
|
+
credential: "oauth",
|
|
93
|
+
oauthClientId: accessToken.clientId,
|
|
94
|
+
oauthFamilyId: accessToken.familyId,
|
|
95
|
+
scopes,
|
|
96
|
+
user: activeUser,
|
|
97
|
+
};
|
|
88
98
|
};
|
|
89
99
|
/**
|
|
90
100
|
* Resolve the caller and the credential type from raw headers using whichever auth providers
|
package/dist/mcp/oauth.js
CHANGED
|
@@ -204,10 +204,10 @@ const addRegistrationRoute = (app, oauth) => {
|
|
|
204
204
|
if (authMethod !== "none") {
|
|
205
205
|
throw new OAuthProtocolError("invalid_client_metadata", "Only public clients are supported: token_endpoint_auth_method must be none");
|
|
206
206
|
}
|
|
207
|
-
const grantTypes = body.grant_types ?? oauthMetadata_1.
|
|
207
|
+
const grantTypes = body.grant_types ?? oauthMetadata_1.PUBLIC_CLIENT_GRANT_TYPES;
|
|
208
208
|
if (!Array.isArray(grantTypes) ||
|
|
209
209
|
!grantTypes.includes("authorization_code") ||
|
|
210
|
-
grantTypes.some((grant) => !oauthMetadata_1.
|
|
210
|
+
grantTypes.some((grant) => !oauthMetadata_1.PUBLIC_CLIENT_GRANT_TYPES.includes(grant))) {
|
|
211
211
|
throw new OAuthProtocolError("invalid_client_metadata", "grant_types must include authorization_code and may add refresh_token");
|
|
212
212
|
}
|
|
213
213
|
const responseTypes = body.response_types ?? oauthMetadata_1.SUPPORTED_RESPONSE_TYPES;
|
|
@@ -245,6 +245,40 @@ const addRegistrationRoute = (app, oauth) => {
|
|
|
245
245
|
});
|
|
246
246
|
}));
|
|
247
247
|
};
|
|
248
|
+
/**
|
|
249
|
+
* RFC 8252 §7.3: a native client binds an ephemeral port, so a loopback redirect matches a
|
|
250
|
+
* registered loopback URI when scheme, hostname, path, and query match. The port is ignored.
|
|
251
|
+
* `localhost`, `127.0.0.1`, and `[::1]` stay distinct hosts. Every other URI stays an exact match.
|
|
252
|
+
*/
|
|
253
|
+
const redirectUriMatchesRegistered = (requested, registered) => {
|
|
254
|
+
if (registered.includes(requested)) {
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
let requestedUrl;
|
|
258
|
+
try {
|
|
259
|
+
requestedUrl = new URL(requested);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
if (!oauthMetadata_1.LOOPBACK_HOSTS.has(requestedUrl.hostname)) {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
return registered.some((candidate) => {
|
|
268
|
+
let registeredUrl;
|
|
269
|
+
try {
|
|
270
|
+
registeredUrl = new URL(candidate);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
return (oauthMetadata_1.LOOPBACK_HOSTS.has(registeredUrl.hostname) &&
|
|
276
|
+
registeredUrl.protocol === requestedUrl.protocol &&
|
|
277
|
+
registeredUrl.hostname === requestedUrl.hostname &&
|
|
278
|
+
registeredUrl.pathname === requestedUrl.pathname &&
|
|
279
|
+
registeredUrl.search === requestedUrl.search);
|
|
280
|
+
});
|
|
281
|
+
};
|
|
248
282
|
const addAuthorizeRoute = (app, oauth) => {
|
|
249
283
|
app.get("/oauth/authorize", oauthHandler(async (req, res) => {
|
|
250
284
|
const query = req.query;
|
|
@@ -253,14 +287,14 @@ const addAuthorizeRoute = (app, oauth) => {
|
|
|
253
287
|
throw new OAuthProtocolError("invalid_request", "client_id is required");
|
|
254
288
|
}
|
|
255
289
|
const client = await mcpOAuthClient_1.McpOAuthClient.findOneOrNone({ clientId });
|
|
256
|
-
if (!client) {
|
|
290
|
+
if (!client || client.revokedAt) {
|
|
257
291
|
throw new OAuthProtocolError("invalid_request", "Unknown client_id");
|
|
258
292
|
}
|
|
259
293
|
// RFC 6749 §4.1.2.1: never redirect to an unverified URI, so these two fail in place.
|
|
260
294
|
const requestedRedirect = stringParam(query.redirect_uri);
|
|
261
295
|
const redirectUri = requestedRedirect ??
|
|
262
296
|
(client.redirectUris.length === 1 ? client.redirectUris[0] : undefined);
|
|
263
|
-
if (!redirectUri || !client.redirectUris
|
|
297
|
+
if (!redirectUri || !redirectUriMatchesRegistered(redirectUri, client.redirectUris)) {
|
|
264
298
|
throw new OAuthProtocolError("invalid_request", "redirect_uri does not match a registered redirect URI");
|
|
265
299
|
}
|
|
266
300
|
const state = stringParam(query.state);
|
|
@@ -436,6 +470,17 @@ const addConsentRoutes = (app, oauth, openApi) => {
|
|
|
436
470
|
});
|
|
437
471
|
}));
|
|
438
472
|
};
|
|
473
|
+
/**
|
|
474
|
+
* A revoke can land after the token route has loaded the client and before this pair exists.
|
|
475
|
+
* A new family has no tombstone yet, so drop the pair when the client is already revoked.
|
|
476
|
+
*/
|
|
477
|
+
const discardIssuedIfClientRevoked = async (clientId, familyId) => {
|
|
478
|
+
const current = await mcpOAuthClient_1.McpOAuthClient.findOneOrNone({ clientId });
|
|
479
|
+
if (!current || current.revokedAt) {
|
|
480
|
+
await mcpOAuthToken_1.McpOAuthToken.revokeFamily(familyId);
|
|
481
|
+
throw new OAuthProtocolError("invalid_client", "Unknown client_id", 401);
|
|
482
|
+
}
|
|
483
|
+
};
|
|
439
484
|
const exchangeAuthorizationCode = async (body, clientId, oauth, userModel) => {
|
|
440
485
|
const code = stringParam(body.code);
|
|
441
486
|
const redirectUri = stringParam(body.redirect_uri);
|
|
@@ -493,6 +538,10 @@ const exchangeAuthorizationCode = async (body, clientId, oauth, userModel) => {
|
|
|
493
538
|
tokenEpoch: (0, auth_2.userTokenEpoch)(user),
|
|
494
539
|
userId: consumed.userId,
|
|
495
540
|
});
|
|
541
|
+
if (!issued.refreshToken) {
|
|
542
|
+
throw new OAuthProtocolError("server_error", "Expected a refresh token", 500);
|
|
543
|
+
}
|
|
544
|
+
await discardIssuedIfClientRevoked(clientId, issued.mcpOAuthToken.familyId);
|
|
496
545
|
return {
|
|
497
546
|
access_token: issued.accessToken,
|
|
498
547
|
expires_in: oauth.accessTokenTtlSeconds,
|
|
@@ -508,7 +557,7 @@ const exchangeRefreshToken = async (body, clientId, oauth, userModel) => {
|
|
|
508
557
|
}
|
|
509
558
|
const refreshTokenHash = (0, mcpOAuthToken_1.hashMcpOAuthSecret)(refreshToken);
|
|
510
559
|
const current = await mcpOAuthToken_1.McpOAuthToken.findOneOrNone({ refreshTokenHash });
|
|
511
|
-
if (!current || current.clientId !== clientId) {
|
|
560
|
+
if (!current || current.clientId !== clientId || current.hasRefreshToken === false) {
|
|
512
561
|
throw new OAuthProtocolError("invalid_grant", "Refresh token is invalid");
|
|
513
562
|
}
|
|
514
563
|
const now = luxon_1.DateTime.now();
|
|
@@ -547,6 +596,10 @@ const exchangeRefreshToken = async (body, clientId, oauth, userModel) => {
|
|
|
547
596
|
tokenEpoch: (0, auth_2.userTokenEpoch)(user),
|
|
548
597
|
userId: rotated.userId,
|
|
549
598
|
});
|
|
599
|
+
if (!issued.refreshToken) {
|
|
600
|
+
throw new OAuthProtocolError("server_error", "Expected a refresh token", 500);
|
|
601
|
+
}
|
|
602
|
+
await discardIssuedIfClientRevoked(clientId, issued.mcpOAuthToken.familyId);
|
|
550
603
|
return {
|
|
551
604
|
access_token: issued.accessToken,
|
|
552
605
|
expires_in: oauth.accessTokenTtlSeconds,
|
|
@@ -555,24 +608,111 @@ const exchangeRefreshToken = async (body, clientId, oauth, userModel) => {
|
|
|
555
608
|
token_type: "Bearer",
|
|
556
609
|
};
|
|
557
610
|
};
|
|
611
|
+
/** RFC 6749 §2.3.1 HTTP Basic client authentication. The id and secret are form-encoded. */
|
|
612
|
+
const readBasicClient = (authorization) => {
|
|
613
|
+
if (!authorization?.startsWith("Basic ")) {
|
|
614
|
+
return {};
|
|
615
|
+
}
|
|
616
|
+
const decoded = Buffer.from(authorization.slice("Basic ".length).trim(), "base64").toString("utf8");
|
|
617
|
+
const separator = decoded.indexOf(":");
|
|
618
|
+
if (separator < 0) {
|
|
619
|
+
return {};
|
|
620
|
+
}
|
|
621
|
+
try {
|
|
622
|
+
return {
|
|
623
|
+
clientId: decodeURIComponent(decoded.slice(0, separator)),
|
|
624
|
+
clientSecret: decodeURIComponent(decoded.slice(separator + 1)),
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
return {};
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
const clientSecretMatches = (client, presented) => {
|
|
632
|
+
if (!presented || !client.clientSecretHash) {
|
|
633
|
+
return false;
|
|
634
|
+
}
|
|
635
|
+
const actual = Buffer.from(client.clientSecretHash);
|
|
636
|
+
const expected = Buffer.from((0, mcpOAuthToken_1.hashMcpOAuthSecret)(presented));
|
|
637
|
+
if (actual.length !== expected.length) {
|
|
638
|
+
return false;
|
|
639
|
+
}
|
|
640
|
+
return (0, node_crypto_1.timingSafeEqual)(actual, expected);
|
|
641
|
+
};
|
|
642
|
+
const assertClientAuthenticated = (client, body, basic) => {
|
|
643
|
+
const method = client.tokenEndpointAuthMethod ?? "none";
|
|
644
|
+
if (method === "none") {
|
|
645
|
+
throw new OAuthProtocolError("invalid_client", "Client authentication failed", 401);
|
|
646
|
+
}
|
|
647
|
+
const presented = method === "client_secret_basic"
|
|
648
|
+
? basic.clientId === client.clientId
|
|
649
|
+
? basic.clientSecret
|
|
650
|
+
: undefined
|
|
651
|
+
: stringParam(body.client_id) === client.clientId
|
|
652
|
+
? stringParam(body.client_secret)
|
|
653
|
+
: undefined;
|
|
654
|
+
const usedOtherMethod = method === "client_secret_basic"
|
|
655
|
+
? Boolean(stringParam(body.client_secret))
|
|
656
|
+
: Boolean(basic.clientSecret);
|
|
657
|
+
if (usedOtherMethod || !clientSecretMatches(client, presented)) {
|
|
658
|
+
throw new OAuthProtocolError("invalid_client", "Client authentication failed", 401);
|
|
659
|
+
}
|
|
660
|
+
};
|
|
661
|
+
const exchangeClientCredentials = async (body, client, oauth, userModel) => {
|
|
662
|
+
if (!client.userId || (client.tokenEndpointAuthMethod ?? "none") === "none") {
|
|
663
|
+
throw new OAuthProtocolError("invalid_client", "Client authentication failed", 401);
|
|
664
|
+
}
|
|
665
|
+
const user = await userModel.findById(client.userId);
|
|
666
|
+
if (!user || userIsDisabled(user)) {
|
|
667
|
+
throw new OAuthProtocolError("invalid_grant", "The user cannot be granted a token");
|
|
668
|
+
}
|
|
669
|
+
const allowed = client.scope
|
|
670
|
+
? client.scope.split(" ").filter((scope) => scope.length > 0)
|
|
671
|
+
: oauth.scopesSupported;
|
|
672
|
+
const scope = parseScope(stringParam(body.scope), allowed);
|
|
673
|
+
const issued = await issueOrInvalidGrant({
|
|
674
|
+
accessTokenTtlSeconds: oauth.accessTokenTtlSeconds,
|
|
675
|
+
clientId: client.clientId,
|
|
676
|
+
includeRefreshToken: false,
|
|
677
|
+
refreshTokenTtlSeconds: oauth.accessTokenTtlSeconds,
|
|
678
|
+
resource: oauth.resource,
|
|
679
|
+
scope,
|
|
680
|
+
tokenEpoch: (0, auth_2.userTokenEpoch)(user),
|
|
681
|
+
userId: client.userId,
|
|
682
|
+
});
|
|
683
|
+
await discardIssuedIfClientRevoked(client.clientId, issued.mcpOAuthToken.familyId);
|
|
684
|
+
return {
|
|
685
|
+
access_token: issued.accessToken,
|
|
686
|
+
expires_in: oauth.accessTokenTtlSeconds,
|
|
687
|
+
scope,
|
|
688
|
+
token_type: "Bearer",
|
|
689
|
+
};
|
|
690
|
+
};
|
|
558
691
|
const addTokenRoutes = (app, oauth, userModel) => {
|
|
559
692
|
app.post("/oauth/token", oauthHandler(async (req, res) => {
|
|
560
693
|
const body = (req.body ?? {});
|
|
561
|
-
const
|
|
694
|
+
const basic = readBasicClient(typeof req.headers.authorization === "string" ? req.headers.authorization : undefined);
|
|
695
|
+
const clientId = stringParam(body.client_id) ?? basic.clientId;
|
|
562
696
|
if (!clientId) {
|
|
563
697
|
throw new OAuthProtocolError("invalid_client", "client_id is required", 401);
|
|
564
698
|
}
|
|
565
699
|
const client = await mcpOAuthClient_1.McpOAuthClient.findOneOrNone({ clientId });
|
|
566
|
-
if (!client) {
|
|
700
|
+
if (!client || client.revokedAt) {
|
|
567
701
|
throw new OAuthProtocolError("invalid_client", "Unknown client_id", 401);
|
|
568
702
|
}
|
|
569
703
|
const grantType = stringParam(body.grant_type);
|
|
570
704
|
if (!grantType || !client.grantTypes.includes(grantType)) {
|
|
571
|
-
throw new OAuthProtocolError("unsupported_grant_type", "grant_type
|
|
705
|
+
throw new OAuthProtocolError("unsupported_grant_type", "grant_type is not allowed for this client");
|
|
706
|
+
}
|
|
707
|
+
if (grantType === "client_credentials" ||
|
|
708
|
+
(client.tokenEndpointAuthMethod && client.tokenEndpointAuthMethod !== "none")) {
|
|
709
|
+
assertClientAuthenticated(client, body, basic);
|
|
572
710
|
}
|
|
573
|
-
const tokens = grantType === "
|
|
574
|
-
? await
|
|
575
|
-
:
|
|
711
|
+
const tokens = grantType === "client_credentials"
|
|
712
|
+
? await exchangeClientCredentials(body, client, oauth, userModel)
|
|
713
|
+
: grantType === "authorization_code"
|
|
714
|
+
? await exchangeAuthorizationCode(body, clientId, oauth, userModel)
|
|
715
|
+
: await exchangeRefreshToken(body, clientId, oauth, userModel);
|
|
576
716
|
res.setHeader("Cache-Control", "no-store");
|
|
577
717
|
res.setHeader("Pragma", "no-cache");
|
|
578
718
|
(0, oauthMetadata_1.sendProtocolJson)(res, 200, tokens);
|