@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/src/mcp/oauth.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* authorization-code flow with PKCE S256. Terreno is backend-only, so the app hosts the consent
|
|
6
6
|
* screen at `consentUrl` and calls the approve/deny endpoints with the signed-in user's JWT.
|
|
7
7
|
*/
|
|
8
|
-
import {createHash, randomUUID} from "node:crypto";
|
|
8
|
+
import {createHash, randomUUID, timingSafeEqual} from "node:crypto";
|
|
9
9
|
import type {Application, NextFunction, Request, RequestHandler, Response} from "express";
|
|
10
10
|
import {DateTime} from "luxon";
|
|
11
11
|
import mongoose from "mongoose";
|
|
@@ -27,6 +27,7 @@ import {MCP_SERVICE_TOKEN_PREFIX} from "../models/mcpServiceToken";
|
|
|
27
27
|
import {createOpenApiBuilder} from "../openApiBuilder";
|
|
28
28
|
import type {
|
|
29
29
|
McpOAuthAuthorizationDocument,
|
|
30
|
+
McpOAuthClientDocument,
|
|
30
31
|
McpOAuthTokenIssueOptions,
|
|
31
32
|
McpOAuthTokenModel,
|
|
32
33
|
} from "../types/mcpOAuth";
|
|
@@ -35,9 +36,9 @@ import {
|
|
|
35
36
|
buildAuthorizationServerMetadata,
|
|
36
37
|
buildProtectedResourceMetadata,
|
|
37
38
|
LOOPBACK_HOSTS,
|
|
39
|
+
PUBLIC_CLIENT_GRANT_TYPES,
|
|
38
40
|
protectedResourceMetadataPath,
|
|
39
41
|
type ResolvedMcpOAuthOptions,
|
|
40
|
-
SUPPORTED_GRANT_TYPES,
|
|
41
42
|
SUPPORTED_RESPONSE_TYPES,
|
|
42
43
|
sendProtocolJson,
|
|
43
44
|
} from "./oauthMetadata";
|
|
@@ -261,11 +262,11 @@ const addRegistrationRoute = (app: Application, oauth: ResolvedMcpOAuthOptions):
|
|
|
261
262
|
"Only public clients are supported: token_endpoint_auth_method must be none"
|
|
262
263
|
);
|
|
263
264
|
}
|
|
264
|
-
const grantTypes = (body.grant_types as unknown[] | undefined) ??
|
|
265
|
+
const grantTypes = (body.grant_types as unknown[] | undefined) ?? PUBLIC_CLIENT_GRANT_TYPES;
|
|
265
266
|
if (
|
|
266
267
|
!Array.isArray(grantTypes) ||
|
|
267
268
|
!grantTypes.includes("authorization_code") ||
|
|
268
|
-
grantTypes.some((grant) => !
|
|
269
|
+
grantTypes.some((grant) => !PUBLIC_CLIENT_GRANT_TYPES.includes(grant as string))
|
|
269
270
|
) {
|
|
270
271
|
throw new OAuthProtocolError(
|
|
271
272
|
"invalid_client_metadata",
|
|
@@ -312,6 +313,41 @@ const addRegistrationRoute = (app: Application, oauth: ResolvedMcpOAuthOptions):
|
|
|
312
313
|
);
|
|
313
314
|
};
|
|
314
315
|
|
|
316
|
+
/**
|
|
317
|
+
* RFC 8252 §7.3: a native client binds an ephemeral port, so a loopback redirect matches a
|
|
318
|
+
* registered loopback URI when scheme, hostname, path, and query match. The port is ignored.
|
|
319
|
+
* `localhost`, `127.0.0.1`, and `[::1]` stay distinct hosts. Every other URI stays an exact match.
|
|
320
|
+
*/
|
|
321
|
+
const redirectUriMatchesRegistered = (requested: string, registered: string[]): boolean => {
|
|
322
|
+
if (registered.includes(requested)) {
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
let requestedUrl: URL;
|
|
326
|
+
try {
|
|
327
|
+
requestedUrl = new URL(requested);
|
|
328
|
+
} catch {
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
if (!LOOPBACK_HOSTS.has(requestedUrl.hostname)) {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
return registered.some((candidate) => {
|
|
335
|
+
let registeredUrl: URL;
|
|
336
|
+
try {
|
|
337
|
+
registeredUrl = new URL(candidate);
|
|
338
|
+
} catch {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
return (
|
|
342
|
+
LOOPBACK_HOSTS.has(registeredUrl.hostname) &&
|
|
343
|
+
registeredUrl.protocol === requestedUrl.protocol &&
|
|
344
|
+
registeredUrl.hostname === requestedUrl.hostname &&
|
|
345
|
+
registeredUrl.pathname === requestedUrl.pathname &&
|
|
346
|
+
registeredUrl.search === requestedUrl.search
|
|
347
|
+
);
|
|
348
|
+
});
|
|
349
|
+
};
|
|
350
|
+
|
|
315
351
|
const addAuthorizeRoute = (app: Application, oauth: ResolvedMcpOAuthOptions): void => {
|
|
316
352
|
app.get(
|
|
317
353
|
"/oauth/authorize",
|
|
@@ -322,7 +358,7 @@ const addAuthorizeRoute = (app: Application, oauth: ResolvedMcpOAuthOptions): vo
|
|
|
322
358
|
throw new OAuthProtocolError("invalid_request", "client_id is required");
|
|
323
359
|
}
|
|
324
360
|
const client = await McpOAuthClient.findOneOrNone({clientId});
|
|
325
|
-
if (!client) {
|
|
361
|
+
if (!client || client.revokedAt) {
|
|
326
362
|
throw new OAuthProtocolError("invalid_request", "Unknown client_id");
|
|
327
363
|
}
|
|
328
364
|
// RFC 6749 §4.1.2.1: never redirect to an unverified URI, so these two fail in place.
|
|
@@ -330,7 +366,7 @@ const addAuthorizeRoute = (app: Application, oauth: ResolvedMcpOAuthOptions): vo
|
|
|
330
366
|
const redirectUri =
|
|
331
367
|
requestedRedirect ??
|
|
332
368
|
(client.redirectUris.length === 1 ? client.redirectUris[0] : undefined);
|
|
333
|
-
if (!redirectUri || !client.redirectUris
|
|
369
|
+
if (!redirectUri || !redirectUriMatchesRegistered(redirectUri, client.redirectUris)) {
|
|
334
370
|
throw new OAuthProtocolError(
|
|
335
371
|
"invalid_request",
|
|
336
372
|
"redirect_uri does not match a registered redirect URI"
|
|
@@ -561,6 +597,18 @@ interface TokenResponse {
|
|
|
561
597
|
token_type: "Bearer";
|
|
562
598
|
}
|
|
563
599
|
|
|
600
|
+
/**
|
|
601
|
+
* A revoke can land after the token route has loaded the client and before this pair exists.
|
|
602
|
+
* A new family has no tombstone yet, so drop the pair when the client is already revoked.
|
|
603
|
+
*/
|
|
604
|
+
const discardIssuedIfClientRevoked = async (clientId: string, familyId: string): Promise<void> => {
|
|
605
|
+
const current = await McpOAuthClient.findOneOrNone({clientId});
|
|
606
|
+
if (!current || current.revokedAt) {
|
|
607
|
+
await McpOAuthToken.revokeFamily(familyId);
|
|
608
|
+
throw new OAuthProtocolError("invalid_client", "Unknown client_id", 401);
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
|
|
564
612
|
const exchangeAuthorizationCode = async (
|
|
565
613
|
body: Record<string, unknown>,
|
|
566
614
|
clientId: string,
|
|
@@ -642,6 +690,10 @@ const exchangeAuthorizationCode = async (
|
|
|
642
690
|
tokenEpoch: userTokenEpoch(user),
|
|
643
691
|
userId: consumed.userId as mongoose.Types.ObjectId,
|
|
644
692
|
});
|
|
693
|
+
if (!issued.refreshToken) {
|
|
694
|
+
throw new OAuthProtocolError("server_error", "Expected a refresh token", 500);
|
|
695
|
+
}
|
|
696
|
+
await discardIssuedIfClientRevoked(clientId, issued.mcpOAuthToken.familyId);
|
|
645
697
|
return {
|
|
646
698
|
access_token: issued.accessToken,
|
|
647
699
|
expires_in: oauth.accessTokenTtlSeconds,
|
|
@@ -663,7 +715,7 @@ const exchangeRefreshToken = async (
|
|
|
663
715
|
}
|
|
664
716
|
const refreshTokenHash = hashMcpOAuthSecret(refreshToken);
|
|
665
717
|
const current = await McpOAuthToken.findOneOrNone({refreshTokenHash});
|
|
666
|
-
if (!current || current.clientId !== clientId) {
|
|
718
|
+
if (!current || current.clientId !== clientId || current.hasRefreshToken === false) {
|
|
667
719
|
throw new OAuthProtocolError("invalid_grant", "Refresh token is invalid");
|
|
668
720
|
}
|
|
669
721
|
const now = DateTime.now();
|
|
@@ -709,6 +761,10 @@ const exchangeRefreshToken = async (
|
|
|
709
761
|
tokenEpoch: userTokenEpoch(user),
|
|
710
762
|
userId: rotated.userId,
|
|
711
763
|
});
|
|
764
|
+
if (!issued.refreshToken) {
|
|
765
|
+
throw new OAuthProtocolError("server_error", "Expected a refresh token", 500);
|
|
766
|
+
}
|
|
767
|
+
await discardIssuedIfClientRevoked(clientId, issued.mcpOAuthToken.familyId);
|
|
712
768
|
return {
|
|
713
769
|
access_token: issued.accessToken,
|
|
714
770
|
expires_in: oauth.accessTokenTtlSeconds,
|
|
@@ -718,6 +774,110 @@ const exchangeRefreshToken = async (
|
|
|
718
774
|
};
|
|
719
775
|
};
|
|
720
776
|
|
|
777
|
+
interface BasicClientCredentials {
|
|
778
|
+
clientId?: string;
|
|
779
|
+
clientSecret?: string;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** RFC 6749 §2.3.1 HTTP Basic client authentication. The id and secret are form-encoded. */
|
|
783
|
+
const readBasicClient = (authorization: string | undefined): BasicClientCredentials => {
|
|
784
|
+
if (!authorization?.startsWith("Basic ")) {
|
|
785
|
+
return {};
|
|
786
|
+
}
|
|
787
|
+
const decoded = Buffer.from(authorization.slice("Basic ".length).trim(), "base64").toString(
|
|
788
|
+
"utf8"
|
|
789
|
+
);
|
|
790
|
+
const separator = decoded.indexOf(":");
|
|
791
|
+
if (separator < 0) {
|
|
792
|
+
return {};
|
|
793
|
+
}
|
|
794
|
+
try {
|
|
795
|
+
return {
|
|
796
|
+
clientId: decodeURIComponent(decoded.slice(0, separator)),
|
|
797
|
+
clientSecret: decodeURIComponent(decoded.slice(separator + 1)),
|
|
798
|
+
};
|
|
799
|
+
} catch {
|
|
800
|
+
return {};
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
|
|
804
|
+
const clientSecretMatches = (
|
|
805
|
+
client: McpOAuthClientDocument,
|
|
806
|
+
presented: string | undefined
|
|
807
|
+
): boolean => {
|
|
808
|
+
if (!presented || !client.clientSecretHash) {
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
811
|
+
const actual = Buffer.from(client.clientSecretHash);
|
|
812
|
+
const expected = Buffer.from(hashMcpOAuthSecret(presented));
|
|
813
|
+
if (actual.length !== expected.length) {
|
|
814
|
+
return false;
|
|
815
|
+
}
|
|
816
|
+
return timingSafeEqual(actual, expected);
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
const assertClientAuthenticated = (
|
|
820
|
+
client: McpOAuthClientDocument,
|
|
821
|
+
body: Record<string, unknown>,
|
|
822
|
+
basic: BasicClientCredentials
|
|
823
|
+
): void => {
|
|
824
|
+
const method = client.tokenEndpointAuthMethod ?? "none";
|
|
825
|
+
if (method === "none") {
|
|
826
|
+
throw new OAuthProtocolError("invalid_client", "Client authentication failed", 401);
|
|
827
|
+
}
|
|
828
|
+
const presented =
|
|
829
|
+
method === "client_secret_basic"
|
|
830
|
+
? basic.clientId === client.clientId
|
|
831
|
+
? basic.clientSecret
|
|
832
|
+
: undefined
|
|
833
|
+
: stringParam(body.client_id) === client.clientId
|
|
834
|
+
? stringParam(body.client_secret)
|
|
835
|
+
: undefined;
|
|
836
|
+
const usedOtherMethod =
|
|
837
|
+
method === "client_secret_basic"
|
|
838
|
+
? Boolean(stringParam(body.client_secret))
|
|
839
|
+
: Boolean(basic.clientSecret);
|
|
840
|
+
if (usedOtherMethod || !clientSecretMatches(client, presented)) {
|
|
841
|
+
throw new OAuthProtocolError("invalid_client", "Client authentication failed", 401);
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
|
|
845
|
+
const exchangeClientCredentials = async (
|
|
846
|
+
body: Record<string, unknown>,
|
|
847
|
+
client: McpOAuthClientDocument,
|
|
848
|
+
oauth: ResolvedMcpOAuthOptions,
|
|
849
|
+
userModel: UserModel
|
|
850
|
+
): Promise<Record<string, unknown>> => {
|
|
851
|
+
if (!client.userId || (client.tokenEndpointAuthMethod ?? "none") === "none") {
|
|
852
|
+
throw new OAuthProtocolError("invalid_client", "Client authentication failed", 401);
|
|
853
|
+
}
|
|
854
|
+
const user = await userModel.findById(client.userId);
|
|
855
|
+
if (!user || userIsDisabled(user)) {
|
|
856
|
+
throw new OAuthProtocolError("invalid_grant", "The user cannot be granted a token");
|
|
857
|
+
}
|
|
858
|
+
const allowed = client.scope
|
|
859
|
+
? client.scope.split(" ").filter((scope) => scope.length > 0)
|
|
860
|
+
: oauth.scopesSupported;
|
|
861
|
+
const scope = parseScope(stringParam(body.scope), allowed);
|
|
862
|
+
const issued = await issueOrInvalidGrant({
|
|
863
|
+
accessTokenTtlSeconds: oauth.accessTokenTtlSeconds,
|
|
864
|
+
clientId: client.clientId,
|
|
865
|
+
includeRefreshToken: false,
|
|
866
|
+
refreshTokenTtlSeconds: oauth.accessTokenTtlSeconds,
|
|
867
|
+
resource: oauth.resource,
|
|
868
|
+
scope,
|
|
869
|
+
tokenEpoch: userTokenEpoch(user),
|
|
870
|
+
userId: client.userId,
|
|
871
|
+
});
|
|
872
|
+
await discardIssuedIfClientRevoked(client.clientId, issued.mcpOAuthToken.familyId);
|
|
873
|
+
return {
|
|
874
|
+
access_token: issued.accessToken,
|
|
875
|
+
expires_in: oauth.accessTokenTtlSeconds,
|
|
876
|
+
scope,
|
|
877
|
+
token_type: "Bearer",
|
|
878
|
+
};
|
|
879
|
+
};
|
|
880
|
+
|
|
721
881
|
const addTokenRoutes = (
|
|
722
882
|
app: Application,
|
|
723
883
|
oauth: ResolvedMcpOAuthOptions,
|
|
@@ -727,25 +887,36 @@ const addTokenRoutes = (
|
|
|
727
887
|
"/oauth/token",
|
|
728
888
|
oauthHandler(async (req, res) => {
|
|
729
889
|
const body = (req.body ?? {}) as Record<string, unknown>;
|
|
730
|
-
const
|
|
890
|
+
const basic = readBasicClient(
|
|
891
|
+
typeof req.headers.authorization === "string" ? req.headers.authorization : undefined
|
|
892
|
+
);
|
|
893
|
+
const clientId = stringParam(body.client_id) ?? basic.clientId;
|
|
731
894
|
if (!clientId) {
|
|
732
895
|
throw new OAuthProtocolError("invalid_client", "client_id is required", 401);
|
|
733
896
|
}
|
|
734
897
|
const client = await McpOAuthClient.findOneOrNone({clientId});
|
|
735
|
-
if (!client) {
|
|
898
|
+
if (!client || client.revokedAt) {
|
|
736
899
|
throw new OAuthProtocolError("invalid_client", "Unknown client_id", 401);
|
|
737
900
|
}
|
|
738
901
|
const grantType = stringParam(body.grant_type);
|
|
739
902
|
if (!grantType || !client.grantTypes.includes(grantType)) {
|
|
740
903
|
throw new OAuthProtocolError(
|
|
741
904
|
"unsupported_grant_type",
|
|
742
|
-
"grant_type
|
|
905
|
+
"grant_type is not allowed for this client"
|
|
743
906
|
);
|
|
744
907
|
}
|
|
908
|
+
if (
|
|
909
|
+
grantType === "client_credentials" ||
|
|
910
|
+
(client.tokenEndpointAuthMethod && client.tokenEndpointAuthMethod !== "none")
|
|
911
|
+
) {
|
|
912
|
+
assertClientAuthenticated(client, body, basic);
|
|
913
|
+
}
|
|
745
914
|
const tokens =
|
|
746
|
-
grantType === "
|
|
747
|
-
? await
|
|
748
|
-
:
|
|
915
|
+
grantType === "client_credentials"
|
|
916
|
+
? await exchangeClientCredentials(body, client, oauth, userModel)
|
|
917
|
+
: grantType === "authorization_code"
|
|
918
|
+
? await exchangeAuthorizationCode(body, clientId, oauth, userModel)
|
|
919
|
+
: await exchangeRefreshToken(body, clientId, oauth, userModel);
|
|
749
920
|
res.setHeader("Cache-Control", "no-store");
|
|
750
921
|
res.setHeader("Pragma", "no-cache");
|
|
751
922
|
sendProtocolJson(res, 200, tokens);
|
package/src/mcp/oauthMetadata.ts
CHANGED
|
@@ -13,7 +13,10 @@ const DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS = 10 * 60;
|
|
|
13
13
|
const DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS = 60;
|
|
14
14
|
const DEFAULT_SCOPES = ["mcp"];
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
/** Grants a public PKCE client may register. Dynamic registration rejects anything else. */
|
|
17
|
+
export const PUBLIC_CLIENT_GRANT_TYPES = ["authorization_code", "refresh_token"];
|
|
18
|
+
const SUPPORTED_GRANT_TYPES = [...PUBLIC_CLIENT_GRANT_TYPES, "client_credentials"];
|
|
19
|
+
const SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS = ["none", "client_secret_basic", "client_secret_post"];
|
|
17
20
|
export const SUPPORTED_RESPONSE_TYPES = ["code"];
|
|
18
21
|
export const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
19
22
|
|
|
@@ -208,7 +211,7 @@ export const buildAuthorizationServerMetadata = (
|
|
|
208
211
|
revocation_endpoint_auth_methods_supported: ["none"],
|
|
209
212
|
scopes_supported: oauth.scopesSupported,
|
|
210
213
|
token_endpoint: `${oauth.issuer}/oauth/token`,
|
|
211
|
-
token_endpoint_auth_methods_supported:
|
|
214
|
+
token_endpoint_auth_methods_supported: SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS,
|
|
212
215
|
});
|
|
213
216
|
|
|
214
217
|
/**
|
package/src/mcp/server.ts
CHANGED
|
@@ -7,6 +7,13 @@ import type {User, UserModel} from "../auth";
|
|
|
7
7
|
import type {BetterAuthInstance} from "../betterAuthSetup";
|
|
8
8
|
import {logger} from "../logger";
|
|
9
9
|
import {setRequestContext} from "../requestContext";
|
|
10
|
+
import {
|
|
11
|
+
filterEnabledMcpTools,
|
|
12
|
+
type McpToolCallRecord,
|
|
13
|
+
type ResolvedMcpRequestLogOptions,
|
|
14
|
+
recordMcpToolCall,
|
|
15
|
+
syncMcpToolSettings,
|
|
16
|
+
} from "./adminTracking";
|
|
10
17
|
import {extractAuthFromHeaders, type MCPAuthContext, type MCPAuthResult} from "./auth";
|
|
11
18
|
import {type ResolvedMcpOAuthOptions, sendMcpOAuthChallenge} from "./oauthMetadata";
|
|
12
19
|
import {getAllMCPTools, type MCPToolDefinition} from "./toolGenerator";
|
|
@@ -20,6 +27,13 @@ export interface MCPServerOptions {
|
|
|
20
27
|
* request without valid credentials with a 401 RFC 9728 challenge.
|
|
21
28
|
*/
|
|
22
29
|
mcpOAuth?: ResolvedMcpOAuthOptions;
|
|
30
|
+
/** When set, each tool call writes a metadata-only `McpRequestLog` row. */
|
|
31
|
+
requestLog?: ResolvedMcpRequestLogOptions;
|
|
32
|
+
/**
|
|
33
|
+
* When true, tools are registered in `McpToolSetting` on mount and tools an admin turned off
|
|
34
|
+
* are left out of `tools/list` and `tools/call`.
|
|
35
|
+
*/
|
|
36
|
+
toolSettings?: boolean;
|
|
23
37
|
}
|
|
24
38
|
|
|
25
39
|
// Auth is resolved once in the Express handler (which may answer 401) and read back by the
|
|
@@ -40,13 +54,29 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
|
|
|
40
54
|
|
|
41
55
|
logger.info(`Mounting MCP server with ${tools.length} tools at /mcp`);
|
|
42
56
|
|
|
57
|
+
if (options.toolSettings) {
|
|
58
|
+
void syncMcpToolSettings(tools).catch((error: unknown) => {
|
|
59
|
+
logger.warn(`[mcp] Could not register tools in McpToolSetting: ${String(error)}`);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const buildServer = async (auth: MCPAuthResult | undefined): Promise<McpServer> => {
|
|
64
|
+
const served = options.toolSettings ? await filterEnabledMcpTools(tools) : tools;
|
|
65
|
+
const onToolCall = options.requestLog
|
|
66
|
+
? (record: Omit<McpToolCallRecord, "auth">): void => {
|
|
67
|
+
recordMcpToolCall({...record, auth}, options.requestLog as ResolvedMcpRequestLogOptions);
|
|
68
|
+
}
|
|
69
|
+
: undefined;
|
|
70
|
+
return createMcpServerInstance(served, auth?.user, onToolCall);
|
|
71
|
+
};
|
|
72
|
+
|
|
43
73
|
// The 2026-07-28 handler is stateless: it creates one server per request and also serves
|
|
44
74
|
// 2025-era clients through the SDK's stateless legacy fallback.
|
|
45
75
|
const handler = createMcpHandler(
|
|
46
76
|
async ({requestInfo}) => {
|
|
47
77
|
const stored = mcpAuthStorage.getStore();
|
|
48
78
|
if (stored) {
|
|
49
|
-
return
|
|
79
|
+
return buildServer(stored.auth);
|
|
50
80
|
}
|
|
51
81
|
const headers: Record<string, string> = {};
|
|
52
82
|
requestInfo?.headers.forEach((value, key) => {
|
|
@@ -54,7 +84,7 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
|
|
|
54
84
|
});
|
|
55
85
|
const auth = await extractAuthFromHeaders(headers, authContext);
|
|
56
86
|
recordMcpAuth(auth);
|
|
57
|
-
return
|
|
87
|
+
return buildServer(auth);
|
|
58
88
|
},
|
|
59
89
|
{
|
|
60
90
|
legacy: "stateless",
|
|
@@ -99,7 +129,18 @@ const recordMcpAuth = (auth: MCPAuthResult | undefined): void => {
|
|
|
99
129
|
});
|
|
100
130
|
};
|
|
101
131
|
|
|
102
|
-
const
|
|
132
|
+
const errorName = (error: unknown): string => {
|
|
133
|
+
if (error instanceof Error) {
|
|
134
|
+
return error.name;
|
|
135
|
+
}
|
|
136
|
+
return typeof error;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const createMcpServerInstance = (
|
|
140
|
+
tools: MCPToolDefinition[],
|
|
141
|
+
user?: User,
|
|
142
|
+
onToolCall?: (record: Omit<McpToolCallRecord, "auth">) => void
|
|
143
|
+
): McpServer => {
|
|
103
144
|
const server = new McpServer(
|
|
104
145
|
{
|
|
105
146
|
name: "terreno-api-mcp",
|
|
@@ -120,7 +161,29 @@ const createMcpServerInstance = (tools: MCPToolDefinition[], user?: User): McpSe
|
|
|
120
161
|
description: tool.description,
|
|
121
162
|
inputSchema: tool.zodSchema,
|
|
122
163
|
},
|
|
123
|
-
async (args: unknown) =>
|
|
164
|
+
async (args: unknown) => {
|
|
165
|
+
if (!onToolCall) {
|
|
166
|
+
return tool.handler(args as Record<string, unknown>, user);
|
|
167
|
+
}
|
|
168
|
+
const startedAt = performance.now();
|
|
169
|
+
try {
|
|
170
|
+
const result = await tool.handler(args as Record<string, unknown>, user);
|
|
171
|
+
onToolCall({
|
|
172
|
+
durationMs: performance.now() - startedAt,
|
|
173
|
+
outcome: result.isError ? "tool_error" : "ok",
|
|
174
|
+
toolName: tool.name,
|
|
175
|
+
});
|
|
176
|
+
return result;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
onToolCall({
|
|
179
|
+
durationMs: performance.now() - startedAt,
|
|
180
|
+
errorName: errorName(error),
|
|
181
|
+
outcome: "exception",
|
|
182
|
+
toolName: tool.name,
|
|
183
|
+
});
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
124
187
|
);
|
|
125
188
|
}
|
|
126
189
|
|
|
@@ -303,7 +303,8 @@ describe("MCP service token OpenAPI", () => {
|
|
|
303
303
|
it("documents create, list, and revoke on /openapi.json", async () => {
|
|
304
304
|
const app = new TerrenoApp({
|
|
305
305
|
configureApp: (router, options) => {
|
|
306
|
-
|
|
306
|
+
// The routes only call get/post/delete, which the configureApp router provides.
|
|
307
|
+
addMcpServiceTokenRoutes(router as unknown as express.Application, {
|
|
307
308
|
openApi: options?.openApi,
|
|
308
309
|
publicMcpUrl: PUBLIC_MCP_URL,
|
|
309
310
|
});
|
|
@@ -3,23 +3,23 @@ import {Writable} from "node:stream";
|
|
|
3
3
|
import * as Sentry from "@sentry/bun";
|
|
4
4
|
import mongoose, {Schema} from "mongoose";
|
|
5
5
|
import winston from "winston";
|
|
6
|
-
|
|
6
|
+
import type {User} from "../auth";
|
|
7
7
|
import {winstonLogger} from "../logger";
|
|
8
8
|
import {Permissions} from "../permissions";
|
|
9
9
|
import {getCurrentRequestContext, runWithRequestContext} from "../requestContext";
|
|
10
10
|
import {generateAllTools, generateToolsForEntry} from "./toolGenerator";
|
|
11
11
|
import type {MCPRegistryEntry} from "./types";
|
|
12
12
|
|
|
13
|
-
const createTestModel = () => {
|
|
13
|
+
const createTestModel = (): mongoose.Model<unknown> => {
|
|
14
14
|
try {
|
|
15
|
-
return mongoose.model("MCPToolGenTest");
|
|
15
|
+
return mongoose.model<unknown>("MCPToolGenTest");
|
|
16
16
|
} catch {
|
|
17
17
|
const schema = new Schema({
|
|
18
18
|
completed: {default: false, description: "Whether the item is complete", type: Boolean},
|
|
19
19
|
name: {description: "The name", required: true, type: String},
|
|
20
20
|
ownerId: {description: "Owner", ref: "User", type: Schema.Types.ObjectId},
|
|
21
21
|
});
|
|
22
|
-
return mongoose.model("MCPToolGenTest", schema);
|
|
22
|
+
return mongoose.model<unknown>("MCPToolGenTest", schema);
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
25
|
|
|
@@ -264,7 +264,11 @@ describe("tool-call observability", () => {
|
|
|
264
264
|
},
|
|
265
265
|
});
|
|
266
266
|
const [tool] = generateToolsForEntry(entry);
|
|
267
|
-
const user = {
|
|
267
|
+
const user: User = {
|
|
268
|
+
_id: new mongoose.Types.ObjectId() as unknown as User["_id"],
|
|
269
|
+
admin: false,
|
|
270
|
+
id: "user-123",
|
|
271
|
+
};
|
|
268
272
|
|
|
269
273
|
await runWithRequestContext({}, async () => {
|
|
270
274
|
const result = await tool.handler({}, user);
|
|
@@ -8,11 +8,12 @@ import {join} from "node:path";
|
|
|
8
8
|
import mongoose from "mongoose";
|
|
9
9
|
|
|
10
10
|
import {setupDb} from "../tests";
|
|
11
|
+
import {partialEnv} from "../tests/testEnv";
|
|
11
12
|
import {runMigrateCli} from "./cli";
|
|
12
|
-
import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION} from "./types";
|
|
13
|
+
import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION, type MigrationStoreDoc} from "./types";
|
|
13
14
|
|
|
14
15
|
const fixtures = (...parts: string[]): string => {
|
|
15
|
-
return join(
|
|
16
|
+
return join(__dirname, "fixtures", ...parts);
|
|
16
17
|
};
|
|
17
18
|
|
|
18
19
|
const capture = (): {
|
|
@@ -41,7 +42,7 @@ const capture = (): {
|
|
|
41
42
|
|
|
42
43
|
const appliedIds = async (): Promise<string[]> => {
|
|
43
44
|
const docs = await mongoose.connection
|
|
44
|
-
.collection(MIGRATIONS_COLLECTION)
|
|
45
|
+
.collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION)
|
|
45
46
|
.find({_id: {$ne: MIGRATION_LOCK_ID}})
|
|
46
47
|
.project({id: 1})
|
|
47
48
|
.toArray();
|
|
@@ -91,7 +92,7 @@ describe("runMigrateCli", () => {
|
|
|
91
92
|
const io = capture();
|
|
92
93
|
const code = await runMigrateCli({
|
|
93
94
|
argv: ["status", "--dir", fixtures("valid")],
|
|
94
|
-
env: {},
|
|
95
|
+
env: partialEnv({}),
|
|
95
96
|
stderr: {write: io.writeErr},
|
|
96
97
|
stdout: {write: io.writeOut},
|
|
97
98
|
});
|
|
@@ -175,7 +176,7 @@ describe("runMigrateCli", () => {
|
|
|
175
176
|
const modelsDir = await mkdtemp(join(tmpdir(), "migrate-cli-models-"));
|
|
176
177
|
try {
|
|
177
178
|
const modelsPath = join(modelsDir, "models.ts");
|
|
178
|
-
const mongooseUrl =
|
|
179
|
+
const mongooseUrl = require.resolve("mongoose");
|
|
179
180
|
await writeFile(
|
|
180
181
|
modelsPath,
|
|
181
182
|
`import mongoose from ${JSON.stringify(mongooseUrl)};
|
|
@@ -249,7 +250,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
249
250
|
const io = capture();
|
|
250
251
|
const code = await runMigrateCli({
|
|
251
252
|
argv: ["up", "--dir", fixtures("valid"), "--force"],
|
|
252
|
-
env: {NODE_ENV: "production"},
|
|
253
|
+
env: partialEnv({NODE_ENV: "production"}),
|
|
253
254
|
mongoose,
|
|
254
255
|
stderr: {write: io.writeErr},
|
|
255
256
|
stdout: {write: io.writeOut},
|
|
@@ -263,7 +264,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
263
264
|
const io = capture();
|
|
264
265
|
const code = await runMigrateCli({
|
|
265
266
|
argv: ["up", "--dir", fixtures("valid")],
|
|
266
|
-
env: {ALLOW_MIGRATIONS: "true", NODE_ENV: "production"},
|
|
267
|
+
env: partialEnv({ALLOW_MIGRATIONS: "true", NODE_ENV: "production"}),
|
|
267
268
|
mongoose,
|
|
268
269
|
stderr: {write: io.writeErr},
|
|
269
270
|
stdout: {write: io.writeOut},
|
|
@@ -276,7 +277,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
276
277
|
const io = capture();
|
|
277
278
|
const code = await runMigrateCli({
|
|
278
279
|
argv: ["status", "--dir", fixtures("valid")],
|
|
279
|
-
env: {NODE_ENV: "test"},
|
|
280
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
280
281
|
mongoose,
|
|
281
282
|
stderr: {write: io.writeErr},
|
|
282
283
|
stdout: {write: io.writeOut},
|
|
@@ -290,7 +291,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
290
291
|
const upIo = capture();
|
|
291
292
|
const upCode = await runMigrateCli({
|
|
292
293
|
argv: ["up", "--dir", fixtures("valid")],
|
|
293
|
-
env: {NODE_ENV: "test"},
|
|
294
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
294
295
|
mongoose,
|
|
295
296
|
stderr: {write: upIo.writeErr},
|
|
296
297
|
stdout: {write: upIo.writeOut},
|
|
@@ -301,7 +302,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
301
302
|
const downIo = capture();
|
|
302
303
|
const downCode = await runMigrateCli({
|
|
303
304
|
argv: ["down", "--dir", fixtures("valid"), "--steps", "1"],
|
|
304
|
-
env: {NODE_ENV: "test"},
|
|
305
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
305
306
|
mongoose,
|
|
306
307
|
stderr: {write: downIo.writeErr},
|
|
307
308
|
stdout: {write: downIo.writeOut},
|
|
@@ -312,7 +313,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
312
313
|
const statusIo = capture();
|
|
313
314
|
const statusCode = await runMigrateCli({
|
|
314
315
|
argv: ["status", "--dir", fixtures("valid")],
|
|
315
|
-
env: {NODE_ENV: "test"},
|
|
316
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
316
317
|
mongoose,
|
|
317
318
|
stderr: {write: statusIo.writeErr},
|
|
318
319
|
stdout: {write: statusIo.writeOut},
|
|
@@ -325,14 +326,14 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
325
326
|
it("fails down when the target file has no down", async () => {
|
|
326
327
|
await runMigrateCli({
|
|
327
328
|
argv: ["up", "--dir", fixtures("valid")],
|
|
328
|
-
env: {NODE_ENV: "test"},
|
|
329
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
329
330
|
mongoose,
|
|
330
331
|
stderr: {write: () => undefined},
|
|
331
332
|
stdout: {write: () => undefined},
|
|
332
333
|
});
|
|
333
334
|
await runMigrateCli({
|
|
334
335
|
argv: ["down", "--dir", fixtures("valid"), "--steps", "1"],
|
|
335
|
-
env: {NODE_ENV: "test"},
|
|
336
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
336
337
|
mongoose,
|
|
337
338
|
stderr: {write: () => undefined},
|
|
338
339
|
stdout: {write: () => undefined},
|
|
@@ -341,7 +342,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
|
|
|
341
342
|
const io = capture();
|
|
342
343
|
const code = await runMigrateCli({
|
|
343
344
|
argv: ["down", "--dir", fixtures("valid"), "--steps", "1"],
|
|
344
|
-
env: {NODE_ENV: "test"},
|
|
345
|
+
env: partialEnv({NODE_ENV: "test"}),
|
|
345
346
|
mongoose,
|
|
346
347
|
stderr: {write: io.writeErr},
|
|
347
348
|
stdout: {write: io.writeOut},
|
package/src/migrations/cli.ts
CHANGED
|
@@ -12,14 +12,14 @@ import {generateMigration, lastSchemaAfter} from "./generate";
|
|
|
12
12
|
import {checkMigrationFiles} from "./load";
|
|
13
13
|
|
|
14
14
|
const fixtures = (...parts: string[]): string => {
|
|
15
|
-
return join(
|
|
15
|
+
return join(__dirname, "fixtures", ...parts);
|
|
16
16
|
};
|
|
17
17
|
|
|
18
18
|
const register = (name: string, schema: mongoose.Schema): mongoose.Model<mongoose.Document> => {
|
|
19
19
|
if (mongoose.models[name]) {
|
|
20
20
|
mongoose.deleteModel(name);
|
|
21
21
|
}
|
|
22
|
-
return mongoose.model(name, schema);
|
|
22
|
+
return mongoose.model<mongoose.Document>(name, schema);
|
|
23
23
|
};
|
|
24
24
|
|
|
25
25
|
const makeModels = ({
|
|
@@ -10,7 +10,7 @@ import {APIError} from "../errors";
|
|
|
10
10
|
import {checkMigrationFiles, loadMigrations, resolveMigrationDir} from "./load";
|
|
11
11
|
|
|
12
12
|
const fixtures = (...parts: string[]): string => {
|
|
13
|
-
return join(
|
|
13
|
+
return join(__dirname, "fixtures", ...parts);
|
|
14
14
|
};
|
|
15
15
|
|
|
16
16
|
describe("checkMigrationFiles", () => {
|
|
@@ -8,10 +8,15 @@ import mongoose from "mongoose";
|
|
|
8
8
|
import {setupDb} from "../tests";
|
|
9
9
|
import {withMigrationLock} from "./lock";
|
|
10
10
|
import {runMigrations} from "./runner";
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
type LoadedMigration,
|
|
13
|
+
MIGRATION_LOCK_ID,
|
|
14
|
+
MIGRATIONS_COLLECTION,
|
|
15
|
+
type MigrationStoreDoc,
|
|
16
|
+
} from "./types";
|
|
12
17
|
|
|
13
|
-
const collection = (): mongoose.Collection => {
|
|
14
|
-
return mongoose.connection.collection(MIGRATIONS_COLLECTION);
|
|
18
|
+
const collection = (): mongoose.Collection<MigrationStoreDoc> => {
|
|
19
|
+
return mongoose.connection.collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION);
|
|
15
20
|
};
|
|
16
21
|
|
|
17
22
|
describe("withMigrationLock", () => {
|