@terreno/api 57.16.2 → 57.17.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,86 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpOAuthAuthorization = void 0;
7
+ const mongoose_1 = __importDefault(require("mongoose"));
8
+ const plugins_1 = require("../plugins");
9
+ const mcpOAuthAuthorizationSchema = new mongoose_1.default.Schema({
10
+ clientId: {
11
+ description: "OAuth client that started this authorization request",
12
+ required: true,
13
+ type: String,
14
+ },
15
+ codeChallenge: {
16
+ description: "PKCE S256 code challenge sent with the authorization request",
17
+ required: true,
18
+ type: String,
19
+ },
20
+ codeExpiresAt: {
21
+ description: "When the issued authorization code stops being exchangeable",
22
+ type: Date,
23
+ },
24
+ codeHash: {
25
+ description: "SHA-256 hash of the issued authorization code",
26
+ index: { sparse: true, unique: true },
27
+ type: String,
28
+ },
29
+ expiresAt: {
30
+ description: "When the pending request expires and the document is removed",
31
+ required: true,
32
+ type: Date,
33
+ },
34
+ familyId: {
35
+ description: "Token family issued from this code, revoked if the code is replayed",
36
+ type: String,
37
+ },
38
+ redirectUri: {
39
+ description: "Registered redirect URI the code is delivered to",
40
+ required: true,
41
+ type: String,
42
+ },
43
+ requestId: {
44
+ description: "Opaque id handed to the consent screen to identify this request",
45
+ required: true,
46
+ type: String,
47
+ unique: true,
48
+ },
49
+ resource: {
50
+ description: "RFC 8707 resource indicator the client asked for",
51
+ type: String,
52
+ },
53
+ scope: {
54
+ description: "Space-separated scopes requested by the client",
55
+ type: String,
56
+ },
57
+ state: {
58
+ description: "Opaque client state echoed back on the redirect",
59
+ type: String,
60
+ },
61
+ status: {
62
+ default: "pending",
63
+ description: "pending, approved (code outstanding), denied, or used (code exchanged)",
64
+ enum: ["pending", "approved", "denied", "used"],
65
+ type: String,
66
+ },
67
+ tokenEpoch: {
68
+ description: "The approving user's tokenEpoch; a code is refused after it changes",
69
+ type: Number,
70
+ },
71
+ usedAt: {
72
+ description: "When the authorization code was exchanged",
73
+ type: Date,
74
+ },
75
+ userId: {
76
+ description: "The user who approved or denied the request",
77
+ ref: "User",
78
+ type: mongoose_1.default.Schema.Types.ObjectId,
79
+ },
80
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
81
+ mcpOAuthAuthorizationSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
82
+ mcpOAuthAuthorizationSchema.plugin(plugins_1.createdUpdatedPlugin);
83
+ mcpOAuthAuthorizationSchema.plugin(plugins_1.findOneOrNone);
84
+ mcpOAuthAuthorizationSchema.plugin(plugins_1.findExactlyOne);
85
+ exports.McpOAuthAuthorization = mongoose_1.default.models.TerrenoMcpOAuthAuthorization ??
86
+ mongoose_1.default.model("TerrenoMcpOAuthAuthorization", mcpOAuthAuthorizationSchema, "mcpoauthauthorizations");
@@ -0,0 +1,2 @@
1
+ import type { McpOAuthClientModel } from "../types/mcpOAuth";
2
+ export declare const McpOAuthClient: McpOAuthClientModel;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpOAuthClient = void 0;
7
+ const mongoose_1 = __importDefault(require("mongoose"));
8
+ const plugins_1 = require("../plugins");
9
+ const mcpOAuthClientSchema = new mongoose_1.default.Schema({
10
+ clientId: {
11
+ description: "Public OAuth client identifier issued by dynamic client registration",
12
+ required: true,
13
+ type: String,
14
+ unique: true,
15
+ },
16
+ clientName: {
17
+ description: "Human-readable client name shown on the consent screen",
18
+ trim: true,
19
+ type: String,
20
+ },
21
+ grantTypes: {
22
+ description: "OAuth grant types the client may use",
23
+ type: [String],
24
+ },
25
+ redirectUris: {
26
+ description: "Exact redirect URIs the client registered",
27
+ type: [String],
28
+ },
29
+ responseTypes: {
30
+ description: "OAuth response types the client may request",
31
+ type: [String],
32
+ },
33
+ scope: {
34
+ description: "Space-separated scopes the client registered for",
35
+ type: String,
36
+ },
37
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
38
+ mcpOAuthClientSchema.plugin(plugins_1.createdUpdatedPlugin);
39
+ mcpOAuthClientSchema.plugin(plugins_1.findOneOrNone);
40
+ mcpOAuthClientSchema.plugin(plugins_1.findExactlyOne);
41
+ exports.McpOAuthClient = mongoose_1.default.models.TerrenoMcpOAuthClient ??
42
+ mongoose_1.default.model("TerrenoMcpOAuthClient", mcpOAuthClientSchema, "mcpoauthclients");
@@ -0,0 +1,2 @@
1
+ import type { McpOAuthRevokedFamilyModel } from "../types/mcpOAuth";
2
+ export declare const McpOAuthRevokedFamily: McpOAuthRevokedFamilyModel;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpOAuthRevokedFamily = void 0;
7
+ const mongoose_1 = __importDefault(require("mongoose"));
8
+ const plugins_1 = require("../plugins");
9
+ /**
10
+ * Tombstone for a revoked token family. `McpOAuthToken.issue` refuses a family that has one, so
11
+ * a request that won a rotation or code exchange before the revoke cannot add a live pair after.
12
+ */
13
+ const mcpOAuthRevokedFamilySchema = new mongoose_1.default.Schema({
14
+ expiresAt: {
15
+ description: "When the tombstone is removed; set past the last refresh expiry in the family",
16
+ required: true,
17
+ type: Date,
18
+ },
19
+ familyId: {
20
+ description: "Rotation chain id that was revoked",
21
+ required: true,
22
+ type: String,
23
+ unique: true,
24
+ },
25
+ revokedAt: {
26
+ description: "When the family was first revoked",
27
+ required: true,
28
+ type: Date,
29
+ },
30
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
31
+ mcpOAuthRevokedFamilySchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
32
+ mcpOAuthRevokedFamilySchema.plugin(plugins_1.createdUpdatedPlugin);
33
+ mcpOAuthRevokedFamilySchema.plugin(plugins_1.findOneOrNone);
34
+ mcpOAuthRevokedFamilySchema.plugin(plugins_1.findExactlyOne);
35
+ exports.McpOAuthRevokedFamily = mongoose_1.default.models.TerrenoMcpOAuthRevokedFamily ??
36
+ mongoose_1.default.model("TerrenoMcpOAuthRevokedFamily", mcpOAuthRevokedFamilySchema, "mcpoauthrevokedfamilies");
@@ -0,0 +1,12 @@
1
+ import type { McpOAuthTokenModel } from "../types/mcpOAuth";
2
+ /** Access tokens carry a prefix distinct from `mcp_` service tokens so `/mcp` can route them. */
3
+ export declare const MCP_OAUTH_ACCESS_TOKEN_PREFIX = "mcpat_";
4
+ /** Thrown by `McpOAuthToken.issue` for a family that was revoked. Answer it as `invalid_grant`. */
5
+ export declare class McpOAuthFamilyRevokedError extends Error {
6
+ readonly familyId: string;
7
+ constructor(familyId: string);
8
+ }
9
+ /** Codes, tokens, and request ids are stored only as SHA-256 hashes. */
10
+ export declare const hashMcpOAuthSecret: (secret: string) => string;
11
+ export declare const generateMcpOAuthSecret: (prefix?: string) => string;
12
+ export declare const McpOAuthToken: McpOAuthTokenModel;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpOAuthToken = exports.generateMcpOAuthSecret = exports.hashMcpOAuthSecret = exports.McpOAuthFamilyRevokedError = exports.MCP_OAUTH_ACCESS_TOKEN_PREFIX = void 0;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const luxon_1 = require("luxon");
9
+ const mongoose_1 = __importDefault(require("mongoose"));
10
+ const plugins_1 = require("../plugins");
11
+ const mcpOAuthRevokedFamily_1 = require("./mcpOAuthRevokedFamily");
12
+ /** Access tokens carry a prefix distinct from `mcp_` service tokens so `/mcp` can route them. */
13
+ exports.MCP_OAUTH_ACCESS_TOKEN_PREFIX = "mcpat_";
14
+ const MCP_OAUTH_REFRESH_TOKEN_PREFIX = "mcprt_";
15
+ const MCP_OAUTH_TOKEN_RANDOM_BYTES = 32;
16
+ // A tombstone outlives in-flight requests even when the family has no unexpired refresh token.
17
+ const MIN_REVOKED_FAMILY_RETENTION_SECONDS = 60 * 60;
18
+ /** Thrown by `McpOAuthToken.issue` for a family that was revoked. Answer it as `invalid_grant`. */
19
+ class McpOAuthFamilyRevokedError extends Error {
20
+ familyId;
21
+ constructor(familyId) {
22
+ super("The token family was revoked");
23
+ this.familyId = familyId;
24
+ this.name = "McpOAuthFamilyRevokedError";
25
+ }
26
+ }
27
+ exports.McpOAuthFamilyRevokedError = McpOAuthFamilyRevokedError;
28
+ const isFamilyRevoked = async (familyId) => Boolean(await mcpOAuthRevokedFamily_1.McpOAuthRevokedFamily.exists({ familyId }));
29
+ /** Codes, tokens, and request ids are stored only as SHA-256 hashes. */
30
+ const hashMcpOAuthSecret = (secret) => (0, node_crypto_1.createHash)("sha256").update(secret).digest("hex");
31
+ exports.hashMcpOAuthSecret = hashMcpOAuthSecret;
32
+ const generateMcpOAuthSecret = (prefix = "") => `${prefix}${(0, node_crypto_1.randomBytes)(MCP_OAUTH_TOKEN_RANDOM_BYTES).toString("base64url")}`;
33
+ exports.generateMcpOAuthSecret = generateMcpOAuthSecret;
34
+ const mcpOAuthTokenSchema = new mongoose_1.default.Schema({
35
+ accessExpiresAt: {
36
+ description: "When the access token stops authenticating MCP requests",
37
+ required: true,
38
+ type: Date,
39
+ },
40
+ accessTokenHash: {
41
+ description: "SHA-256 hash of the opaque access token",
42
+ required: true,
43
+ type: String,
44
+ unique: true,
45
+ },
46
+ clientId: {
47
+ description: "OAuth client the tokens were issued to",
48
+ required: true,
49
+ type: String,
50
+ },
51
+ familyId: {
52
+ description: "Rotation chain id shared by every pair issued from one authorization",
53
+ index: true,
54
+ required: true,
55
+ type: String,
56
+ },
57
+ refreshExpiresAt: {
58
+ description: "When the refresh token stops being exchangeable; the document is removed then",
59
+ required: true,
60
+ type: Date,
61
+ },
62
+ refreshTokenHash: {
63
+ description: "SHA-256 hash of the opaque refresh token",
64
+ required: true,
65
+ type: String,
66
+ unique: true,
67
+ },
68
+ resource: {
69
+ description: "RFC 8707 resource the tokens are bound to",
70
+ type: String,
71
+ },
72
+ revokedAt: {
73
+ description: "When the pair was revoked; unset while it remains active",
74
+ type: Date,
75
+ },
76
+ rotatedAt: {
77
+ description: "When the refresh token was exchanged for a new pair",
78
+ type: Date,
79
+ },
80
+ scope: {
81
+ description: "Space-separated scopes granted",
82
+ type: String,
83
+ },
84
+ tokenEpoch: {
85
+ description: "The user's tokenEpoch when the grant was approved; the pair stops working after it changes",
86
+ type: Number,
87
+ },
88
+ userId: {
89
+ description: "The user the tokens act as",
90
+ index: true,
91
+ ref: "User",
92
+ required: true,
93
+ type: mongoose_1.default.Schema.Types.ObjectId,
94
+ },
95
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
96
+ mcpOAuthTokenSchema.index({ refreshExpiresAt: 1 }, { expireAfterSeconds: 0 });
97
+ mcpOAuthTokenSchema.plugin(plugins_1.createdUpdatedPlugin);
98
+ mcpOAuthTokenSchema.plugin(plugins_1.findOneOrNone);
99
+ mcpOAuthTokenSchema.plugin(plugins_1.findExactlyOne);
100
+ mcpOAuthTokenSchema.statics = {
101
+ ...mcpOAuthTokenSchema.statics,
102
+ async issue(options) {
103
+ const familyId = options.familyId ?? (0, node_crypto_1.randomUUID)();
104
+ if (await isFamilyRevoked(familyId)) {
105
+ throw new McpOAuthFamilyRevokedError(familyId);
106
+ }
107
+ const accessToken = (0, exports.generateMcpOAuthSecret)(exports.MCP_OAUTH_ACCESS_TOKEN_PREFIX);
108
+ const refreshToken = (0, exports.generateMcpOAuthSecret)(MCP_OAUTH_REFRESH_TOKEN_PREFIX);
109
+ const now = luxon_1.DateTime.now();
110
+ const mcpOAuthToken = await this.create({
111
+ accessExpiresAt: now.plus({ seconds: options.accessTokenTtlSeconds }).toJSDate(),
112
+ accessTokenHash: (0, exports.hashMcpOAuthSecret)(accessToken),
113
+ clientId: options.clientId,
114
+ familyId,
115
+ refreshExpiresAt: now.plus({ seconds: options.refreshTokenTtlSeconds }).toJSDate(),
116
+ refreshTokenHash: (0, exports.hashMcpOAuthSecret)(refreshToken),
117
+ resource: options.resource,
118
+ scope: options.scope,
119
+ tokenEpoch: options.tokenEpoch ?? 0,
120
+ userId: options.userId,
121
+ });
122
+ // revokeFamily writes the tombstone before it revokes pairs, so a revoke that raced this
123
+ // create has either revoked the new pair already or is visible here.
124
+ if (await isFamilyRevoked(familyId)) {
125
+ await this.updateOne({ _id: mcpOAuthToken._id, revokedAt: { $exists: false } }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
126
+ throw new McpOAuthFamilyRevokedError(familyId);
127
+ }
128
+ return { accessToken, mcpOAuthToken, refreshToken };
129
+ },
130
+ async revokeFamily(familyId) {
131
+ const now = luxon_1.DateTime.now();
132
+ const [latest] = await this.find({ familyId })
133
+ .sort({ refreshExpiresAt: -1 })
134
+ .limit(1)
135
+ .select({ refreshExpiresAt: 1 });
136
+ const minimumRetention = now.plus({ seconds: MIN_REVOKED_FAMILY_RETENTION_SECONDS });
137
+ const retainUntil = latest
138
+ ? luxon_1.DateTime.max(minimumRetention, luxon_1.DateTime.fromJSDate(latest.refreshExpiresAt))
139
+ : minimumRetention;
140
+ // The tombstone goes first: issue checks it again after creating a pair.
141
+ await mcpOAuthRevokedFamily_1.McpOAuthRevokedFamily.updateOne({ familyId }, {
142
+ $max: { expiresAt: retainUntil.toJSDate() },
143
+ $setOnInsert: { revokedAt: now.toJSDate() },
144
+ }, { upsert: true });
145
+ await this.updateMany({ familyId, revokedAt: { $exists: false } }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
146
+ },
147
+ async verifyAccessToken(token) {
148
+ if (!token.startsWith(exports.MCP_OAUTH_ACCESS_TOKEN_PREFIX)) {
149
+ return null;
150
+ }
151
+ return this.findOneOrNone({
152
+ accessExpiresAt: { $gt: luxon_1.DateTime.now().toJSDate() },
153
+ accessTokenHash: (0, exports.hashMcpOAuthSecret)(token),
154
+ revokedAt: { $exists: false },
155
+ });
156
+ },
157
+ };
158
+ exports.McpOAuthToken = mongoose_1.default.models.TerrenoMcpOAuthToken ??
159
+ mongoose_1.default.model("TerrenoMcpOAuthToken", mcpOAuthTokenSchema, "mcpoauthtokens");
@@ -1,3 +1,4 @@
1
1
  import type { McpServiceTokenModel } from "../types/mcpServiceToken";
2
2
  export type { McpServiceTokenDocument, McpServiceTokenIssueOptions, McpServiceTokenModel, McpServiceTokenStatics, } from "../types/mcpServiceToken";
3
+ export declare const MCP_SERVICE_TOKEN_PREFIX = "mcp_";
3
4
  export declare const McpServiceToken: McpServiceTokenModel;
@@ -3,12 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.McpServiceToken = void 0;
6
+ exports.McpServiceToken = exports.MCP_SERVICE_TOKEN_PREFIX = void 0;
7
7
  const node_crypto_1 = require("node:crypto");
8
8
  const luxon_1 = require("luxon");
9
9
  const mongoose_1 = __importDefault(require("mongoose"));
10
10
  const plugins_1 = require("../plugins");
11
- const MCP_SERVICE_TOKEN_PREFIX = "mcp_";
11
+ exports.MCP_SERVICE_TOKEN_PREFIX = "mcp_";
12
12
  const MCP_SERVICE_TOKEN_RANDOM_BYTES = 32;
13
13
  const MCP_SERVICE_TOKEN_DISPLAY_LENGTH = 8;
14
14
  const hashToken = (token) => (0, node_crypto_1.createHash)("sha256").update(token).digest("hex");
@@ -31,6 +31,10 @@ const mcpServiceTokenSchema = new mongoose_1.default.Schema({
31
31
  description: "When this MCP service token was revoked; unset while it remains active",
32
32
  type: Date,
33
33
  },
34
+ tokenEpoch: {
35
+ description: "The user's tokenEpoch when the token was issued; the token stops working after it changes",
36
+ type: Number,
37
+ },
34
38
  tokenHash: {
35
39
  description: "SHA-256 hash of the full MCP service token plaintext",
36
40
  required: true,
@@ -88,12 +92,13 @@ mcpServiceTokenSchema.statics = {
88
92
  });
89
93
  },
90
94
  async issueFor(user, options) {
91
- const token = `${MCP_SERVICE_TOKEN_PREFIX}${(0, node_crypto_1.randomBytes)(MCP_SERVICE_TOKEN_RANDOM_BYTES).toString("hex")}`;
95
+ const token = `${exports.MCP_SERVICE_TOKEN_PREFIX}${(0, node_crypto_1.randomBytes)(MCP_SERVICE_TOKEN_RANDOM_BYTES).toString("hex")}`;
92
96
  const mcpServiceToken = await this.create({
93
97
  expiresAt: options.expiresAt,
94
98
  name: options.name,
99
+ tokenEpoch: user.tokenEpoch ?? 0,
95
100
  tokenHash: hashToken(token),
96
- tokenPrefix: token.slice(MCP_SERVICE_TOKEN_PREFIX.length, MCP_SERVICE_TOKEN_PREFIX.length + MCP_SERVICE_TOKEN_DISPLAY_LENGTH),
101
+ tokenPrefix: token.slice(exports.MCP_SERVICE_TOKEN_PREFIX.length, exports.MCP_SERVICE_TOKEN_PREFIX.length + MCP_SERVICE_TOKEN_DISPLAY_LENGTH),
97
102
  userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
98
103
  });
99
104
  return { mcpServiceToken, token };
@@ -105,6 +110,18 @@ mcpServiceTokenSchema.statics = {
105
110
  userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
106
111
  }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } }, { returnDocument: "after" });
107
112
  },
113
+ /**
114
+ * Revoke the user's active tokens issued under an earlier tokenEpoch. A token from before the
115
+ * field existed counts as epoch 0, the same way a refresh token without `te` does.
116
+ */
117
+ async revokeOutdatedForUser(user) {
118
+ const currentEpoch = user.tokenEpoch ?? 0;
119
+ await this.updateMany({
120
+ revokedAt: { $exists: false },
121
+ tokenEpoch: { $nin: currentEpoch === 0 ? [0, null] : [currentEpoch] },
122
+ userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
123
+ }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
124
+ },
108
125
  async verify(token) {
109
126
  const now = luxon_1.DateTime.now().toJSDate();
110
127
  return this.findOneOrNone({
@@ -4,6 +4,13 @@ import type { Model } from "mongoose";
4
4
  import type { ModelRouterOptions, RESTMethod } from "./api";
5
5
  import type { User } from "./auth";
6
6
  export type PermissionMethod<T> = (method: RESTMethod, user?: User, obj?: T) => boolean | Promise<boolean>;
7
+ /**
8
+ * Permission that refuses an MCP OAuth access token unless it was granted `scope`. Other
9
+ * credentials (the user's own JWT or Better Auth session, and `mcp_` service tokens) are not
10
+ * scoped and pass. Combine it with the method's other permissions, for example
11
+ * `[Permissions.IsAuthenticated, requireOAuthScope("write")]`.
12
+ */
13
+ export declare const requireOAuthScope: (scope: string) => PermissionMethod<unknown>;
7
14
  export interface RESTPermissions<T> {
8
15
  create: PermissionMethod<T>[];
9
16
  list: PermissionMethod<T>[];
@@ -1,9 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OrganizationQueryFilter = exports.getUserOrganizationIds = exports.OwnerQueryFilter = void 0;
3
+ exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OrganizationQueryFilter = exports.getUserOrganizationIds = exports.OwnerQueryFilter = exports.requireOAuthScope = void 0;
4
4
  const docLoader_1 = require("./docLoader");
5
5
  const errors_1 = require("./errors");
6
6
  const orgPermissions_1 = require("./orgs/orgPermissions");
7
+ const requestContext_1 = require("./requestContext");
8
+ /**
9
+ * Permission that refuses an MCP OAuth access token unless it was granted `scope`. Other
10
+ * credentials (the user's own JWT or Better Auth session, and `mcp_` service tokens) are not
11
+ * scoped and pass. Combine it with the method's other permissions, for example
12
+ * `[Permissions.IsAuthenticated, requireOAuthScope("write")]`.
13
+ */
14
+ const requireOAuthScope = (scope) => {
15
+ return () => {
16
+ const context = (0, requestContext_1.getCurrentRequestContext)();
17
+ if (context?.credential !== "oauth") {
18
+ return true;
19
+ }
20
+ return context.oauthScopes?.includes(scope) === true;
21
+ };
22
+ };
23
+ exports.requireOAuthScope = requireOAuthScope;
7
24
  const OwnerQueryFilter = (user) => {
8
25
  if (user) {
9
26
  return { ownerId: user?.id };
@@ -6,5 +6,9 @@ import type { RateLimitPolicyName } from "./types";
6
6
  */
7
7
  export declare const isJwtCredentialExchangePath: (req: Request) => boolean;
8
8
  export declare const shouldSkipRateLimit: (req: Request, extraSkip?: (req: Request) => boolean) => boolean;
9
+ /**
10
+ * Charge the auth bucket when either the path as written or its dot-segment-resolved form is a
11
+ * credential route, since Express and Better Auth may route the same request differently.
12
+ */
9
13
  export declare const classifyRateLimitPolicy: (req: Request, betterAuthBasePath?: string) => RateLimitPolicyName;
10
14
  export declare const rateLimitKey: (req: Request, policy: RateLimitPolicyName) => string;
@@ -16,11 +16,30 @@ const normalizeRequestPath = (url) => {
16
16
  : withoutQuery;
17
17
  return withoutSlash.toLowerCase();
18
18
  };
19
+ const PATH_BASE = "http://terreno.invalid";
20
+ /**
21
+ * Resolve `.`/`..` segments (including `%2e` forms) the way the WHATWG URL parser does. Better
22
+ * Auth routes on that parsed pathname, so `/api/auth/%2e/sign-in/email` reaches sign-in.
23
+ */
24
+ const resolveDotSegments = (path) => {
25
+ try {
26
+ const url = path.startsWith("/") ? new URL(`${PATH_BASE}${path}`) : new URL(path, PATH_BASE);
27
+ return url.pathname;
28
+ }
29
+ catch {
30
+ return path;
31
+ }
32
+ };
19
33
  /** Prefer Express `req.path` (routing) over the raw request-target. */
20
- const requestPath = (req) => {
34
+ const rawRequestPath = (req) => {
21
35
  const raw = req.path || req.url || req.originalUrl || "";
22
36
  return normalizeRequestPath(raw);
23
37
  };
38
+ /** The request path as a WHATWG-normalizing router such as Better Auth's sees it. */
39
+ const requestPath = (req) => {
40
+ const raw = req.path || req.url || req.originalUrl || "";
41
+ return normalizeRequestPath(resolveDotSegments(stripQueryAndFragment(raw)));
42
+ };
24
43
  const JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
25
44
  "/auth/login",
26
45
  "/auth/signup",
@@ -35,11 +54,15 @@ const JWT_CREDENTIAL_EXCHANGE_EXACT = new Set([
35
54
  * `setupAuth` runs before those routes so the client can still exchange credentials.
36
55
  */
37
56
  const isJwtCredentialExchangePath = (req) => {
38
- return JWT_CREDENTIAL_EXCHANGE_EXACT.has(requestPath(req));
57
+ return JWT_CREDENTIAL_EXCHANGE_EXACT.has(rawRequestPath(req));
39
58
  };
40
59
  exports.isJwtCredentialExchangePath = isJwtCredentialExchangePath;
41
60
  const shouldSkipRateLimit = (req, extraSkip) => {
42
61
  const path = requestPath(req);
62
+ // A path with dot segments may route somewhere else than it looks; never exempt it.
63
+ if (path !== rawRequestPath(req)) {
64
+ return false;
65
+ }
43
66
  if (req.method === "GET" && (path === "/health" || path === "/healthz")) {
44
67
  return true;
45
68
  }
@@ -68,6 +91,10 @@ const AUTH_EXACT = new Set([
68
91
  "/auth/github",
69
92
  "/auth/github/callback",
70
93
  "/auth/github/failure",
94
+ "/oauth/register",
95
+ "/oauth/authorize",
96
+ "/oauth/token",
97
+ "/oauth/revoke",
71
98
  ]);
72
99
  const AUTH_PREFIXES = ["/auth/github/"];
73
100
  const betterAuthAuthPrefixes = (basePath) => {
@@ -82,23 +109,35 @@ const betterAuthAuthPrefixes = (basePath) => {
82
109
  `${base}/send-verification-email`,
83
110
  `${base}/verify-email`,
84
111
  `${base}/callback`,
112
+ `${base}/oauth-handoff`,
113
+ `${base}/one-time-token`,
85
114
  ];
86
115
  };
87
- const classifyRateLimitPolicy = (req, betterAuthBasePath = DEFAULT_BETTER_AUTH_BASE_PATH) => {
88
- const path = requestPath(req);
116
+ const isAuthPath = (path, betterAuthBasePath) => {
89
117
  if (AUTH_EXACT.has(path)) {
90
- return "auth";
118
+ return true;
91
119
  }
92
120
  for (const prefix of AUTH_PREFIXES) {
93
121
  if (path.startsWith(prefix)) {
94
- return "auth";
122
+ return true;
95
123
  }
96
124
  }
97
125
  for (const prefix of betterAuthAuthPrefixes(betterAuthBasePath)) {
98
126
  if (path === prefix || path.startsWith(`${prefix}/`)) {
99
- return "auth";
127
+ return true;
100
128
  }
101
129
  }
130
+ return false;
131
+ };
132
+ /**
133
+ * Charge the auth bucket when either the path as written or its dot-segment-resolved form is a
134
+ * credential route, since Express and Better Auth may route the same request differently.
135
+ */
136
+ const classifyRateLimitPolicy = (req, betterAuthBasePath = DEFAULT_BETTER_AUTH_BASE_PATH) => {
137
+ if (isAuthPath(requestPath(req), betterAuthBasePath) ||
138
+ isAuthPath(rawRequestPath(req), betterAuthBasePath)) {
139
+ return "auth";
140
+ }
102
141
  return "api";
103
142
  };
104
143
  exports.classifyRateLimitPolicy = classifyRateLimitPolicy;
@@ -162,6 +162,7 @@ const createAccess = (options) => {
162
162
  queryFilter,
163
163
  roles: roleManager,
164
164
  statements: mergedStatements,
165
+ userModel: options.userModel,
165
166
  };
166
167
  };
167
168
  exports.createAccess = createAccess;
@@ -3,4 +3,8 @@ import type { PermissionSource } from "./types";
3
3
  export declare const MEMBERSHIP_ORG_ADMIN_PERMISSION_SOURCE_NAME = "membership-org-admin";
4
4
  /** Grants applied when `Membership.roleName` is `org-admin` in the current org context. */
5
5
  export declare const ORG_ADMIN_PERMISSION_BUNDLE: PermissionSet;
6
+ /**
7
+ * Additive-only: it never returns `deny`, so an outage drops only its org-admin grants and does
8
+ * not fail resolution closed.
9
+ */
6
10
  export declare const membershipOrgAdminPermissionSource: () => PermissionSource;
@@ -29,7 +29,12 @@ const shellOnlyOrgAdminGrants = () => ({
29
29
  admin: [...exports.ORG_ADMIN_PERMISSION_BUNDLE.admin],
30
30
  },
31
31
  });
32
+ /**
33
+ * Additive-only: it never returns `deny`, so an outage drops only its org-admin grants and does
34
+ * not fail resolution closed.
35
+ */
32
36
  const membershipOrgAdminPermissionSource = () => ({
37
+ failClosedWhenDenyUnknown: false,
33
38
  getGrants: async ({ user }) => {
34
39
  const contextMembership = (0, orgContext_1.getOrgContext)()?.membership;
35
40
  if (contextMembership) {
@@ -1,9 +1,15 @@
1
1
  import type express from "express";
2
2
  import type { RESTMethod } from "../api";
3
3
  import type { User } from "../auth";
4
- import type { RESTPermissions } from "../permissions";
4
+ import type { PermissionMethod, RESTPermissions } from "../permissions";
5
5
  import type { AnyTerrenoAccess, ModelRouterAccessOptions, ResourceScope } from "./types";
6
6
  export declare const resolveActionForMethod: (method: RESTMethod, access: ModelRouterAccessOptions, statements: Record<string, readonly string[]>) => string | null;
7
+ /**
8
+ * Per-document check for a router-level `access.scope`, shared by CRUD permissions and modelRouter
9
+ * actions. Returns undefined when the router has no scope check.
10
+ * @internal
11
+ */
12
+ export declare const buildAccessScopeCheck: <T>(accessControl: AnyTerrenoAccess, access: ModelRouterAccessOptions, action: string) => PermissionMethod<T> | undefined;
7
13
  /** @internal */
8
14
  export declare const buildAccessPermissions: <T>(accessControl: AnyTerrenoAccess, access: ModelRouterAccessOptions) => RESTPermissions<T>;
9
15
  /** @internal */