@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.
Files changed (169) hide show
  1. package/CHANGELOG.md +2071 -2
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
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) ?? SUPPORTED_GRANT_TYPES;
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) => !SUPPORTED_GRANT_TYPES.includes(grant as string))
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.includes(redirectUri)) {
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 clientId = stringParam(body.client_id);
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 must be authorization_code or refresh_token"
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 === "authorization_code"
747
- ? await exchangeAuthorizationCode(body, clientId, oauth, userModel)
748
- : await exchangeRefreshToken(body, clientId, oauth, userModel);
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);
@@ -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
- export const SUPPORTED_GRANT_TYPES = ["authorization_code", "refresh_token"];
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: ["none"],
214
+ token_endpoint_auth_methods_supported: SUPPORTED_TOKEN_ENDPOINT_AUTH_METHODS,
212
215
  });
213
216
 
214
217
  /**
@@ -42,6 +42,43 @@ const consentResponseSchema = new mongoose.Schema<ConsentResponseDocument, Conse
42
42
  required: true,
43
43
  type: String,
44
44
  },
45
+ provisional: {
46
+ default: false,
47
+ description:
48
+ "Whether another user recorded this agreement on the user's behalf. The user still sees the form and signs it themselves",
49
+ type: Boolean,
50
+ },
51
+ provisionalNote: {
52
+ description: "Required note from the provisional signer explaining how consent was obtained",
53
+ maxlength: 2000,
54
+ required: [
55
+ function (this: ConsentResponseDocument): boolean {
56
+ return this.provisional === true;
57
+ },
58
+ "provisionalNote is required for a provisional signature",
59
+ ],
60
+ trim: true,
61
+ type: String,
62
+ },
63
+ provisionalSignedBy: {
64
+ description: "The user who recorded this provisional signature",
65
+ ref: "User",
66
+ required: [
67
+ function (this: ConsentResponseDocument): boolean {
68
+ return this.provisional === true;
69
+ },
70
+ "provisionalSignedBy is required for a provisional signature",
71
+ ],
72
+ type: mongoose.Schema.Types.ObjectId,
73
+ },
74
+ provisionalSignerIp: {
75
+ description: "IP address of the provisional signer, captured for audit purposes",
76
+ type: String,
77
+ },
78
+ provisionalSignerUserAgent: {
79
+ description: "User-agent string of the provisional signer's browser or app",
80
+ type: String,
81
+ },
45
82
  signature: {
46
83
  description: "Base64-encoded signature image or typed signature text, if captured",
47
84
  type: String,
@@ -61,6 +98,22 @@ const consentResponseSchema = new mongoose.Schema<ConsentResponseDocument, Conse
61
98
  required: true,
62
99
  type: mongoose.Schema.Types.ObjectId,
63
100
  },
101
+ voidedAt: {
102
+ description:
103
+ "When a provisional signature was voided. Voided signatures no longer count as consent",
104
+ type: Date,
105
+ },
106
+ voidedBy: {
107
+ description: "The user who voided this provisional signature",
108
+ ref: "User",
109
+ type: mongoose.Schema.Types.ObjectId,
110
+ },
111
+ voidReason: {
112
+ description: "Why the provisional signature was voided",
113
+ maxlength: 2000,
114
+ trim: true,
115
+ type: String,
116
+ },
64
117
  },
65
118
  {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
66
119
  );
@@ -1,12 +1,19 @@
1
+ import {randomUUID} from "node:crypto";
2
+ import {DateTime} from "luxon";
1
3
  import mongoose from "mongoose";
2
4
 
3
5
  import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
- import type {McpOAuthClientDocument, McpOAuthClientModel} from "../types/mcpOAuth";
6
+ import type {
7
+ McpOAuthClientDocument,
8
+ McpOAuthClientModel,
9
+ McpOAuthConfidentialClientOptions,
10
+ } from "../types/mcpOAuth";
11
+ import {generateMcpOAuthSecret, hashMcpOAuthSecret, McpOAuthToken} from "./mcpOAuthToken";
5
12
 
6
13
  const mcpOAuthClientSchema = new mongoose.Schema<McpOAuthClientDocument, McpOAuthClientModel>(
7
14
  {
8
15
  clientId: {
9
- description: "Public OAuth client identifier issued by dynamic client registration",
16
+ description: "Public OAuth client identifier",
10
17
  required: true,
11
18
  type: String,
12
19
  unique: true,
@@ -16,22 +23,42 @@ const mcpOAuthClientSchema = new mongoose.Schema<McpOAuthClientDocument, McpOAut
16
23
  trim: true,
17
24
  type: String,
18
25
  },
26
+ clientSecretHash: {
27
+ description: "SHA-256 hash of the confidential client secret. Unset for public clients",
28
+ type: String,
29
+ },
19
30
  grantTypes: {
20
31
  description: "OAuth grant types the client may use",
21
32
  type: [String],
22
33
  },
23
34
  redirectUris: {
24
- description: "Exact redirect URIs the client registered",
35
+ description:
36
+ "Registered redirect URIs. Loopback hosts (localhost, 127.0.0.1, [::1]) match any port; every other URI must match exactly",
25
37
  type: [String],
26
38
  },
27
39
  responseTypes: {
28
40
  description: "OAuth response types the client may request",
29
41
  type: [String],
30
42
  },
43
+ revokedAt: {
44
+ description: "When the client was revoked. A revoked client cannot take new grants",
45
+ type: Date,
46
+ },
31
47
  scope: {
32
48
  description: "Space-separated scopes the client registered for",
33
49
  type: String,
34
50
  },
51
+ tokenEndpointAuthMethod: {
52
+ description:
53
+ "How the client authenticates at the token endpoint. none is a public client; client_secret_basic and client_secret_post are confidential",
54
+ enum: ["none", "client_secret_basic", "client_secret_post"],
55
+ type: String,
56
+ },
57
+ userId: {
58
+ description: "User a client_credentials token acts as",
59
+ ref: "User",
60
+ type: mongoose.Schema.Types.ObjectId,
61
+ },
35
62
  },
36
63
  {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
37
64
  );
@@ -40,6 +67,76 @@ mcpOAuthClientSchema.plugin(createdUpdatedPlugin);
40
67
  mcpOAuthClientSchema.plugin(findOneOrNone);
41
68
  mcpOAuthClientSchema.plugin(findExactlyOne);
42
69
 
70
+ const revokeTokensForClient = async (clientId: string | undefined): Promise<void> => {
71
+ if (!clientId) {
72
+ return;
73
+ }
74
+ await McpOAuthToken.revokeClient(clientId);
75
+ };
76
+
77
+ mcpOAuthClientSchema.pre("deleteOne", {document: true, query: false}, async function () {
78
+ await revokeTokensForClient(this.clientId);
79
+ });
80
+
81
+ mcpOAuthClientSchema.pre("deleteOne", {document: false, query: true}, async function () {
82
+ // deleteOne removes one document. Pin that document so its tokens are the ones revoked.
83
+ const [existing] = await this.model.find(this.getFilter()).limit(1).select({_id: 1, clientId: 1});
84
+ if (!existing) {
85
+ return;
86
+ }
87
+ this.setQuery({_id: existing._id});
88
+ await revokeTokensForClient(existing.clientId);
89
+ });
90
+
91
+ mcpOAuthClientSchema.pre("findOneAndDelete", async function () {
92
+ const [existing] = await this.model.find(this.getFilter()).limit(1).select({_id: 1, clientId: 1});
93
+ if (!existing) {
94
+ return;
95
+ }
96
+ this.setQuery({_id: existing._id});
97
+ await revokeTokensForClient(existing.clientId);
98
+ });
99
+
100
+ mcpOAuthClientSchema.pre("deleteMany", async function () {
101
+ const clients = await this.model.find(this.getFilter()).select({clientId: 1});
102
+ for (const client of clients) {
103
+ await revokeTokensForClient(client.clientId);
104
+ }
105
+ });
106
+
107
+ mcpOAuthClientSchema.statics = {
108
+ ...mcpOAuthClientSchema.statics,
109
+ async issueConfidential(
110
+ this: McpOAuthClientModel,
111
+ options: McpOAuthConfidentialClientOptions
112
+ ): Promise<{client: McpOAuthClientDocument; clientSecret: string}> {
113
+ const clientSecret = generateMcpOAuthSecret("mcpcs_");
114
+ const client = await this.create({
115
+ clientId: options.clientId ?? randomUUID(),
116
+ clientName: options.clientName,
117
+ clientSecretHash: hashMcpOAuthSecret(clientSecret),
118
+ grantTypes: ["client_credentials"],
119
+ redirectUris: [],
120
+ responseTypes: [],
121
+ scope: options.scope,
122
+ tokenEndpointAuthMethod: options.tokenEndpointAuthMethod,
123
+ userId: new mongoose.Types.ObjectId(String(options.userId)),
124
+ });
125
+ return {client, clientSecret};
126
+ },
127
+ async revoke(
128
+ this: McpOAuthClientModel,
129
+ clientId: string
130
+ ): Promise<McpOAuthClientDocument | null> {
131
+ await this.updateOne(
132
+ {clientId, revokedAt: {$exists: false}},
133
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
134
+ );
135
+ await McpOAuthToken.revokeClient(clientId);
136
+ return this.findOneOrNone({clientId});
137
+ },
138
+ };
139
+
43
140
  export const McpOAuthClient =
44
141
  (mongoose.models.TerrenoMcpOAuthClient as McpOAuthClientModel | undefined) ??
45
142
  mongoose.model<McpOAuthClientDocument, McpOAuthClientModel>(
@@ -62,6 +62,11 @@ const mcpOAuthTokenSchema = new mongoose.Schema<McpOAuthTokenDocument, McpOAuthT
62
62
  required: true,
63
63
  type: String,
64
64
  },
65
+ hasRefreshToken: {
66
+ description:
67
+ "False when this document is an access-only client_credentials token. The refresh hash is then of a discarded secret and cannot be exchanged",
68
+ type: Boolean,
69
+ },
65
70
  refreshExpiresAt: {
66
71
  description: "When the refresh token stops being exchangeable; the document is removed then",
67
72
  required: true,
@@ -116,21 +121,30 @@ mcpOAuthTokenSchema.statics = {
116
121
  async issue(
117
122
  this: McpOAuthTokenModel,
118
123
  options: McpOAuthTokenIssueOptions
119
- ): Promise<{accessToken: string; mcpOAuthToken: McpOAuthTokenDocument; refreshToken: string}> {
124
+ ): Promise<{accessToken: string; mcpOAuthToken: McpOAuthTokenDocument; refreshToken?: string}> {
120
125
  const familyId = options.familyId ?? randomUUID();
121
126
  if (await isFamilyRevoked(familyId)) {
122
127
  throw new McpOAuthFamilyRevokedError(familyId);
123
128
  }
129
+ const includeRefreshToken = options.includeRefreshToken !== false;
124
130
  const accessToken = generateMcpOAuthSecret(MCP_OAUTH_ACCESS_TOKEN_PREFIX);
125
- const refreshToken = generateMcpOAuthSecret(MCP_OAUTH_REFRESH_TOKEN_PREFIX);
131
+ // Access-only grants still store a unique hash so the refreshTokenHash index stays unique.
132
+ // The preimage is discarded, and hasRefreshToken false makes it unusable for refresh.
133
+ const refreshSecret = includeRefreshToken
134
+ ? generateMcpOAuthSecret(MCP_OAUTH_REFRESH_TOKEN_PREFIX)
135
+ : generateMcpOAuthSecret("discarded_");
126
136
  const now = DateTime.now();
137
+ const refreshTtlSeconds = includeRefreshToken
138
+ ? options.refreshTokenTtlSeconds
139
+ : options.accessTokenTtlSeconds;
127
140
  const mcpOAuthToken = await this.create({
128
141
  accessExpiresAt: now.plus({seconds: options.accessTokenTtlSeconds}).toJSDate(),
129
142
  accessTokenHash: hashMcpOAuthSecret(accessToken),
130
143
  clientId: options.clientId,
131
144
  familyId,
132
- refreshExpiresAt: now.plus({seconds: options.refreshTokenTtlSeconds}).toJSDate(),
133
- refreshTokenHash: hashMcpOAuthSecret(refreshToken),
145
+ hasRefreshToken: includeRefreshToken,
146
+ refreshExpiresAt: now.plus({seconds: refreshTtlSeconds}).toJSDate(),
147
+ refreshTokenHash: hashMcpOAuthSecret(refreshSecret),
134
148
  resource: options.resource,
135
149
  scope: options.scope,
136
150
  tokenEpoch: options.tokenEpoch ?? 0,
@@ -145,7 +159,18 @@ mcpOAuthTokenSchema.statics = {
145
159
  );
146
160
  throw new McpOAuthFamilyRevokedError(familyId);
147
161
  }
148
- return {accessToken, mcpOAuthToken, refreshToken};
162
+ return {
163
+ accessToken,
164
+ mcpOAuthToken,
165
+ refreshToken: includeRefreshToken ? refreshSecret : undefined,
166
+ };
167
+ },
168
+ async revokeClient(this: McpOAuthTokenModel, clientId: string): Promise<void> {
169
+ const tokens = await this.find({clientId, revokedAt: {$exists: false}}).select({familyId: 1});
170
+ const familyIds = new Set(tokens.map((token) => token.familyId));
171
+ for (const familyId of familyIds) {
172
+ await this.revokeFamily(familyId);
173
+ }
149
174
  },
150
175
  async revokeFamily(this: McpOAuthTokenModel, familyId: string): Promise<void> {
151
176
  const now = DateTime.now();
@@ -0,0 +1,39 @@
1
+ import {APIError} from "../errors";
2
+ import type {MembershipDocument} from "../types/membership";
3
+ import {Membership} from "./organizationModel";
4
+
5
+ export const LAST_ORG_ADMIN_TITLE = "Cannot remove the last org-admin";
6
+
7
+ const countActiveOrgAdmins = async (
8
+ organizationId: MembershipDocument["organizationId"]
9
+ ): Promise<number> => {
10
+ return Membership.countDocuments({
11
+ organizationId,
12
+ roleName: "org-admin",
13
+ status: "active",
14
+ });
15
+ };
16
+
17
+ /**
18
+ * Refuses (400) a membership change that would leave the organization with no active org-admin,
19
+ * so an org can never lose every administrator through a role change, suspension, or removal.
20
+ */
21
+ export const assertNotLastOrgAdmin = async (
22
+ membership: MembershipDocument,
23
+ nextRoleName?: string,
24
+ nextStatus?: string
25
+ ): Promise<void> => {
26
+ const remainsOrgAdmin =
27
+ (nextRoleName ?? membership.roleName) === "org-admin" &&
28
+ (nextStatus ?? membership.status) === "active";
29
+ if (remainsOrgAdmin) {
30
+ return;
31
+ }
32
+ if (membership.roleName !== "org-admin" || membership.status !== "active") {
33
+ return;
34
+ }
35
+ const activeAdmins = await countActiveOrgAdmins(membership.organizationId);
36
+ if (activeAdmins <= 1) {
37
+ throw new APIError({status: 400, title: LAST_ORG_ADMIN_TITLE});
38
+ }
39
+ };
@@ -74,7 +74,7 @@ describe("organization RBAC", () => {
74
74
  assert.isTrue(operator.isLocked);
75
75
  assert.deepEqual(operator.permissions.organization, [...terrenoStatements.organization]);
76
76
  assert.deepEqual(operator.permissions.admin, ["access"]);
77
- assert.deepEqual(operator.permissions.user, ["list", "read", "update"]);
77
+ assert.deepEqual(operator.permissions.user, ["list", "read", "update", "manageSecurity"]);
78
78
 
79
79
  const orgAdminRole = await RbacRole.findOne({name: "org-admin"});
80
80
  assert.isNull(orgAdminRole);