@terreno/api 57.18.0 → 57.20.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 +2071 -2
- 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.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/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- 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/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 +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- 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/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- 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 +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -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 +39 -7
- package/src/betterAuthSetup.ts +457 -38
- 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/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- 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 +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
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")
|
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";
|
|
@@ -125,7 +137,7 @@ export * from "./terrenoPlugin";
|
|
|
125
137
|
export * from "./transformers";
|
|
126
138
|
export * from "./types/consentForm";
|
|
127
139
|
export * from "./types/consentResponse";
|
|
128
|
-
export type { McpOAuthAuthorizationDocument, McpOAuthAuthorizationStatus, McpOAuthClientDocument, McpOAuthRevokedFamilyDocument, McpOAuthTokenDocument, } from "./types/mcpOAuth";
|
|
140
|
+
export type { McpOAuthAuthorizationDocument, McpOAuthAuthorizationStatus, McpOAuthClientDocument, McpOAuthConfidentialClientOptions, McpOAuthRevokedFamilyDocument, McpOAuthTokenDocument, McpOAuthTokenEndpointAuthMethod, } from "./types/mcpOAuth";
|
|
129
141
|
export * from "./utils";
|
|
130
142
|
export * from "./versionCheckPlugin";
|
|
131
143
|
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.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.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.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 = exports.assertAllowed = exports.DEFAULT_WINDOW_MS = exports.DEFAULT_AUTH_MAX = exports.DEFAULT_API_MAX = exports.createRouteRateLimitMiddleware = exports.notificationsBeforeSend = exports.NotificationsApp = exports.getNotificationService = 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 = 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);
|
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);
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* can serve the same metadata and challenge.
|
|
5
5
|
*/
|
|
6
6
|
import type { Response } from "express";
|
|
7
|
-
|
|
7
|
+
/** Grants a public PKCE client may register. Dynamic registration rejects anything else. */
|
|
8
|
+
export declare const PUBLIC_CLIENT_GRANT_TYPES: string[];
|
|
8
9
|
export declare const SUPPORTED_RESPONSE_TYPES: string[];
|
|
9
10
|
export declare const LOOPBACK_HOSTS: Set<string>;
|
|
10
11
|
export interface McpOAuthOptions {
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.sendMcpOAuthChallenge = exports.buildAuthorizationServerMetadata = exports.buildProtectedResourceMetadata = exports.sendProtocolJson = exports.resolveMcpOAuthOption = exports.protectedResourceMetadataPath = exports.LOOPBACK_HOSTS = exports.SUPPORTED_RESPONSE_TYPES = exports.
|
|
3
|
+
exports.sendMcpOAuthChallenge = exports.buildAuthorizationServerMetadata = exports.buildProtectedResourceMetadata = exports.sendProtocolJson = exports.resolveMcpOAuthOption = exports.protectedResourceMetadataPath = exports.LOOPBACK_HOSTS = exports.SUPPORTED_RESPONSE_TYPES = exports.PUBLIC_CLIENT_GRANT_TYPES = void 0;
|
|
4
4
|
const errors_1 = require("../errors");
|
|
5
5
|
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 60 * 60;
|
|
6
6
|
const DEFAULT_REFRESH_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
|
|
7
7
|
const DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS = 10 * 60;
|
|
8
8
|
const DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS = 60;
|
|
9
9
|
const DEFAULT_SCOPES = ["mcp"];
|
|
10
|
-
|
|
10
|
+
/** Grants a public PKCE client may register. Dynamic registration rejects anything else. */
|
|
11
|
+
exports.PUBLIC_CLIENT_GRANT_TYPES = ["authorization_code", "refresh_token"];
|
|
12
|
+
const SUPPORTED_GRANT_TYPES = [...exports.PUBLIC_CLIENT_GRANT_TYPES, "client_credentials"];
|
|
13
|
+
const SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS = ["none", "client_secret_basic", "client_secret_post"];
|
|
11
14
|
exports.SUPPORTED_RESPONSE_TYPES = ["code"];
|
|
12
15
|
exports.LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
13
16
|
const misconfigured = (detail) => new errors_1.APIError({
|
|
@@ -107,14 +110,14 @@ const buildAuthorizationServerMetadata = (oauth) => ({
|
|
|
107
110
|
authorization_endpoint: `${oauth.issuer}/oauth/authorize`,
|
|
108
111
|
authorization_response_iss_parameter_supported: true,
|
|
109
112
|
code_challenge_methods_supported: ["S256"],
|
|
110
|
-
grant_types_supported:
|
|
113
|
+
grant_types_supported: SUPPORTED_GRANT_TYPES,
|
|
111
114
|
issuer: oauth.issuer,
|
|
112
115
|
response_types_supported: exports.SUPPORTED_RESPONSE_TYPES,
|
|
113
116
|
revocation_endpoint: `${oauth.issuer}/oauth/revoke`,
|
|
114
117
|
revocation_endpoint_auth_methods_supported: ["none"],
|
|
115
118
|
scopes_supported: oauth.scopesSupported,
|
|
116
119
|
token_endpoint: `${oauth.issuer}/oauth/token`,
|
|
117
|
-
token_endpoint_auth_methods_supported:
|
|
120
|
+
token_endpoint_auth_methods_supported: SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS,
|
|
118
121
|
});
|
|
119
122
|
exports.buildAuthorizationServerMetadata = buildAuthorizationServerMetadata;
|
|
120
123
|
/**
|
|
@@ -45,6 +45,42 @@ const consentResponseSchema = new mongoose_1.default.Schema({
|
|
|
45
45
|
required: true,
|
|
46
46
|
type: String,
|
|
47
47
|
},
|
|
48
|
+
provisional: {
|
|
49
|
+
default: false,
|
|
50
|
+
description: "Whether another user recorded this agreement on the user's behalf. The user still sees the form and signs it themselves",
|
|
51
|
+
type: Boolean,
|
|
52
|
+
},
|
|
53
|
+
provisionalNote: {
|
|
54
|
+
description: "Required note from the provisional signer explaining how consent was obtained",
|
|
55
|
+
maxlength: 2000,
|
|
56
|
+
required: [
|
|
57
|
+
function () {
|
|
58
|
+
return this.provisional === true;
|
|
59
|
+
},
|
|
60
|
+
"provisionalNote is required for a provisional signature",
|
|
61
|
+
],
|
|
62
|
+
trim: true,
|
|
63
|
+
type: String,
|
|
64
|
+
},
|
|
65
|
+
provisionalSignedBy: {
|
|
66
|
+
description: "The user who recorded this provisional signature",
|
|
67
|
+
ref: "User",
|
|
68
|
+
required: [
|
|
69
|
+
function () {
|
|
70
|
+
return this.provisional === true;
|
|
71
|
+
},
|
|
72
|
+
"provisionalSignedBy is required for a provisional signature",
|
|
73
|
+
],
|
|
74
|
+
type: mongoose_1.default.Schema.Types.ObjectId,
|
|
75
|
+
},
|
|
76
|
+
provisionalSignerIp: {
|
|
77
|
+
description: "IP address of the provisional signer, captured for audit purposes",
|
|
78
|
+
type: String,
|
|
79
|
+
},
|
|
80
|
+
provisionalSignerUserAgent: {
|
|
81
|
+
description: "User-agent string of the provisional signer's browser or app",
|
|
82
|
+
type: String,
|
|
83
|
+
},
|
|
48
84
|
signature: {
|
|
49
85
|
description: "Base64-encoded signature image or typed signature text, if captured",
|
|
50
86
|
type: String,
|
|
@@ -64,6 +100,21 @@ const consentResponseSchema = new mongoose_1.default.Schema({
|
|
|
64
100
|
required: true,
|
|
65
101
|
type: mongoose_1.default.Schema.Types.ObjectId,
|
|
66
102
|
},
|
|
103
|
+
voidedAt: {
|
|
104
|
+
description: "When a provisional signature was voided. Voided signatures no longer count as consent",
|
|
105
|
+
type: Date,
|
|
106
|
+
},
|
|
107
|
+
voidedBy: {
|
|
108
|
+
description: "The user who voided this provisional signature",
|
|
109
|
+
ref: "User",
|
|
110
|
+
type: mongoose_1.default.Schema.Types.ObjectId,
|
|
111
|
+
},
|
|
112
|
+
voidReason: {
|
|
113
|
+
description: "Why the provisional signature was voided",
|
|
114
|
+
maxlength: 2000,
|
|
115
|
+
trim: true,
|
|
116
|
+
type: String,
|
|
117
|
+
},
|
|
67
118
|
}, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
|
|
68
119
|
consentResponseSchema.index({ consentFormId: 1, userId: 1 });
|
|
69
120
|
consentResponseSchema.plugin(plugins_1.createdUpdatedPlugin);
|
|
@@ -4,11 +4,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.McpOAuthClient = void 0;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const luxon_1 = require("luxon");
|
|
7
9
|
const mongoose_1 = __importDefault(require("mongoose"));
|
|
8
10
|
const plugins_1 = require("../plugins");
|
|
11
|
+
const mcpOAuthToken_1 = require("./mcpOAuthToken");
|
|
9
12
|
const mcpOAuthClientSchema = new mongoose_1.default.Schema({
|
|
10
13
|
clientId: {
|
|
11
|
-
description: "Public OAuth client identifier
|
|
14
|
+
description: "Public OAuth client identifier",
|
|
12
15
|
required: true,
|
|
13
16
|
type: String,
|
|
14
17
|
unique: true,
|
|
@@ -18,25 +21,98 @@ const mcpOAuthClientSchema = new mongoose_1.default.Schema({
|
|
|
18
21
|
trim: true,
|
|
19
22
|
type: String,
|
|
20
23
|
},
|
|
24
|
+
clientSecretHash: {
|
|
25
|
+
description: "SHA-256 hash of the confidential client secret. Unset for public clients",
|
|
26
|
+
type: String,
|
|
27
|
+
},
|
|
21
28
|
grantTypes: {
|
|
22
29
|
description: "OAuth grant types the client may use",
|
|
23
30
|
type: [String],
|
|
24
31
|
},
|
|
25
32
|
redirectUris: {
|
|
26
|
-
description: "
|
|
33
|
+
description: "Registered redirect URIs. Loopback hosts (localhost, 127.0.0.1, [::1]) match any port; every other URI must match exactly",
|
|
27
34
|
type: [String],
|
|
28
35
|
},
|
|
29
36
|
responseTypes: {
|
|
30
37
|
description: "OAuth response types the client may request",
|
|
31
38
|
type: [String],
|
|
32
39
|
},
|
|
40
|
+
revokedAt: {
|
|
41
|
+
description: "When the client was revoked. A revoked client cannot take new grants",
|
|
42
|
+
type: Date,
|
|
43
|
+
},
|
|
33
44
|
scope: {
|
|
34
45
|
description: "Space-separated scopes the client registered for",
|
|
35
46
|
type: String,
|
|
36
47
|
},
|
|
48
|
+
tokenEndpointAuthMethod: {
|
|
49
|
+
description: "How the client authenticates at the token endpoint. none is a public client; client_secret_basic and client_secret_post are confidential",
|
|
50
|
+
enum: ["none", "client_secret_basic", "client_secret_post"],
|
|
51
|
+
type: String,
|
|
52
|
+
},
|
|
53
|
+
userId: {
|
|
54
|
+
description: "User a client_credentials token acts as",
|
|
55
|
+
ref: "User",
|
|
56
|
+
type: mongoose_1.default.Schema.Types.ObjectId,
|
|
57
|
+
},
|
|
37
58
|
}, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
|
|
38
59
|
mcpOAuthClientSchema.plugin(plugins_1.createdUpdatedPlugin);
|
|
39
60
|
mcpOAuthClientSchema.plugin(plugins_1.findOneOrNone);
|
|
40
61
|
mcpOAuthClientSchema.plugin(plugins_1.findExactlyOne);
|
|
62
|
+
const revokeTokensForClient = async (clientId) => {
|
|
63
|
+
if (!clientId) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
await mcpOAuthToken_1.McpOAuthToken.revokeClient(clientId);
|
|
67
|
+
};
|
|
68
|
+
mcpOAuthClientSchema.pre("deleteOne", { document: true, query: false }, async function () {
|
|
69
|
+
await revokeTokensForClient(this.clientId);
|
|
70
|
+
});
|
|
71
|
+
mcpOAuthClientSchema.pre("deleteOne", { document: false, query: true }, async function () {
|
|
72
|
+
// deleteOne removes one document. Pin that document so its tokens are the ones revoked.
|
|
73
|
+
const [existing] = await this.model.find(this.getFilter()).limit(1).select({ _id: 1, clientId: 1 });
|
|
74
|
+
if (!existing) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
this.setQuery({ _id: existing._id });
|
|
78
|
+
await revokeTokensForClient(existing.clientId);
|
|
79
|
+
});
|
|
80
|
+
mcpOAuthClientSchema.pre("findOneAndDelete", async function () {
|
|
81
|
+
const [existing] = await this.model.find(this.getFilter()).limit(1).select({ _id: 1, clientId: 1 });
|
|
82
|
+
if (!existing) {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
this.setQuery({ _id: existing._id });
|
|
86
|
+
await revokeTokensForClient(existing.clientId);
|
|
87
|
+
});
|
|
88
|
+
mcpOAuthClientSchema.pre("deleteMany", async function () {
|
|
89
|
+
const clients = await this.model.find(this.getFilter()).select({ clientId: 1 });
|
|
90
|
+
for (const client of clients) {
|
|
91
|
+
await revokeTokensForClient(client.clientId);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
mcpOAuthClientSchema.statics = {
|
|
95
|
+
...mcpOAuthClientSchema.statics,
|
|
96
|
+
async issueConfidential(options) {
|
|
97
|
+
const clientSecret = (0, mcpOAuthToken_1.generateMcpOAuthSecret)("mcpcs_");
|
|
98
|
+
const client = await this.create({
|
|
99
|
+
clientId: options.clientId ?? (0, node_crypto_1.randomUUID)(),
|
|
100
|
+
clientName: options.clientName,
|
|
101
|
+
clientSecretHash: (0, mcpOAuthToken_1.hashMcpOAuthSecret)(clientSecret),
|
|
102
|
+
grantTypes: ["client_credentials"],
|
|
103
|
+
redirectUris: [],
|
|
104
|
+
responseTypes: [],
|
|
105
|
+
scope: options.scope,
|
|
106
|
+
tokenEndpointAuthMethod: options.tokenEndpointAuthMethod,
|
|
107
|
+
userId: new mongoose_1.default.Types.ObjectId(String(options.userId)),
|
|
108
|
+
});
|
|
109
|
+
return { client, clientSecret };
|
|
110
|
+
},
|
|
111
|
+
async revoke(clientId) {
|
|
112
|
+
await this.updateOne({ clientId, revokedAt: { $exists: false } }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
|
|
113
|
+
await mcpOAuthToken_1.McpOAuthToken.revokeClient(clientId);
|
|
114
|
+
return this.findOneOrNone({ clientId });
|
|
115
|
+
},
|
|
116
|
+
};
|
|
41
117
|
exports.McpOAuthClient = mongoose_1.default.models.TerrenoMcpOAuthClient ??
|
|
42
118
|
mongoose_1.default.model("TerrenoMcpOAuthClient", mcpOAuthClientSchema, "mcpoauthclients");
|