@terreno/api 57.16.2 → 57.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
@@ -0,0 +1,97 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
+ import type {McpOAuthAuthorizationDocument, McpOAuthAuthorizationModel} from "../types/mcpOAuth";
5
+
6
+ const mcpOAuthAuthorizationSchema = new mongoose.Schema<
7
+ McpOAuthAuthorizationDocument,
8
+ McpOAuthAuthorizationModel
9
+ >(
10
+ {
11
+ clientId: {
12
+ description: "OAuth client that started this authorization request",
13
+ required: true,
14
+ type: String,
15
+ },
16
+ codeChallenge: {
17
+ description: "PKCE S256 code challenge sent with the authorization request",
18
+ required: true,
19
+ type: String,
20
+ },
21
+ codeExpiresAt: {
22
+ description: "When the issued authorization code stops being exchangeable",
23
+ type: Date,
24
+ },
25
+ codeHash: {
26
+ description: "SHA-256 hash of the issued authorization code",
27
+ index: {sparse: true, unique: true},
28
+ type: String,
29
+ },
30
+ expiresAt: {
31
+ description: "When the pending request expires and the document is removed",
32
+ required: true,
33
+ type: Date,
34
+ },
35
+ familyId: {
36
+ description: "Token family issued from this code, revoked if the code is replayed",
37
+ type: String,
38
+ },
39
+ redirectUri: {
40
+ description: "Registered redirect URI the code is delivered to",
41
+ required: true,
42
+ type: String,
43
+ },
44
+ requestId: {
45
+ description: "Opaque id handed to the consent screen to identify this request",
46
+ required: true,
47
+ type: String,
48
+ unique: true,
49
+ },
50
+ resource: {
51
+ description: "RFC 8707 resource indicator the client asked for",
52
+ type: String,
53
+ },
54
+ scope: {
55
+ description: "Space-separated scopes requested by the client",
56
+ type: String,
57
+ },
58
+ state: {
59
+ description: "Opaque client state echoed back on the redirect",
60
+ type: String,
61
+ },
62
+ status: {
63
+ default: "pending",
64
+ description: "pending, approved (code outstanding), denied, or used (code exchanged)",
65
+ enum: ["pending", "approved", "denied", "used"],
66
+ type: String,
67
+ },
68
+ tokenEpoch: {
69
+ description: "The approving user's tokenEpoch; a code is refused after it changes",
70
+ type: Number,
71
+ },
72
+ usedAt: {
73
+ description: "When the authorization code was exchanged",
74
+ type: Date,
75
+ },
76
+ userId: {
77
+ description: "The user who approved or denied the request",
78
+ ref: "User",
79
+ type: mongoose.Schema.Types.ObjectId,
80
+ },
81
+ },
82
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
83
+ );
84
+
85
+ mcpOAuthAuthorizationSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
86
+
87
+ mcpOAuthAuthorizationSchema.plugin(createdUpdatedPlugin);
88
+ mcpOAuthAuthorizationSchema.plugin(findOneOrNone);
89
+ mcpOAuthAuthorizationSchema.plugin(findExactlyOne);
90
+
91
+ export const McpOAuthAuthorization =
92
+ (mongoose.models.TerrenoMcpOAuthAuthorization as McpOAuthAuthorizationModel | undefined) ??
93
+ mongoose.model<McpOAuthAuthorizationDocument, McpOAuthAuthorizationModel>(
94
+ "TerrenoMcpOAuthAuthorization",
95
+ mcpOAuthAuthorizationSchema,
96
+ "mcpoauthauthorizations"
97
+ );
@@ -0,0 +1,49 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
+ import type {McpOAuthClientDocument, McpOAuthClientModel} from "../types/mcpOAuth";
5
+
6
+ const mcpOAuthClientSchema = new mongoose.Schema<McpOAuthClientDocument, McpOAuthClientModel>(
7
+ {
8
+ clientId: {
9
+ description: "Public OAuth client identifier issued by dynamic client registration",
10
+ required: true,
11
+ type: String,
12
+ unique: true,
13
+ },
14
+ clientName: {
15
+ description: "Human-readable client name shown on the consent screen",
16
+ trim: true,
17
+ type: String,
18
+ },
19
+ grantTypes: {
20
+ description: "OAuth grant types the client may use",
21
+ type: [String],
22
+ },
23
+ redirectUris: {
24
+ description: "Exact redirect URIs the client registered",
25
+ type: [String],
26
+ },
27
+ responseTypes: {
28
+ description: "OAuth response types the client may request",
29
+ type: [String],
30
+ },
31
+ scope: {
32
+ description: "Space-separated scopes the client registered for",
33
+ type: String,
34
+ },
35
+ },
36
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
37
+ );
38
+
39
+ mcpOAuthClientSchema.plugin(createdUpdatedPlugin);
40
+ mcpOAuthClientSchema.plugin(findOneOrNone);
41
+ mcpOAuthClientSchema.plugin(findExactlyOne);
42
+
43
+ export const McpOAuthClient =
44
+ (mongoose.models.TerrenoMcpOAuthClient as McpOAuthClientModel | undefined) ??
45
+ mongoose.model<McpOAuthClientDocument, McpOAuthClientModel>(
46
+ "TerrenoMcpOAuthClient",
47
+ mcpOAuthClientSchema,
48
+ "mcpoauthclients"
49
+ );
@@ -0,0 +1,47 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
+ import type {McpOAuthRevokedFamilyDocument, McpOAuthRevokedFamilyModel} from "../types/mcpOAuth";
5
+
6
+ /**
7
+ * Tombstone for a revoked token family. `McpOAuthToken.issue` refuses a family that has one, so
8
+ * a request that won a rotation or code exchange before the revoke cannot add a live pair after.
9
+ */
10
+ const mcpOAuthRevokedFamilySchema = new mongoose.Schema<
11
+ McpOAuthRevokedFamilyDocument,
12
+ McpOAuthRevokedFamilyModel
13
+ >(
14
+ {
15
+ expiresAt: {
16
+ description: "When the tombstone is removed; set past the last refresh expiry in the family",
17
+ required: true,
18
+ type: Date,
19
+ },
20
+ familyId: {
21
+ description: "Rotation chain id that was revoked",
22
+ required: true,
23
+ type: String,
24
+ unique: true,
25
+ },
26
+ revokedAt: {
27
+ description: "When the family was first revoked",
28
+ required: true,
29
+ type: Date,
30
+ },
31
+ },
32
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
33
+ );
34
+
35
+ mcpOAuthRevokedFamilySchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
36
+
37
+ mcpOAuthRevokedFamilySchema.plugin(createdUpdatedPlugin);
38
+ mcpOAuthRevokedFamilySchema.plugin(findOneOrNone);
39
+ mcpOAuthRevokedFamilySchema.plugin(findExactlyOne);
40
+
41
+ export const McpOAuthRevokedFamily =
42
+ (mongoose.models.TerrenoMcpOAuthRevokedFamily as McpOAuthRevokedFamilyModel | undefined) ??
43
+ mongoose.model<McpOAuthRevokedFamilyDocument, McpOAuthRevokedFamilyModel>(
44
+ "TerrenoMcpOAuthRevokedFamily",
45
+ mcpOAuthRevokedFamilySchema,
46
+ "mcpoauthrevokedfamilies"
47
+ );
@@ -0,0 +1,82 @@
1
+ import {beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import {DateTime} from "luxon";
3
+ import mongoose from "mongoose";
4
+
5
+ import {McpOAuthRevokedFamily} from "./mcpOAuthRevokedFamily";
6
+ import {McpOAuthFamilyRevokedError, McpOAuthToken} from "./mcpOAuthToken";
7
+
8
+ const issueOptions = (familyId?: string) => ({
9
+ accessTokenTtlSeconds: 60,
10
+ clientId: "client-1",
11
+ familyId,
12
+ refreshTokenTtlSeconds: 3 * 24 * 60 * 60,
13
+ userId: new mongoose.Types.ObjectId(),
14
+ });
15
+
16
+ const activePairs = (familyId: string): Promise<number> =>
17
+ McpOAuthToken.countDocuments({familyId, revokedAt: {$exists: false}});
18
+
19
+ describe("McpOAuthToken family revocation", () => {
20
+ beforeEach(async () => {
21
+ await McpOAuthToken.deleteMany({});
22
+ await McpOAuthRevokedFamily.deleteMany({});
23
+ });
24
+
25
+ it("revokes every pair in the family and refuses to issue into it afterwards", async () => {
26
+ const {mcpOAuthToken} = await McpOAuthToken.issue(issueOptions());
27
+ const {familyId} = mcpOAuthToken;
28
+
29
+ await McpOAuthToken.revokeFamily(familyId);
30
+
31
+ expect(await activePairs(familyId)).toBe(0);
32
+ await expect(McpOAuthToken.issue(issueOptions(familyId))).rejects.toBeInstanceOf(
33
+ McpOAuthFamilyRevokedError
34
+ );
35
+ expect(await activePairs(familyId)).toBe(0);
36
+ });
37
+
38
+ it("revokes a pair whose family was revoked while it was being created", async () => {
39
+ const familyId = "family-raced";
40
+ const realCreate = McpOAuthToken.create.bind(McpOAuthToken);
41
+ // The revoke lands after issue's first check but before the pair exists.
42
+ const createSpy = spyOn(McpOAuthToken, "create").mockImplementation((async (
43
+ ...args: Parameters<typeof realCreate>
44
+ ) => {
45
+ await McpOAuthToken.revokeFamily(familyId);
46
+ return realCreate(...args);
47
+ }) as typeof McpOAuthToken.create);
48
+ try {
49
+ await expect(McpOAuthToken.issue(issueOptions(familyId))).rejects.toBeInstanceOf(
50
+ McpOAuthFamilyRevokedError
51
+ );
52
+ } finally {
53
+ createSpy.mockRestore();
54
+ }
55
+
56
+ expect(await McpOAuthToken.countDocuments({familyId})).toBe(1);
57
+ expect(await activePairs(familyId)).toBe(0);
58
+ });
59
+
60
+ it("keeps the tombstone until the family's last refresh token would have expired", async () => {
61
+ const {mcpOAuthToken} = await McpOAuthToken.issue(issueOptions());
62
+
63
+ await McpOAuthToken.revokeFamily(mcpOAuthToken.familyId);
64
+ await McpOAuthToken.revokeFamily(mcpOAuthToken.familyId);
65
+
66
+ const tombstone = await McpOAuthRevokedFamily.findExactlyOne({
67
+ familyId: mcpOAuthToken.familyId,
68
+ });
69
+ expect(tombstone.expiresAt.getTime()).toBeGreaterThanOrEqual(
70
+ mcpOAuthToken.refreshExpiresAt.getTime()
71
+ );
72
+ });
73
+
74
+ it("keeps a tombstone for at least an hour when the family has no pairs", async () => {
75
+ await McpOAuthToken.revokeFamily("family-without-pairs");
76
+
77
+ const tombstone = await McpOAuthRevokedFamily.findExactlyOne({
78
+ familyId: "family-without-pairs",
79
+ });
80
+ expect(DateTime.fromJSDate(tombstone.expiresAt).diffNow("minutes").minutes).toBeGreaterThan(59);
81
+ });
82
+ });
@@ -0,0 +1,195 @@
1
+ import {createHash, randomBytes, randomUUID} from "node:crypto";
2
+ import {DateTime} from "luxon";
3
+ import mongoose from "mongoose";
4
+
5
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
6
+ import type {
7
+ McpOAuthTokenDocument,
8
+ McpOAuthTokenIssueOptions,
9
+ McpOAuthTokenModel,
10
+ } from "../types/mcpOAuth";
11
+ import {McpOAuthRevokedFamily} from "./mcpOAuthRevokedFamily";
12
+
13
+ /** Access tokens carry a prefix distinct from `mcp_` service tokens so `/mcp` can route them. */
14
+ export const MCP_OAUTH_ACCESS_TOKEN_PREFIX = "mcpat_";
15
+ const MCP_OAUTH_REFRESH_TOKEN_PREFIX = "mcprt_";
16
+ const MCP_OAUTH_TOKEN_RANDOM_BYTES = 32;
17
+ // A tombstone outlives in-flight requests even when the family has no unexpired refresh token.
18
+ const MIN_REVOKED_FAMILY_RETENTION_SECONDS = 60 * 60;
19
+
20
+ /** Thrown by `McpOAuthToken.issue` for a family that was revoked. Answer it as `invalid_grant`. */
21
+ export class McpOAuthFamilyRevokedError extends Error {
22
+ readonly familyId: string;
23
+
24
+ constructor(familyId: string) {
25
+ super("The token family was revoked");
26
+ this.familyId = familyId;
27
+ this.name = "McpOAuthFamilyRevokedError";
28
+ }
29
+ }
30
+
31
+ const isFamilyRevoked = async (familyId: string): Promise<boolean> =>
32
+ Boolean(await McpOAuthRevokedFamily.exists({familyId}));
33
+
34
+ /** Codes, tokens, and request ids are stored only as SHA-256 hashes. */
35
+ export const hashMcpOAuthSecret = (secret: string): string =>
36
+ createHash("sha256").update(secret).digest("hex");
37
+
38
+ export const generateMcpOAuthSecret = (prefix = ""): string =>
39
+ `${prefix}${randomBytes(MCP_OAUTH_TOKEN_RANDOM_BYTES).toString("base64url")}`;
40
+
41
+ const mcpOAuthTokenSchema = new mongoose.Schema<McpOAuthTokenDocument, McpOAuthTokenModel>(
42
+ {
43
+ accessExpiresAt: {
44
+ description: "When the access token stops authenticating MCP requests",
45
+ required: true,
46
+ type: Date,
47
+ },
48
+ accessTokenHash: {
49
+ description: "SHA-256 hash of the opaque access token",
50
+ required: true,
51
+ type: String,
52
+ unique: true,
53
+ },
54
+ clientId: {
55
+ description: "OAuth client the tokens were issued to",
56
+ required: true,
57
+ type: String,
58
+ },
59
+ familyId: {
60
+ description: "Rotation chain id shared by every pair issued from one authorization",
61
+ index: true,
62
+ required: true,
63
+ type: String,
64
+ },
65
+ refreshExpiresAt: {
66
+ description: "When the refresh token stops being exchangeable; the document is removed then",
67
+ required: true,
68
+ type: Date,
69
+ },
70
+ refreshTokenHash: {
71
+ description: "SHA-256 hash of the opaque refresh token",
72
+ required: true,
73
+ type: String,
74
+ unique: true,
75
+ },
76
+ resource: {
77
+ description: "RFC 8707 resource the tokens are bound to",
78
+ type: String,
79
+ },
80
+ revokedAt: {
81
+ description: "When the pair was revoked; unset while it remains active",
82
+ type: Date,
83
+ },
84
+ rotatedAt: {
85
+ description: "When the refresh token was exchanged for a new pair",
86
+ type: Date,
87
+ },
88
+ scope: {
89
+ description: "Space-separated scopes granted",
90
+ type: String,
91
+ },
92
+ tokenEpoch: {
93
+ description:
94
+ "The user's tokenEpoch when the grant was approved; the pair stops working after it changes",
95
+ type: Number,
96
+ },
97
+ userId: {
98
+ description: "The user the tokens act as",
99
+ index: true,
100
+ ref: "User",
101
+ required: true,
102
+ type: mongoose.Schema.Types.ObjectId,
103
+ },
104
+ },
105
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
106
+ );
107
+
108
+ mcpOAuthTokenSchema.index({refreshExpiresAt: 1}, {expireAfterSeconds: 0});
109
+
110
+ mcpOAuthTokenSchema.plugin(createdUpdatedPlugin);
111
+ mcpOAuthTokenSchema.plugin(findOneOrNone);
112
+ mcpOAuthTokenSchema.plugin(findExactlyOne);
113
+
114
+ mcpOAuthTokenSchema.statics = {
115
+ ...mcpOAuthTokenSchema.statics,
116
+ async issue(
117
+ this: McpOAuthTokenModel,
118
+ options: McpOAuthTokenIssueOptions
119
+ ): Promise<{accessToken: string; mcpOAuthToken: McpOAuthTokenDocument; refreshToken: string}> {
120
+ const familyId = options.familyId ?? randomUUID();
121
+ if (await isFamilyRevoked(familyId)) {
122
+ throw new McpOAuthFamilyRevokedError(familyId);
123
+ }
124
+ const accessToken = generateMcpOAuthSecret(MCP_OAUTH_ACCESS_TOKEN_PREFIX);
125
+ const refreshToken = generateMcpOAuthSecret(MCP_OAUTH_REFRESH_TOKEN_PREFIX);
126
+ const now = DateTime.now();
127
+ const mcpOAuthToken = await this.create({
128
+ accessExpiresAt: now.plus({seconds: options.accessTokenTtlSeconds}).toJSDate(),
129
+ accessTokenHash: hashMcpOAuthSecret(accessToken),
130
+ clientId: options.clientId,
131
+ familyId,
132
+ refreshExpiresAt: now.plus({seconds: options.refreshTokenTtlSeconds}).toJSDate(),
133
+ refreshTokenHash: hashMcpOAuthSecret(refreshToken),
134
+ resource: options.resource,
135
+ scope: options.scope,
136
+ tokenEpoch: options.tokenEpoch ?? 0,
137
+ userId: options.userId,
138
+ });
139
+ // revokeFamily writes the tombstone before it revokes pairs, so a revoke that raced this
140
+ // create has either revoked the new pair already or is visible here.
141
+ if (await isFamilyRevoked(familyId)) {
142
+ await this.updateOne(
143
+ {_id: mcpOAuthToken._id, revokedAt: {$exists: false}},
144
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
145
+ );
146
+ throw new McpOAuthFamilyRevokedError(familyId);
147
+ }
148
+ return {accessToken, mcpOAuthToken, refreshToken};
149
+ },
150
+ async revokeFamily(this: McpOAuthTokenModel, familyId: string): Promise<void> {
151
+ const now = DateTime.now();
152
+ const [latest] = await this.find({familyId})
153
+ .sort({refreshExpiresAt: -1})
154
+ .limit(1)
155
+ .select({refreshExpiresAt: 1});
156
+ const minimumRetention = now.plus({seconds: MIN_REVOKED_FAMILY_RETENTION_SECONDS});
157
+ const retainUntil = latest
158
+ ? DateTime.max(minimumRetention, DateTime.fromJSDate(latest.refreshExpiresAt))
159
+ : minimumRetention;
160
+ // The tombstone goes first: issue checks it again after creating a pair.
161
+ await McpOAuthRevokedFamily.updateOne(
162
+ {familyId},
163
+ {
164
+ $max: {expiresAt: retainUntil.toJSDate()},
165
+ $setOnInsert: {revokedAt: now.toJSDate()},
166
+ },
167
+ {upsert: true}
168
+ );
169
+ await this.updateMany(
170
+ {familyId, revokedAt: {$exists: false}},
171
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
172
+ );
173
+ },
174
+ async verifyAccessToken(
175
+ this: McpOAuthTokenModel,
176
+ token: string
177
+ ): Promise<McpOAuthTokenDocument | null> {
178
+ if (!token.startsWith(MCP_OAUTH_ACCESS_TOKEN_PREFIX)) {
179
+ return null;
180
+ }
181
+ return this.findOneOrNone({
182
+ accessExpiresAt: {$gt: DateTime.now().toJSDate()},
183
+ accessTokenHash: hashMcpOAuthSecret(token),
184
+ revokedAt: {$exists: false},
185
+ });
186
+ },
187
+ };
188
+
189
+ export const McpOAuthToken =
190
+ (mongoose.models.TerrenoMcpOAuthToken as McpOAuthTokenModel | undefined) ??
191
+ mongoose.model<McpOAuthTokenDocument, McpOAuthTokenModel>(
192
+ "TerrenoMcpOAuthToken",
193
+ mcpOAuthTokenSchema,
194
+ "mcpoauthtokens"
195
+ );
@@ -12,7 +12,7 @@ export type {
12
12
  McpServiceTokenStatics,
13
13
  } from "../types/mcpServiceToken";
14
14
 
15
- const MCP_SERVICE_TOKEN_PREFIX = "mcp_";
15
+ export const MCP_SERVICE_TOKEN_PREFIX = "mcp_";
16
16
  const MCP_SERVICE_TOKEN_RANDOM_BYTES = 32;
17
17
  const MCP_SERVICE_TOKEN_DISPLAY_LENGTH = 8;
18
18
 
@@ -38,6 +38,11 @@ const mcpServiceTokenSchema = new mongoose.Schema<McpServiceTokenDocument, McpSe
38
38
  description: "When this MCP service token was revoked; unset while it remains active",
39
39
  type: Date,
40
40
  },
