@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
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveModelRouterAccess = exports.validateAccessWritePayload = exports.validateAccessWriteBody = exports.wrapAccessResponseHandler = exports.buildAccessQueryFilter = exports.buildAccessPermissions = exports.resolveActionForMethod = void 0;
3
+ exports.resolveModelRouterAccess = exports.validateAccessWritePayload = exports.validateAccessWriteBody = exports.wrapAccessResponseHandler = exports.buildAccessQueryFilter = exports.buildAccessPermissions = exports.buildAccessScopeCheck = exports.resolveActionForMethod = void 0;
4
4
  const errors_1 = require("../errors");
5
5
  const transformers_1 = require("../transformers");
6
6
  const fieldViews_1 = require("./fieldViews");
@@ -48,6 +48,39 @@ exports.resolveActionForMethod = resolveActionForMethod;
48
48
  const buildPermissionRequest = (resource, action) => ({
49
49
  [resource]: [action],
50
50
  });
51
+ /**
52
+ * Per-document check for a router-level `access.scope`, shared by CRUD permissions and modelRouter
53
+ * actions. Returns undefined when the router has no scope check.
54
+ * @internal
55
+ */
56
+ const buildAccessScopeCheck = (accessControl, access, action) => {
57
+ if (!access.scope?.check) {
58
+ return undefined;
59
+ }
60
+ return async (_method, user, obj) => {
61
+ if (!user) {
62
+ return false;
63
+ }
64
+ const result = await access.scope?.check?.({
65
+ action,
66
+ doc: obj,
67
+ user,
68
+ });
69
+ if (result === false) {
70
+ return false;
71
+ }
72
+ if (result && typeof result === "object") {
73
+ const extra = await accessControl.can({
74
+ doc: obj,
75
+ permissions: result,
76
+ user,
77
+ });
78
+ return extra.allowed;
79
+ }
80
+ return true;
81
+ };
82
+ };
83
+ exports.buildAccessScopeCheck = buildAccessScopeCheck;
51
84
  /** @internal */
52
85
  const buildAccessPermissions = (accessControl, access) => {
53
86
  const isPermitted = (0, middleware_1.createIsPermitted)({ can: accessControl.can });
@@ -60,29 +93,9 @@ const buildAccessPermissions = (accessControl, access) => {
60
93
  const checks = [
61
94
  isPermitted(buildPermissionRequest(access.resource, action)),
62
95
  ];
63
- if (access.scope?.check) {
64
- checks.push(async (_method, user, obj) => {
65
- if (!user) {
66
- return false;
67
- }
68
- const result = await access.scope?.check?.({
69
- action,
70
- doc: obj,
71
- user,
72
- });
73
- if (result === false) {
74
- return false;
75
- }
76
- if (result && typeof result === "object") {
77
- const extra = await accessControl.can({
78
- doc: obj,
79
- permissions: result,
80
- user,
81
- });
82
- return extra.allowed;
83
- }
84
- return true;
85
- });
96
+ const scopeCheck = (0, exports.buildAccessScopeCheck)(accessControl, access, action);
97
+ if (scopeCheck) {
98
+ checks.push(scopeCheck);
86
99
  }
87
100
  const also = access.also?.[method] ?? [];
88
101
  return [...checks, ...also];
@@ -24,6 +24,15 @@ const resolveActionForMethod = (method, access, statements) => {
24
24
  }
25
25
  return DEFAULT_METHOD_ACTIONS[method];
26
26
  };
27
+ // REST and snapshot permissions append access.also[method] to the RBAC role and scope checks
28
+ // (buildAccessPermissions), so realtime decisions must apply them too.
29
+ const checkAlsoPermissions = async (access, method, user, doc) => {
30
+ const also = access.also?.[method] ?? [];
31
+ if (also.length === 0) {
32
+ return true;
33
+ }
34
+ return (0, permissions_1.checkPermissions)(method, also, user, doc);
35
+ };
27
36
  const canSubscribeRealtime = async (entry, method, user) => {
28
37
  const access = entry.options.access;
29
38
  const accessControl = entry.options.accessControl;
@@ -38,7 +47,10 @@ const canSubscribeRealtime = async (entry, method, user) => {
38
47
  permissions: { [access.resource]: [action] },
39
48
  user,
40
49
  });
41
- return result.allowed;
50
+ if (!result.allowed) {
51
+ return false;
52
+ }
53
+ return checkAlsoPermissions(access, method, user);
42
54
  }
43
55
  const permissions = entry.options.permissions?.[method] ?? [];
44
56
  return (0, permissions_1.checkPermissions)(method, permissions, user);
@@ -81,10 +93,12 @@ const canReadDocumentRealtime = async (entry, user, doc) => {
81
93
  permissions: scopeResult,
82
94
  user,
83
95
  });