41
+ tokenEpoch: {
42
+ description:
43
+ "The user's tokenEpoch when the token was issued; the token stops working after it changes",
44
+ type: Number,
45
+ },
41
46
  tokenHash: {
42
47
  description: "SHA-256 hash of the full MCP service token plaintext",
43
48
  required: true,
@@ -109,13 +114,14 @@ mcpServiceTokenSchema.statics = {
109
114
  },
110
115
  async issueFor(
111
116
  this: McpServiceTokenModel,
112
- user: {_id: {toString(): string}},
117
+ user: {_id: {toString(): string}; tokenEpoch?: number},
113
118
  options: {expiresAt?: Date; name: string}
114
119
  ): Promise<{mcpServiceToken: McpServiceTokenDocument; token: string}> {
115
120
  const token = `${MCP_SERVICE_TOKEN_PREFIX}${randomBytes(MCP_SERVICE_TOKEN_RANDOM_BYTES).toString("hex")}`;
116
121
  const mcpServiceToken = await this.create({
117
122
  expiresAt: options.expiresAt,
118
123
  name: options.name,
124
+ tokenEpoch: user.tokenEpoch ?? 0,
119
125
  tokenHash: hashToken(token),
120
126
  tokenPrefix: token.slice(
121
127
  MCP_SERVICE_TOKEN_PREFIX.length,
@@ -140,6 +146,24 @@ mcpServiceTokenSchema.statics = {
140
146
  {returnDocument: "after"}
141
147
  );
142
148
  },
149
+ /**
150
+ * Revoke the user's active tokens issued under an earlier tokenEpoch. A token from before the
151
+ * field existed counts as epoch 0, the same way a refresh token without `te` does.
152
+ */
153
+ async revokeOutdatedForUser(
154
+ this: McpServiceTokenModel,
155
+ user: {_id: {toString(): string}; tokenEpoch?: number}
156
+ ): Promise<void> {
157
+ const currentEpoch = user.tokenEpoch ?? 0;
158
+ await this.updateMany(
159
+ {
160
+ revokedAt: {$exists: false},
161
+ tokenEpoch: {$nin: currentEpoch === 0 ? [0, null] : [currentEpoch]},
162
+ userId: new mongoose.Types.ObjectId(String(user._id)),
163
+ },
164
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
165
+ );
166
+ },
143
167
  async verify(this: McpServiceTokenModel, token: string): Promise<McpServiceTokenDocument | null> {
144
168
  const now = DateTime.now().toJSDate();
145
169
  return this.findOneOrNone({
@@ -7,6 +7,7 @@ import type {User} from "./auth";
7
7
  import {loadDocOr404} from "./docLoader";
8
8
  import {APIError} from "./errors";
9
9
  import {isOrgMemberPermission, OrgQueryFilter} from "./orgs/orgPermissions";
10
+ import {getCurrentRequestContext} from "./requestContext";
10
11
 
11
12
  export type PermissionMethod<T> = (
12
13
  method: RESTMethod,
@@ -14,6 +15,22 @@ export type PermissionMethod<T> = (
14
15
  obj?: T
15
16
  ) => boolean | Promise<boolean>;
16
17
 
18
+ /**
19
+ * Permission that refuses an MCP OAuth access token unless it was granted `scope`. Other
20
+ * credentials (the user's own JWT or Better Auth session, and `mcp_` service tokens) are not
21
+ * scoped and pass. Combine it with the method's other permissions, for example
22
+ * `[Permissions.IsAuthenticated, requireOAuthScope("write")]`.
23
+ */
24
+ export const requireOAuthScope = (scope: string): PermissionMethod<unknown> => {
25
+ return (): boolean => {
26
+ const context = getCurrentRequestContext();
27
+ if (context?.credential !== "oauth") {
28
+ return true;
29
+ }
30
+ return context.oauthScopes?.includes(scope) === true;
31
+ };
32
+ };
33
+
17
34
  export interface RESTPermissions<T> {
18
35
  create: PermissionMethod<T>[];
19
36
  list: PermissionMethod<T>[];
@@ -21,12 +21,33 @@ const normalizeRequestPath = (url: string): string => {
21
21
  return withoutSlash.toLowerCase();
22
22
  };
23
23
 
24
+ const PATH_BASE = "http://terreno.invalid";
25
+
26
+ /**
27
+ * Resolve `.`/`..` segments (including `%2e` forms) the way the WHATWG URL parser does. Better
28
+ * Auth routes on that parsed pathname, so `/api/auth/%2e/sign-in/email` reaches sign-in.
29
+ */
30
+ const resolveDotSegments = (path: string): string => {
31
+ try {
32
+ const url = path.startsWith("/") ? new URL(`${PATH_BASE}${path}`) : new URL(path, PATH_BASE);
33
+ return url.pathname;
34
+ } catch {
35
+ return path;
36
+ }
37
+ };
38
+
24
39
  /** Prefer Express `req.path` (routing) over the raw request-target. */
25
- const requestPath = (req: Request): string => {
40
+ const rawRequestPath = (req: Request): string => {
26
41
  const raw = req.path || req.url || req.originalUrl || "";
27
42
  return normalizeRequestPath(raw);
28
43
  };
29
44
 
45
+ /** The request path as a WHATWG-normalizing router such as Better Auth's sees it. */
46
+ const requestPath = (req: Request): string => {
47
+ const raw = req.path || req.url || req.originalUrl || "";
48
+ return normalizeRequestPath(resolveDotSegments(stripQueryAndFragment(raw)));
49
+ };
50
+
30
51
  const JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
31
52
  "/auth/login",
32
53
  "/auth/signup",
@@ -42,7 +63,7 @@ const JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
42
63
  * `setupAuth` runs before those routes so the client can still exchange credentials.
43
64
  */
44
65
  export const isJwtCredentialExchangePath = (req: Request): boolean => {
45
- return JWT_CREDENTIAL_EXCHANGE_EXACT.has(requestPath(req));
66
+ return JWT_CREDENTIAL_EXCHANGE_EXACT.has(rawRequestPath(req));
46
67
  };
47
68
 
48
69
  export const shouldSkipRateLimit = (
@@ -50,6 +71,10 @@ export const shouldSkipRateLimit = (
50
71
  extraSkip?: (req: Request) => boolean
51
72
  ): boolean => {
52
73
  const path = requestPath(req);
74
+ // A path with dot segments may route somewhere else than it looks; never exempt it.
75
+ if (path !== rawRequestPath(req)) {
76
+ return false;
77
+ }
53
78
  if (req.method === "GET" && (path === "/health" || path === "/healthz")) {
54
79
  return true;
55
80
  }
@@ -78,6 +103,10 @@ const AUTH_EXACT = new Set([
78
103
  "/auth/github",
79
104
  "/auth/github/callback",
80
105
  "/auth/github/failure",
106
+ "/oauth/register",
107
+ "/oauth/authorize",
108
+ "/oauth/token",
109
+ "/oauth/revoke",
81
110
  ]);
82
111
 
83
112
  const AUTH_PREFIXES = ["/auth/github/"];
@@ -94,27 +123,42 @@ const betterAuthAuthPrefixes = (basePath: string): string[] => {
94
123
  `${base}/send-verification-email`,
95
124
  `${base}/verify-email`,
96
125
  `${base}/callback`,
126
+ `${base}/oauth-handoff`,
127
+ `${base}/one-time-token`,
97
128
  ];
98
129
  };
99
130
 
100
- export const classifyRateLimitPolicy = (
101
- req: Request,
102
- betterAuthBasePath = DEFAULT_BETTER_AUTH_BASE_PATH
103
- ): RateLimitPolicyName => {
104
- const path = requestPath(req);
131
+ const isAuthPath = (path: string, betterAuthBasePath: string): boolean => {
105
132
  if (AUTH_EXACT.has(path)) {
106
- return "auth";
133
+ return true;
107
134
  }
108
135
  for (const prefix of AUTH_PREFIXES) {
109
136
  if (path.startsWith(prefix)) {
110
- return "auth";
137
+ return true;
111
138
  }
112
139
  }
113
140
  for (const prefix of betterAuthAuthPrefixes(betterAuthBasePath)) {
114
141
  if (path === prefix || path.startsWith(`${prefix}/`)) {
115
- return "auth";
142
+ return true;
116
143
  }
117
144
  }
145
+ return false;
146
+ };
147
+
148
+ /**
149
+ * Charge the auth bucket when either the path as written or its dot-segment-resolved form is a
150
+ * credential route, since Express and Better Auth may route the same request differently.
151
+ */
152
+ export const classifyRateLimitPolicy = (
153
+ req: Request,
154
+ betterAuthBasePath = DEFAULT_BETTER_AUTH_BASE_PATH
155
+ ): RateLimitPolicyName => {
156
+ if (
157
+ isAuthPath(requestPath(req), betterAuthBasePath) ||
158
+ isAuthPath(rawRequestPath(req), betterAuthBasePath)
159
+ ) {
160
+ return "auth";
161
+ }
118
162
  return "api";
119
163
  };
120
164