84
- return extra.allowed;
96
+ if (!extra.allowed) {
97
+ return false;
98
+ }
85
99
  }
86
100
  }
87
- return true;
101
+ return checkAlsoPermissions(access, "read", user, doc);
88
102
  }
89
103
  return (0, permissions_1.checkPermissions)("read", entry.options.permissions?.read ?? [], user, doc);
90
104
  };
@@ -3,10 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createPermissionResolver = void 0;
4
4
  const access_1 = require("better-auth/plugins/access");
5
5
  const luxon_1 = require("luxon");
6
+ const errors_1 = require("../errors");
6
7
  const logger_1 = require("../logger");
7
8
  const orgContext_1 = require("../orgs/orgContext");
8
9
  const permissionUtils_1 = require("./permissionUtils");
9
10
  const DEFAULT_CACHE_TTL_MS = 30_000;
11
+ /** Sources fail closed on a cold failure unless they opt out (additive-only sources). */
12
+ const failsClosedWhenDenyUnknown = (source) => {
13
+ return source.failClosedWhenDenyUnknown !== false;
14
+ };
10
15
  const DEFAULT_MAX_CACHE_ENTRIES = 10_000;
11
16
  const getUserRoles = (user) => {
12
17
  const withRoles = user;
@@ -32,6 +37,12 @@ const createPermissionResolver = (args) => {
32
37
  const ac = (0, access_1.createAccessControl)(statements);
33
38
  const permissionCache = new Map();
34
39
  const sourceCache = new Map();
40
+ // Last-known deny set per user and source from the last successful fetch. Kept apart from the
41
+ // grant caches so role edits (invalidateCache) and permission-cache eviction cannot lift an
42
+ // IdP/ABAC restriction while its source is down. Only users with a deny set (or a source that
43
+ // fails closed when the deny is unknown, the default, which needs a "no deny" marker) take an
44
+ // entry.
45
+ const denyPosture = new Map();
35
46
  const enforceCacheBound = () => {
36
47
  const now = luxon_1.DateTime.now().toMillis();
37
48
  for (const [userId, entry] of permissionCache) {
@@ -60,6 +71,28 @@ const createPermissionResolver = (args) => {
60
71
  permissionCache.set(cacheKey, entry);
61
72
  enforceCacheBound();
62
73
  };
74
+ const recordDenyPosture = (userId, source, grants) => {
75
+ const deny = grants?.deny && Object.keys(grants.deny).length > 0 ? grants.deny : null;
76
+ const userPosture = denyPosture.get(userId);
77
+ if (!deny && !failsClosedWhenDenyUnknown(source)) {
78
+ userPosture?.delete(source.name);
79
+ if (userPosture?.size === 0) {
80
+ denyPosture.delete(userId);
81
+ }
82
+ return;
83
+ }
84
+ const next = userPosture ?? new Map();
85
+ next.set(source.name, deny);
86
+ denyPosture.delete(userId);
87
+ denyPosture.set(userId, next);
88
+ while (denyPosture.size > maxCacheEntries) {
89
+ const oldestUserId = denyPosture.keys().next().value;
90
+ if (oldestUserId === undefined) {
91
+ break;
92
+ }
93
+ denyPosture.delete(oldestUserId);
94
+ }
95
+ };
63
96
  const invalidateCache = (invalidateArgs) => {
64
97
  if (invalidateArgs?.userId) {
65
98
  deletePermissionCacheForUser(permissionCache, invalidateArgs.userId);
@@ -109,19 +142,36 @@ const createPermissionResolver = (args) => {
109
142
  }
110
143
  return { deny };
111
144
  };
112
- const grantsAfterSourceFailure = (source, cached, now) => {
145
+ const grantsAfterSourceFailure = (user, source, cached, now) => {
113
146
  const stale = grantsFromStaleCache(source, cached, now);
114
147
  if (stale) {
115
148
  return stale;
116
149
  }
117
- return denyOnlyFromCache(cached);
150
+ if (cached) {
151
+ return denyOnlyFromCache(cached);
152
+ }
153
+ const userPosture = denyPosture.get(user.id);
154
+ if (userPosture?.has(source.name)) {
155
+ const deny = userPosture.get(source.name);
156
+ return deny ? { deny } : null;
157
+ }
158
+ if (failsClosedWhenDenyUnknown(source)) {
159
+ throw new errors_1.APIError({
160
+ detail: `Permission source ${source.name} failed before its deny set was known`,
161
+ status: 503,
162
+ title: "Permission source unavailable",
163
+ });
164
+ }
165
+ return null;
118
166
  };
119
167
  const fetchSourceGrants = async (user, source, shouldCache = true) => {
120
168
  const now = luxon_1.DateTime.now().toMillis();
121
169
  const cached = sourceCache.get(user.id)?.get(source.name);
122
170
  if (!shouldCache) {
123
171
  try {
124
- return await source.getGrants({ user });
172
+ const grants = await source.getGrants({ user });
173
+ recordDenyPosture(user.id, source, grants);
174
+ return { failed: false, grants };
125
175
  }
126
176
  catch (error) {
127
177
  logger_1.logger.warn("Permission source refresh failed during uncached resolution", {
@@ -129,7 +179,7 @@ const createPermissionResolver = (args) => {
129
179
  policy: source.staleOnFailure ?? "deny",
130
180
  source: source.name,
131
181
  });
132
- return grantsAfterSourceFailure(source, cached, now);
182
+ return { failed: true, grants: grantsAfterSourceFailure(user, source, cached, now) };
133
183
  }
134
184
  }
135
185
  const userSources = sourceCache.get(user.id) ?? new Map();
@@ -138,12 +188,13 @@ const createPermissionResolver = (args) => {
138
188
  const ttlMs = source.ttlMs ?? cacheTtlMs;
139
189
  const cachedAfterTouch = userSources.get(source.name);
140
190
  if (cachedAfterTouch && now - cachedAfterTouch.fetchedAt < ttlMs) {
141
- return cachedAfterTouch.grants;
191
+ return { failed: false, grants: cachedAfterTouch.grants };
142
192
  }
143
193
  try {
144
194
  const grants = await source.getGrants({ user });
145
195
  userSources.set(source.name, { fetchedAt: now, grants });
146
- return grants;
196
+ recordDenyPosture(user.id, source, grants);
197
+ return { failed: false, grants };
147
198
  }
148
199
  catch (error) {
149
200
  logger_1.logger.warn("Permission source refresh failed", {
@@ -151,7 +202,10 @@ const createPermissionResolver = (args) => {
151
202
  policy: source.staleOnFailure ?? "deny",
152
203
  source: source.name,
153
204
  });
154
- return grantsAfterSourceFailure(source, cachedAfterTouch, now);
205
+ return {
206
+ failed: true,
207
+ grants: grantsAfterSourceFailure(user, source, cachedAfterTouch, now),
208
+ };
155
209
  }
156
210
  };
157
211
  const resolveEffectivePermissions = async (user, shouldCache) => {
@@ -166,8 +220,10 @@ const createPermissionResolver = (args) => {
166
220
  const roleNames = [...getUserRoles(user)];
167
221
  const permissionSets = [];
168
222
  const sourceResults = new Map();
223
+ let anySourceFailed = false;
169
224
  for (const source of sources) {
170
- const grants = await fetchSourceGrants(user, source, shouldCache);
225
+ const { failed, grants } = await fetchSourceGrants(user, source, shouldCache);
226
+ anySourceFailed = anySourceFailed || failed;
171
227
  sourceResults.set(source.name, grants);
172
228
  if (!grants) {
173
229
  continue;
@@ -194,7 +250,8 @@ const createPermissionResolver = (args) => {
194
250
  permissions = applyDenyGrants(permissions, grants.deny);
195
251
  }
196
252
  }
197
- if (shouldCache) {
253
+ // A set computed during a source outage is not cached, so recovery takes effect at once.
254
+ if (shouldCache && !anySourceFailed) {
198
255
  rememberPermissions(cacheKey, {
199
256
  expiresAt: luxon_1.DateTime.now().plus({ milliseconds: cacheTtlMs }).toMillis(),
200
257
  permissions,
@@ -117,6 +117,47 @@ const createRoleManager = (args) => {
117
117
  throw error;
118
118
  }
119
119
  };
120
+ // Users hold roles by name, so a rename changes who holds which permissions. Treat it like a
121
+ // permission edit: the actor must hold the role's grants, and the new name must not already
122
+ // bind any user or role (a stale `user.roles` entry would otherwise inherit the grants).
123
+ const assertRenameAllowed = async (args) => {
124
+ const { actor, existing, newName, roleName } = args;
125
+ if (existing.isLocked) {
126
+ throw new errors_1.APIError({ status: 400, title: "Cannot rename a locked role" });
127
+ }
128
+ if (typeof newName !== "string" || newName.trim() === "") {
129
+ throw new errors_1.APIError({ status: 400, title: "Role name must be a non-empty string" });
130
+ }
131
+ await assertNoEscalationOrAudit({
132
+ action: "role.update",
133
+ actor,
134
+ permissions: existing.permissions ?? {},
135
+ targetRoleName: roleName,
136
+ });
137
+ if (await rbacRoleModel.exists({ name: newName })) {
138
+ throw new errors_1.APIError({ status: 409, title: "A role with that name already exists" });
139
+ }
140
+ if (userModel && (await userModel.countDocuments({ roles: newName })) > 0) {
141
+ throw new errors_1.APIError({ status: 409, title: "Users already hold a role with that name" });
142
+ }
143
+ };
144
+ // Keeps holders of a renamed role on the same grants.
145
+ const moveRoleHolders = async (args) => {
146
+ try {
147
+ if (userModel) {
148
+ await userModel.updateMany({ roles: args.fromName }, { $set: { "roles.$": args.toName } });
149
+ }
150
+ await rbacRoleModel.updateMany({ excludesRoles: args.fromName }, { $set: { "excludesRoles.$": args.toName } });
151
+ }
152
+ catch (error) {
153
+ logger_1.logger.error("Failed to move role holders after a rename", {
154
+ error,
155
+ fromName: args.fromName,
156
+ toName: args.toName,
157
+ });
158
+ throw error;
159
+ }
160
+ };
120
161
  const seedDefaults = async () => {
121
162
  await rbacRoleModel.seedDefaults({ extraRoles: defaultRoles, statements });
122
163
  };
@@ -305,17 +346,28 @@ const createRoleManager = (args) => {
305
346
  });
306
347
  }
307
348
  }
308
- if (changes.permissions) {
309
- assertValidPermissionSet(changes.permissions, statements);
349
+ // Any `permissions` key is written below, so validate on presence, not truthiness:
350
+ // `false` or `""` would otherwise skip both checks and empty the role.
351
+ if ("permissions" in changes) {
352
+ const incoming = changes.permissions;
353
+ if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) {
354
+ throw new errors_1.APIError({
355
+ detail: "permissions must be an object of resource action lists",
356
+ status: 400,
357
+ title: "Invalid permissions",
358
+ });
359
+ }
360
+ assertValidPermissionSet(incoming, statements);
310
361
  await assertNoEscalationOrAudit({
311
362
  action: "role.update",
312
363
  actor,
313
- permissions: (0, permissionUtils_1.unionPermissionSets)(existing.permissions ?? {}, changes.permissions),
364
+ permissions: (0, permissionUtils_1.unionPermissionSets)(existing.permissions ?? {}, incoming),
314
365
  targetRoleName: roleName,
315
366
  });
316
367
  }
317
- if (changes.name && existing.isLocked) {
318
- throw new errors_1.APIError({ status: 400, title: "Cannot rename a locked role" });
368
+ const isRename = changes.name !== undefined && changes.name !== roleName;
369
+ if (isRename) {
370
+ await assertRenameAllowed({ actor, existing, newName: changes.name, roleName });
319
371
  }
320
372
  if (changes.excludesRoles && userModel) {
321
373
  const holders = await userModel.find({ roles: roleName });
@@ -344,6 +396,9 @@ const createRoleManager = (args) => {
344
396
  existing.set("description", undefined);
345
397
  }
346
398
  await existing.save();
399
+ if (isRename) {
400
+ await moveRoleHolders({ fromName: roleName, toName: existing.name });
401
+ }
347
402
  invalidateCache();
348
403
  await emitAudit({
349
404
  action: "role.update",
@@ -98,7 +98,7 @@ exports.terrenoDefaultRoles = [
98
98
  adminAnnouncementClickEvent: ["read"],
99
99
  adminAnnouncementImpression: ["read"],
100
100
  configuration: ["read", "update"],
101
- user: ["create", "list", "read", "update"],
101
+ user: ["create", "list", "read", "update", "updateIdentity"],
102
102
  ...observabilityAdminPermissionSpec(),
103
103
  },
104
104
  },
@@ -36,7 +36,7 @@ export declare const terrenoStatements: {
36
36
  readonly featureFlag: readonly ["create", "list", "read", "update", "delete"];
37
37
  readonly organization: readonly ["create", "list", "read", "update", "delete", "manageMembers", "disable"];
38
38
  readonly rbac: readonly ["read", "manageRoles", "assignRoles"];
39
- readonly user: readonly ["create", "list", "read", "update", "delete", "impersonate", "setPassword"];
39
+ readonly user: readonly ["create", "list", "read", "update", "delete", "impersonate", "setPassword", "updateIdentity"];
40
40
  };
41
41
  export type Statements = Record<string, readonly string[]>;
42
42
  export type PermissionSet = {
@@ -61,7 +61,16 @@ exports.terrenoStatements = {
61
61
  featureFlag: MODEL_CRUD,
62
62
  organization: exports.ORGANIZATION_ACTIONS,
63
63
  rbac: ["read", "manageRoles", "assignRoles"],
64
- user: ["create", "list", "read", "update", "delete", "impersonate", "setPassword"],
64
+ user: [
65
+ "create",
66
+ "list",
67
+ "read",
68
+ "update",
69
+ "delete",
70
+ "impersonate",
71
+ "setPassword",
72
+ "updateIdentity",
73
+ ],
65
74
  };
66
75
  exports.READ_ACTIONS = ["read", "list", "view"];
67
76
  exports.READ_ONLY_ROLE_PERMISSIONS = { readOnly: true };
@@ -116,6 +125,9 @@ exports.terrenoStatementDescriptions = {
116
125
  list: "List traces and observability status",
117
126
  read: "View trace detail and run trace test helpers",
118
127
  },
128
+ user: {
129
+ updateIdentity: "Change another user's email, disabled flag, email verification, or linked Better Auth and GitHub ids",
130
+ },
119
131
  };
120
132
  /** Add missing actions for selected resources without removing consumer-defined grants. */
121
133
  const mergeMissingResourcePermissions = (existing, defaults, resources) => {
@@ -116,6 +116,13 @@ export interface PermissionSource {
116
116
  ttlMs?: number;
117
117
  staleOnFailure?: StaleOnFailurePolicy;
118
118
  staleMaxAgeMs?: number;
119
+ /**
120
+ * When true (the default), a failed `getGrants` for a user this process has no last-known deny
121
+ * posture for (cold instance, or the posture was evicted) throws a 503 instead of resolving
122
+ * local roles without this source's deny. Set it to `false` on additive-only sources that never
123
+ * return `deny`, so their outage drops only their grants.
124
+ */
125
+ failClosedWhenDenyUnknown?: boolean;
119
126
  getGrants: (args: {
120
127
  user: User;
121
128
  }) => Promise<PermissionSourceGrants | null>;
@@ -204,4 +211,9 @@ export interface TerrenoAccess<S extends Statements> {
204
211
  invalidateCache: (args?: {
205
212
  userId?: string;
206
213
  }) => void;
214
+ /**
215
+ * The `userModel` passed to `createAccess`. Write paths use it to recognize the user model when
216
+ * it is compiled under a name other than `"User"`.
217
+ */
218
+ readonly userModel?: UserModel;
207
219
  }
@@ -0,0 +1,50 @@
1
+ import type { User } from "../auth";
2
+ /**
3
+ * True when a write-body key addresses `field` itself or a path inside it. Mongoose `set`,
4
+ * `create`, and the document constructor treat a dotted key such as `roles.0` as a path into
5
+ * `roles`, so field filters must match the first path segment, not only the exact key.
6
+ */
7
+ export declare const isWriteKeyForField: (key: string, field: string) => boolean;
8
+ /**
9
+ * User fields that identify the account or control whether it can sign in. Changing them on
10
+ * another user through generic RBAC user-model writes needs `user:updateIdentity` on top of
11
+ * `user:update`; see {@link assertCanWriteUserIdentity}.
12
+ */
13
+ export declare const USER_IDENTITY_FIELDS: readonly ["email", "disabled", "betterAuthId", "githubId", "emailVerified"];
14
+ /** RBAC action on the `user` resource that allows changing {@link USER_IDENTITY_FIELDS}. */
15
+ export declare const USER_UPDATE_IDENTITY_ACTION: "updateIdentity";
16
+ /**
17
+ * True when RBAC is enabled and `modelName` names the user model: `"User"`, or the compiled
18
+ * name of the `userModel` passed to `createAccess`.
19
+ */
20
+ export declare const isRbacUserModelName: (modelName: string, accessControl: unknown) => boolean;
21
+ /**
22
+ * Enforces RoleManager's target-privilege rule on generic writes to the RBAC user model: an actor
23
+ * may change or delete another user only when the actor holds every permission that user holds.
24
+ * REST, array subroutes, write instance actions, sync, and MCP all call this, so a `user:update`
25
+ * holder cannot take over or lock out a more privileged account. Self-writes and legacy
26
+ * `admin: true` actors (the plane above RBAC) are not checked, and neither are writes without an
27
+ * authenticated actor (internal server calls).
28
+ */
29
+ export declare const assertCanWriteTargetUser: ({ accessControl, actor, modelName, target, }: {
30
+ accessControl: unknown;
31
+ actor?: User;
32
+ modelName: string;
33
+ target: unknown;
34
+ }) => Promise<void>;
35
+ /**
36
+ * Requires `user:updateIdentity` for generic writes that change another user's
37
+ * {@link USER_IDENTITY_FIELDS} on the RBAC user model, so `user:update` alone cannot redirect a
38
+ * user's email, rebind their external login, or disable them. Keys whose value matches the
39
+ * target's current value do not count, so clients that echo the whole record still work. The
40
+ * write is rejected with 403, not stripped. Exempt, like {@link assertCanWriteTargetUser}:
41
+ * self-writes, writes without an actor (internal server calls), and legacy `admin: true` actors.
42
+ * Creates are not checked; this guards existing users only.
43
+ */
44
+ export declare const assertCanWriteUserIdentity: ({ accessControl, actor, body, modelName, target, }: {
45
+ accessControl: unknown;
46
+ actor?: User;
47
+ body: unknown;
48
+ modelName: string;
49
+ target: unknown;
50
+ }) => Promise<void>;
@@ -0,0 +1,156 @@
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.assertCanWriteUserIdentity = exports.assertCanWriteTargetUser = exports.isRbacUserModelName = exports.USER_UPDATE_IDENTITY_ACTION = exports.USER_IDENTITY_FIELDS = exports.isWriteKeyForField = void 0;
7
+ const isEqual_1 = __importDefault(require("lodash/isEqual"));
8
+ const errors_1 = require("../errors");
9
+ const logger_1 = require("../logger");
10
+ const permissionUtils_1 = require("./permissionUtils");
11
+ /**
12
+ * True when a write-body key addresses `field` itself or a path inside it. Mongoose `set`,
13
+ * `create`, and the document constructor treat a dotted key such as `roles.0` as a path into
14
+ * `roles`, so field filters must match the first path segment, not only the exact key.
15
+ */
16
+ const isWriteKeyForField = (key, field) => {
17
+ return key === field || key.startsWith(`${field}.`);
18
+ };
19
+ exports.isWriteKeyForField = isWriteKeyForField;
20
+ /**
21
+ * User fields that identify the account or control whether it can sign in. Changing them on
22
+ * another user through generic RBAC user-model writes needs `user:updateIdentity` on top of
23
+ * `user:update`; see {@link assertCanWriteUserIdentity}.
24
+ */
25
+ exports.USER_IDENTITY_FIELDS = [
26
+ "email",
27
+ "disabled",
28
+ "betterAuthId",
29
+ "githubId",
30
+ "emailVerified",
31
+ ];
32
+ /** RBAC action on the `user` resource that allows changing {@link USER_IDENTITY_FIELDS}. */
33
+ exports.USER_UPDATE_IDENTITY_ACTION = "updateIdentity";
34
+ const IDENTITY_PERMISSION_TITLE = `Missing user:${exports.USER_UPDATE_IDENTITY_ACTION} permission`;
35
+ /**
36
+ * True when RBAC is enabled and `modelName` names the user model: `"User"`, or the compiled
37
+ * name of the `userModel` passed to `createAccess`.
38
+ */
39
+ const isRbacUserModelName = (modelName, accessControl) => {
40
+ if (!accessControl) {
41
+ return false;
42
+ }
43
+ if (modelName === "User") {
44
+ return true;
45
+ }
46
+ const userModelName = accessControl.userModel?.modelName;
47
+ return typeof userModelName === "string" && userModelName === modelName;
48
+ };
49
+ exports.isRbacUserModelName = isRbacUserModelName;
50
+ /**
51
+ * Enforces RoleManager's target-privilege rule on generic writes to the RBAC user model: an actor
52
+ * may change or delete another user only when the actor holds every permission that user holds.
53
+ * REST, array subroutes, write instance actions, sync, and MCP all call this, so a `user:update`
54
+ * holder cannot take over or lock out a more privileged account. Self-writes and legacy
55
+ * `admin: true` actors (the plane above RBAC) are not checked, and neither are writes without an
56
+ * authenticated actor (internal server calls).
57
+ */
58
+ const assertCanWriteTargetUser = async ({ accessControl, actor, modelName, target, }) => {
59
+ if (!actor || actor.admin === true) {
60
+ return;
61
+ }
62
+ if (!(0, exports.isRbacUserModelName)(modelName, accessControl)) {
63
+ return;
64
+ }
65
+ const getPermissions = accessControl.getPermissions;
66
+ // Test doubles without a resolver have no permissions to compare.
67
+ if (typeof getPermissions !== "function") {
68
+ return;
69
+ }
70
+ const targetRecord = target;
71
+ const targetId = String(targetRecord?.id ?? targetRecord?._id ?? "");
72
+ if (!targetId || targetId === String(actor.id)) {
73
+ return;
74
+ }
75
+ const actorPermissions = await getPermissions({ user: actor });
76
+ const targetPermissions = await getPermissions({ user: target });
77
+ if ((0, permissionUtils_1.isPermissionSubset)(actorPermissions, targetPermissions)) {
78
+ return;
79
+ }
80
+ logger_1.logger.warn("RBAC privileged-user write denied", { actorId: actor.id, modelName, targetId });
81
+ throw new errors_1.APIError({
82
+ status: 403,
83
+ title: "Cannot modify a user with permissions you do not hold",
84
+ });
85
+ };
86
+ exports.assertCanWriteTargetUser = assertCanWriteTargetUser;
87
+ // Unset, null, empty, and false all mean "no value" for identity fields, so a form that echoes
88
+ // `disabled: false` or `githubId: null` back for a user without them is not a change.
89
+ const isEmptyIdentityValue = (value) => {
90
+ return value === undefined || value === null || value === "" || value === false;
91
+ };
92
+ const changedIdentityKeys = (body, target) => {
93
+ const current = (target ?? {});
94
+ return Object.keys(body).filter((key) => {
95
+ const field = exports.USER_IDENTITY_FIELDS.find((identityField) => (0, exports.isWriteKeyForField)(key, identityField));
96
+ if (!field) {
97
+ return false;
98
+ }
99
+ // A dotted path into an identity field always counts as a change.
100
+ if (key !== field) {
101
+ return true;
102
+ }
103
+ const next = body[key];
104
+ const previous = current[key];
105
+ if (isEmptyIdentityValue(next) && isEmptyIdentityValue(previous)) {
106
+ return false;
107
+ }
108
+ return !(0, isEqual_1.default)(next, previous);
109
+ });
110
+ };
111
+ /**
112
+ * Requires `user:updateIdentity` for generic writes that change another user's
113
+ * {@link USER_IDENTITY_FIELDS} on the RBAC user model, so `user:update` alone cannot redirect a
114
+ * user's email, rebind their external login, or disable them. Keys whose value matches the
115
+ * target's current value do not count, so clients that echo the whole record still work. The
116
+ * write is rejected with 403, not stripped. Exempt, like {@link assertCanWriteTargetUser}:
117
+ * self-writes, writes without an actor (internal server calls), and legacy `admin: true` actors.
118
+ * Creates are not checked; this guards existing users only.
119
+ */
120
+ const assertCanWriteUserIdentity = async ({ accessControl, actor, body, modelName, target, }) => {
121
+ if (!actor || actor.admin === true) {
122
+ return;
123
+ }
124
+ if (!(0, exports.isRbacUserModelName)(modelName, accessControl)) {
125
+ return;
126
+ }
127
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
128
+ return;
129
+ }
130
+ const targetRecord = target;
131
+ const targetId = String(targetRecord?.id ?? targetRecord?._id ?? "");
132
+ if (targetId && targetId === String(actor.id)) {
133
+ return;
134
+ }
135
+ const changed = changedIdentityKeys(body, target);
136
+ if (changed.length === 0) {
137
+ return;
138
+ }
139
+ const getPermissions = accessControl.getPermissions;
140
+ // Test doubles without a resolver have no permissions to compare.
141
+ if (typeof getPermissions !== "function") {
142
+ return;
143
+ }
144
+ const actorPermissions = await getPermissions({ user: actor });
145
+ if ((actorPermissions.user ?? []).includes(exports.USER_UPDATE_IDENTITY_ACTION)) {
146
+ return;
147
+ }
148
+ logger_1.logger.warn("RBAC user identity write denied", {
149
+ actorId: actor.id,
150
+ fields: changed,
151
+ modelName,
152
+ targetId,
153
+ });
154
+ throw new errors_1.APIError({ status: 403, title: IDENTITY_PERMISSION_TITLE });
155
+ };
156
+ exports.assertCanWriteUserIdentity = assertCanWriteUserIdentity;
@@ -100,7 +100,10 @@ export declare const emitPayloadToAuthorizedRoom: ({ io, room, eventName, entry,
100
100
  eventName: string;
101
101
  entry: AuthorizedEmitEntry;
102
102
  fullDocument: Record<string, unknown> | undefined;
103
- /** Build the per-socket payload; a throw drops the emission for that socket only. */
103
+ /**
104
+ * Build the per-socket payload; a throw drops the emission for that socket only, and
105
+ * returning SKIP_EMISSION sends nothing to it.
106
+ */
104
107
  buildPayload: (user: User | undefined) => Promise<unknown> | unknown;
105
108
  logDebug: (msg: string) => void;
106
109
  }) => Promise<void>;