@terreno/api 57.0.0 → 57.1.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 (175) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +8 -0
  2. package/dist/actions.d.ts +7 -2
  3. package/dist/actions.js +60 -25
  4. package/dist/adminModelRouter.d.ts +14 -0
  5. package/dist/adminModelRouter.js +199 -0
  6. package/dist/adminTypes.d.ts +156 -0
  7. package/dist/adminTypes.js +5 -0
  8. package/dist/api.d.ts +44 -3
  9. package/dist/api.js +74 -26
  10. package/dist/auth.d.ts +18 -1
  11. package/dist/auth.js +122 -20
  12. package/dist/consentApp.d.ts +2 -0
  13. package/dist/consentApp.js +98 -0
  14. package/dist/index.d.ts +22 -1
  15. package/dist/index.js +51 -7
  16. package/dist/mcp/auth.d.ts +11 -0
  17. package/dist/mcp/auth.js +133 -0
  18. package/dist/mcp/createMCPRequest.d.ts +16 -0
  19. package/dist/mcp/createMCPRequest.js +26 -0
  20. package/dist/mcp/handlers.d.ts +8 -0
  21. package/dist/mcp/handlers.js +793 -0
  22. package/dist/mcp/query.d.ts +32 -0
  23. package/dist/mcp/query.js +232 -0
  24. package/dist/mcp/registry.d.ts +21 -0
  25. package/dist/mcp/registry.js +54 -0
  26. package/dist/mcp/schemaGenerator.d.ts +14 -0
  27. package/dist/mcp/schemaGenerator.js +379 -0
  28. package/dist/mcp/server.d.ts +8 -0
  29. package/dist/mcp/server.js +133 -0
  30. package/dist/mcp/toolGenerator.d.ts +14 -0
  31. package/dist/mcp/toolGenerator.js +246 -0
  32. package/dist/mcp/types.d.ts +85 -0
  33. package/dist/mcp/types.js +2 -0
  34. package/dist/openApi.d.ts +1 -1
  35. package/dist/openApi.js +26 -8
  36. package/dist/permissions.js +15 -15
  37. package/dist/rbac/access.d.ts +3 -0
  38. package/dist/rbac/access.js +294 -0
  39. package/dist/rbac/auditModel.d.ts +31 -0
  40. package/dist/rbac/auditModel.js +112 -0
  41. package/dist/rbac/backfillAdmins.d.ts +18 -0
  42. package/dist/rbac/backfillAdmins.js +139 -0
  43. package/dist/rbac/fieldViews.d.ts +3 -0
  44. package/dist/rbac/fieldViews.js +201 -0
  45. package/dist/rbac/middleware.d.ts +21 -0
  46. package/dist/rbac/middleware.js +108 -0
  47. package/dist/rbac/modelRouterAccess.d.ts +42 -0
  48. package/dist/rbac/modelRouterAccess.js +388 -0
  49. package/dist/rbac/permissionUtils.d.ts +8 -0
  50. package/dist/rbac/permissionUtils.js +209 -0
  51. package/dist/rbac/realtimeAccess.d.ts +18 -0
  52. package/dist/rbac/realtimeAccess.js +173 -0
  53. package/dist/rbac/resolve.d.ts +28 -0
  54. package/dist/rbac/resolve.js +387 -0
  55. package/dist/rbac/roleManager.d.ts +20 -0
  56. package/dist/rbac/roleManager.js +741 -0
  57. package/dist/rbac/roleModel.d.ts +42 -0
  58. package/dist/rbac/roleModel.js +267 -0
  59. package/dist/rbac/routes.d.ts +9 -0
  60. package/dist/rbac/routes.js +211 -0
  61. package/dist/rbac/scopes.d.ts +15 -0
  62. package/dist/rbac/scopes.js +155 -0
  63. package/dist/rbac/statements.d.ts +20 -0
  64. package/dist/rbac/statements.js +115 -0
  65. package/dist/rbac/types.d.ts +202 -0
  66. package/dist/rbac/types.js +2 -0
  67. package/dist/rbac/userPlugin.d.ts +12 -0
  68. package/dist/rbac/userPlugin.js +41 -0
  69. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  70. package/dist/realtime/changeStreamWatcher.js +48 -39
  71. package/dist/realtime/realtimeApp.js +4 -8
  72. package/dist/realtime/registry.d.ts +5 -0
  73. package/dist/realtime/registry.js +13 -1
  74. package/dist/scrubAdminFields.d.ts +17 -0
  75. package/dist/scrubAdminFields.js +192 -0
  76. package/dist/sync/executors.d.ts +1 -1
  77. package/dist/sync/executors.js +63 -40
  78. package/dist/sync/loadHarness.js +4 -5
  79. package/dist/sync/registry.d.ts +5 -0
  80. package/dist/sync/registry.js +13 -1
  81. package/dist/sync/routes.js +41 -36
  82. package/dist/sync/serialize.js +5 -6
  83. package/dist/terrenoApp.d.ts +18 -0
  84. package/dist/terrenoApp.js +46 -3
  85. package/dist/terrenoPlugin.d.ts +8 -1
  86. package/dist/tests/createTestData.js +8 -0
  87. package/dist/tests/models.d.ts +1 -0
  88. package/dist/tests/models.js +5 -0
  89. package/dist/tests/testHelper.js +1 -2
  90. package/dist/transformers.js +16 -1
  91. package/package.json +16 -12
  92. package/src/__snapshots__/openApi.test.ts.snap +192 -0
  93. package/src/actions.test.ts +194 -1
  94. package/src/actions.ts +65 -8
  95. package/src/adminModelRouter.ts +154 -0
  96. package/src/adminTypes.ts +183 -0
  97. package/src/api.test.ts +66 -1
  98. package/src/api.ts +131 -12
  99. package/src/auth.test.ts +135 -1
  100. package/src/auth.ts +81 -3
  101. package/src/consentApp.test.ts +24 -0
  102. package/src/consentApp.ts +100 -0
  103. package/src/index.ts +56 -0
  104. package/src/mcp/auth.test.ts +197 -0
  105. package/src/mcp/auth.ts +100 -0
  106. package/src/mcp/createMCPRequest.test.ts +47 -0
  107. package/src/mcp/createMCPRequest.ts +32 -0
  108. package/src/mcp/customTools.test.ts +54 -0
  109. package/src/mcp/handlers.ts +639 -0
  110. package/src/mcp/integration.test.ts +1493 -0
  111. package/src/mcp/query.test.ts +172 -0
  112. package/src/mcp/query.ts +179 -0
  113. package/src/mcp/registry.ts +70 -0
  114. package/src/mcp/schemaGenerator.test.ts +182 -0
  115. package/src/mcp/schemaGenerator.ts +354 -0
  116. package/src/mcp/server.test.ts +226 -0
  117. package/src/mcp/server.ts +86 -0
  118. package/src/mcp/toolGenerator.test.ts +284 -0
  119. package/src/mcp/toolGenerator.ts +199 -0
  120. package/src/mcp/types.ts +95 -0
  121. package/src/openApi.test.ts +107 -0
  122. package/src/openApi.ts +32 -1
  123. package/src/permissions.ts +3 -2
  124. package/src/rbac/access.test.ts +357 -0
  125. package/src/rbac/access.ts +201 -0
  126. package/src/rbac/auditModel.ts +103 -0
  127. package/src/rbac/backfillAdmins.ts +54 -0
  128. package/src/rbac/fieldViews.test.ts +39 -0
  129. package/src/rbac/fieldViews.ts +122 -0
  130. package/src/rbac/middleware.ts +55 -0
  131. package/src/rbac/modelRouterAccess.test.ts +336 -0
  132. package/src/rbac/modelRouterAccess.ts +331 -0
  133. package/src/rbac/permissionUtils.test.ts +112 -0
  134. package/src/rbac/permissionUtils.ts +83 -0
  135. package/src/rbac/realtimeAccess.test.ts +242 -0
  136. package/src/rbac/realtimeAccess.ts +138 -0
  137. package/src/rbac/resolve.test.ts +358 -0
  138. package/src/rbac/resolve.ts +285 -0
  139. package/src/rbac/roleManager.test.ts +915 -0
  140. package/src/rbac/roleManager.ts +440 -0
  141. package/src/rbac/roleModel.test.ts +114 -0
  142. package/src/rbac/roleModel.ts +196 -0
  143. package/src/rbac/routes.ts +170 -0
  144. package/src/rbac/scopes.test.ts +105 -0
  145. package/src/rbac/scopes.ts +81 -0
  146. package/src/rbac/statements.test.ts +65 -0
  147. package/src/rbac/statements.ts +62 -0
  148. package/src/rbac/types.ts +198 -0
  149. package/src/rbac/userPlugin.test.ts +55 -0
  150. package/src/rbac/userPlugin.ts +25 -0
  151. package/src/realtime/changeStreamWatcher.ts +20 -15
  152. package/src/realtime/realtime.test.ts +25 -1
  153. package/src/realtime/realtimeApp.ts +2 -5
  154. package/src/realtime/registry.ts +15 -0
  155. package/src/scrubAdminFields.test.ts +113 -0
  156. package/src/scrubAdminFields.ts +158 -0
  157. package/src/sync/executors.ts +31 -1
  158. package/src/sync/loadHarness.ts +8 -7
  159. package/src/sync/models.test.ts +262 -0
  160. package/src/sync/registry.ts +15 -0
  161. package/src/sync/routes.ts +25 -11
  162. package/src/sync/scripts/compactTombstones.test.ts +4 -6
  163. package/src/sync/serialize.ts +17 -9
  164. package/src/sync/sync.test.ts +52 -0
  165. package/src/sync/syncRoutes.test.ts +5 -2
  166. package/src/sync/syncSocket.test.ts +28 -0
  167. package/src/terrenoApp.test.ts +100 -0
  168. package/src/terrenoApp.ts +65 -3
  169. package/src/terrenoPlugin.ts +10 -1
  170. package/src/tests/bunSetup.ts +2 -0
  171. package/src/tests/createTestData.ts +5 -1
  172. package/src/tests/models.ts +6 -0
  173. package/src/tests/testHelper.ts +1 -3
  174. package/src/transformers.test.ts +12 -0
  175. package/src/transformers.ts +7 -1
@@ -0,0 +1,198 @@
1
+ import type {createAccessControl} from "better-auth/plugins/access";
2
+ import type express from "express";
3
+ import type {RequestHandler} from "express";
4
+ import type {Connection} from "mongoose";
5
+ import type {RESTMethod} from "../api";
6
+ import type {User, UserModel} from "../auth";
7
+ import type {PermissionMethod} from "../permissions";
8
+ import type {RbacAuditWrite} from "./auditModel";
9
+ import type {RbacRoleDocument, RoleDefinition} from "./roleModel";
10
+ import type {PermissionSet, Statements} from "./statements";
11
+
12
+ /**
13
+ * Non-generic TerrenoAccess for runtime wiring (modelRouter, rbacRouter, TerrenoApp).
14
+ * `queryFilter` / `fieldMask` take `resource: string` so a concrete
15
+ * `TerrenoAccess<AppStatements>` remains assignable (function parameters are
16
+ * contravariant; a keyof-S union would not accept `string`).
17
+ */
18
+ export type AnyTerrenoAccess = TerrenoAccess<Statements>;
19
+
20
+ /** @deprecated Prefer typed TerrenoAccess; AnyTerrenoAccess uses TerrenoAccess<any>. */
21
+ export type LoosePermissionRequest = {
22
+ [resource: string]: string[] | undefined;
23
+ };
24
+
25
+ export interface ModelRouterAccessOptions {
26
+ resource: string;
27
+ actions?: Partial<Record<RESTMethod, string | null>>;
28
+ scope?: ResourceScope;
29
+ also?: Partial<Record<RESTMethod, PermissionMethod<unknown>[]>>;
30
+ allowAnonymous?: boolean;
31
+ }
32
+
33
+ export type {Statements};
34
+
35
+ export type PermissionRequest<S extends Statements> = {
36
+ [K in keyof S]?: S[K][number][];
37
+ };
38
+
39
+ export interface AccessResult {
40
+ allowed: boolean;
41
+ deniedBy?: "role" | "scope" | "source";
42
+ reason?: string;
43
+ }
44
+
45
+ export interface AccessCheckArgs<S extends Statements> {
46
+ user?: User;
47
+ permissions: PermissionRequest<S>;
48
+ doc?: unknown;
49
+ context?: Record<string, unknown>;
50
+ }
51
+
52
+ export interface FieldMask {
53
+ read: string[] | "*";
54
+ write: string[] | "*";
55
+ omit?: string[];
56
+ }
57
+
58
+ export interface RoleDiff {
59
+ gained: PermissionSet;
60
+ lost: PermissionSet;
61
+ affectedUserCount: number;
62
+ }
63
+
64
+ export interface UserPermissionDiff {
65
+ gained: PermissionSet;
66
+ lost: PermissionSet;
67
+ resulting: PermissionSet;
68
+ }
69
+
70
+ export interface RoleInput {
71
+ name: string;
72
+ displayName: string;
73
+ description?: string | null;
74
+ permissions: PermissionSet;
75
+ excludesRoles?: string[];
76
+ isLocked?: boolean;
77
+ isSealed?: boolean;
78
+ }
79
+
80
+ export interface RoleManager {
81
+ seedDefaults: () => Promise<void>;
82
+ list: () => Promise<RbacRoleDocument[]>;
83
+ create: (args: {actor: User; role: RoleInput}) => Promise<RbacRoleDocument>;
84
+ update: (args: {
85
+ actor: User;
86
+ roleName: string;
87
+ changes: Partial<RoleInput>;
88
+ }) => Promise<RbacRoleDocument>;
89
+ remove: (args: {actor: User; roleName: string}) => Promise<void>;
90
+ assign: (args: {actor: User; userId: string; roleNames: string[]}) => Promise<void>;
91
+ unassign: (args: {actor: User; userId: string; roleNames: string[]}) => Promise<void>;
92
+ assertCanModifyUser: (args: {actor: User; userId: string}) => Promise<void>;
93
+ previewRoleChange: (args: {roleName: string; permissions: PermissionSet}) => Promise<RoleDiff>;
94
+ previewAssignment: (args: {
95
+ actor: User;
96
+ userId: string;
97
+ roleNames: string[];
98
+ }) => Promise<UserPermissionDiff>;
99
+ }
100
+
101
+ export type StaleOnFailurePolicy = "deny" | "use-stale" | "use-stale-bounded";
102
+
103
+ export interface PermissionSourceGrants {
104
+ roles?: string[];
105
+ permissions?: PermissionSet;
106
+ deny?: PermissionSet;
107
+ }
108
+
109
+ export interface PermissionSource {
110
+ name: string;
111
+ ttlMs?: number;
112
+ staleOnFailure?: StaleOnFailurePolicy;
113
+ staleMaxAgeMs?: number;
114
+ getGrants: (args: {user: User}) => Promise<PermissionSourceGrants | null>;
115
+ }
116
+
117
+ export interface ResourceScope<TDoc = unknown> {
118
+ check?: (args: ScopeArgs<TDoc>) => boolean | PermissionSet | Promise<boolean | PermissionSet>;
119
+ filter?: (args: ScopeArgs<TDoc>) => Promise<Record<string, unknown> | null>;
120
+ }
121
+
122
+ export interface ScopeArgs<TDoc> {
123
+ user: User;
124
+ action: string;
125
+ doc?: TDoc;
126
+ context?: Record<string, unknown>;
127
+ }
128
+
129
+ export type ResourceScopes<_S extends Statements> = {
130
+ [key: string]: ResourceScope;
131
+ };
132
+
133
+ export interface ResourceFieldViews<_S extends Statements> {
134
+ [resource: string]: {
135
+ views: Record<string, FieldMask>;
136
+ select: (args: {
137
+ user?: User;
138
+ doc?: unknown;
139
+ permissions: PermissionSet;
140
+ phase: "read" | "write" | "create";
141
+ }) => string | FieldMask | Promise<string | FieldMask>;
142
+ createView?: string | FieldMask | "deny";
143
+ };
144
+ }
145
+
146
+ export type {PermissionSet, RbacAuditWrite};
147
+
148
+ export type RbacAuditSink = (record: RbacAuditWrite) => void | Promise<void>;
149
+
150
+ export interface AccessOptions<S extends Statements> {
151
+ connection: Connection;
152
+ statements: S;
153
+ userModel?: UserModel;
154
+ defaultRoles?: RoleDefinition[];
155
+ scopes?: ResourceScopes<S>;
156
+ fieldViews?: ResourceFieldViews<S>;
157
+ sources?: PermissionSource[];
158
+ readActions?: readonly string[];
159
+ cacheTtlMs?: number;
160
+ resolvePermissions?: (args: {user: User}) => Promise<PermissionSet | null>;
161
+ statementDescriptions?: Record<string, Record<string, string>>;
162
+ /**
163
+ * Extra destinations for RoleManager audit records (e.g. a consuming-app audit log).
164
+ * The built-in `RbacAudit` collection is still written unless `persistAudit` is false.
165
+ */
166
+ auditSink?: RbacAuditSink | RbacAuditSink[];
167
+ /**
168
+ * When false, skip the built-in `RbacAudit` collection. At least one `auditSink` is then
169
+ * required so role mutations cannot go unaudited.
170
+ */
171
+ persistAudit?: boolean;
172
+ }
173
+
174
+ export interface TerrenoAccess<S extends Statements> {
175
+ readonly statements: S;
176
+ readonly ac: ReturnType<typeof createAccessControl<S>>;
177
+ can: (args: AccessCheckArgs<S>) => Promise<AccessResult>;
178
+ getPermissions: (args: {user: User}) => Promise<PermissionSet>;
179
+ queryFilter: (args: {
180
+ user?: User;
181
+ resource: string;
182
+ action: string;
183
+ context?: Record<string, unknown>;
184
+ }) => Promise<Record<string, unknown> | null>;
185
+ fieldMask: (args: {
186
+ user?: User;
187
+ resource: string;
188
+ doc?: unknown;
189
+ phase?: "read" | "write" | "create";
190
+ }) => Promise<FieldMask>;
191
+ middleware: (
192
+ permissions: PermissionRequest<S>,
193
+ options?: {getDoc?: (req: express.Request) => Promise<unknown>}
194
+ ) => RequestHandler;
195
+ permission: (permissions: PermissionRequest<S>) => PermissionMethod<unknown>;
196
+ roles: RoleManager;
197
+ invalidateCache: (args?: {userId?: string}) => void;
198
+ }
@@ -0,0 +1,55 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import {Schema} from "mongoose";
3
+
4
+ import {rbacUserPlugin} from "./userPlugin";
5
+
6
+ interface TestUser {
7
+ email: string;
8
+ roles: string[];
9
+ }
10
+
11
+ const buildSchema = (): Schema<TestUser> =>
12
+ new Schema<TestUser>({
13
+ email: {description: "Email", type: String},
14
+ });
15
+
16
+ const resolveDefault = (schema: Schema<TestUser>): unknown => {
17
+ const rolesPath = schema.path("roles") as unknown as {options: {default: () => unknown}};
18
+ return rolesPath.options.default();
19
+ };
20
+
21
+ describe("rbacUserPlugin", () => {
22
+ it("adds roles field with default empty array", () => {
23
+ const schema = buildSchema();
24
+ rbacUserPlugin(schema);
25
+
26
+ expect(schema.path("roles")).toBeDefined();
27
+ expect(resolveDefault(schema)).toEqual([]);
28
+ });
29
+
30
+ it("assigns configured default roles to new users", () => {
31
+ const schema = buildSchema();
32
+ rbacUserPlugin(schema, {defaultRoles: ["member", "todoUser"]});
33
+
34
+ expect(resolveDefault(schema)).toEqual(["member", "todoUser"]);
35
+ });
36
+
37
+ it("gives each document its own default roles array", () => {
38
+ const schema = buildSchema();
39
+ rbacUserPlugin(schema, {defaultRoles: ["member"]});
40
+
41
+ const first = resolveDefault(schema) as string[];
42
+ first.push("mutated");
43
+
44
+ expect(resolveDefault(schema)).toEqual(["member"]);
45
+ });
46
+
47
+ it("ignores later mutations of the caller's defaultRoles array", () => {
48
+ const schema = buildSchema();
49
+ const defaultRoles = ["member"];
50
+ rbacUserPlugin(schema, {defaultRoles});
51
+ defaultRoles.push("sneaky");
52
+
53
+ expect(resolveDefault(schema)).toEqual(["member"]);
54
+ });
55
+ });
@@ -0,0 +1,25 @@
1
+ import type {Schema} from "mongoose";
2
+
3
+ export interface RbacUser {
4
+ roles: string[];
5
+ }
6
+
7
+ export interface RbacUserPluginOptions {
8
+ /**
9
+ * Role names assigned to newly created users. Apps that gate resources through
10
+ * `access` need a baseline role here, otherwise signups start with no permissions.
11
+ */
12
+ defaultRoles?: string[];
13
+ }
14
+
15
+ export const rbacUserPlugin = (schema: Schema, options?: RbacUserPluginOptions): void => {
16
+ const defaultRoles = [...(options?.defaultRoles ?? [])];
17
+ schema.add({
18
+ roles: {
19
+ default: () => [...defaultRoles],
20
+ description: "RBAC role names assigned to this user",
21
+ index: true,
22
+ type: [String],
23
+ },
24
+ });
25
+ };
@@ -8,7 +8,8 @@ import type {Server, Socket} from "socket.io";
8
8
  import type {User} from "../auth";
9
9
  import {APIError} from "../errors";
10
10
  import {logger} from "../logger";
11
- import {checkPermissions, type PermissionMethod} from "../permissions";
11
+ import type {PermissionMethod} from "../permissions";
12
+ import {canReadDocumentRealtime, maskRealtimeDocument} from "../rbac/realtimeAccess";
12
13
  import {computeStableFrontier, SyncScopeMove} from "../sync/models";
13
14
  import {findSyncEntryByCollectionName, type SyncRegistryEntry} from "../sync/registry";
14
15
  import {serializeSyncPayload} from "../sync/serialize";
@@ -18,7 +19,7 @@ import type {SyncDelta, SyncMutationOperation, SyncResyncHint} from "../sync/typ
18
19
  import {matchesQuery} from "./queryMatcher";
19
20
  import {getQuerySubscriptionsForCollection} from "./queryStore";
20
21
  import {findRegistryEntryByCollection, type RealtimeRegistryEntry} from "./registry";
21
- import {getSocketUser, type SocketWithDecodedToken} from "./socketUser";
22
+ import {awaitSocketFullUser, type SocketWithDecodedToken} from "./socketUser";
22
23
  import type {ChangeStreamConfig, RealtimeEvent} from "./types";
23
24
 
24
25
  /**
@@ -199,9 +200,7 @@ const canReadDocument = async (
199
200
  entry: AuthorizedEmitEntry,
200
201
  user?: User,
201
202
  doc?: Record<string, unknown>
202
- ): Promise<boolean> => {
203
- return checkPermissions("read", entry.options.permissions.read, user, doc);
204
- };
203
+ ): Promise<boolean> => canReadDocumentRealtime(entry, user, doc);
205
204
 
206
205
  /**
207
206
  * Determine which Socket.io rooms to emit to based on the room strategy.
@@ -297,14 +296,14 @@ export const serializeDoc = async (
297
296
  const restMethod = method === "delete" ? "read" : method;
298
297
  // Synthesize the minimal request shape responseHandlers commonly inspect.
299
298
  const syntheticReq = {params: {}, query: {}, user} as unknown as express.Request;
300
- return ensureApiId(
301
- await responseHandler(
302
- doc as unknown as mongoose.Document<unknown, unknown, unknown>,
303
- restMethod,
304
- syntheticReq,
305
- entry.options
306
- )
299
+ const serialized = await responseHandler(
300
+ doc as unknown as mongoose.Document<unknown, unknown, unknown>,
301
+ restMethod,
302
+ syntheticReq,
303
+ entry.options
307
304
  );
305
+ const masked = await maskRealtimeDocument(entry, user, serialized, restMethod);
306
+ return ensureApiId(masked);
308
307
  } catch (error) {
309
308
  logger.error(
310
309
  `[realtime] modelRouter responseHandler threw during realtime serialization for ` +
@@ -314,9 +313,15 @@ export const serializeDoc = async (
314
313
  }
315
314
  }
316
315
 
317
- return ensureApiId(
318
- typeof doc.toJSON === "function" ? (doc as {toJSON: () => unknown}).toJSON() : doc
316
+ const fallback =
317
+ typeof doc.toJSON === "function" ? (doc as {toJSON: () => unknown}).toJSON() : doc;
318
+ const maskedFallback = await maskRealtimeDocument(
319
+ entry,
320
+ user,
321
+ fallback,
322
+ method === "delete" ? "read" : method
319
323
  );
324
+ return ensureApiId(maskedFallback);
320
325
  };
321
326
 
322
327
  /**
@@ -347,7 +352,7 @@ export const emitPayloadToAuthorizedRoom = async ({
347
352
  }): Promise<void> => {
348
353
  const sockets = getSocketsInRoom(io, room);
349
354
  for (const socket of sockets) {
350
- const user = getSocketUser(socket);
355
+ const user = await awaitSocketFullUser(socket);
351
356
  try {
352
357
  // Hard deletes have no document context; use an empty object so object-scoped
353
358
  // permission helpers fail closed instead of treating the check as preflight.
@@ -14,6 +14,8 @@ import {afterEach, beforeAll, beforeEach, describe, expect, it, mock} from "bun:
14
14
  import express from "express";
15
15
  import mongoose from "mongoose";
16
16
 
17
+ import type {ModelRouterOptions} from "../api";
18
+
17
19
  import {
18
20
  emitToAuthorizedRoom,
19
21
  emitToDocumentAndQueryRooms,
@@ -48,6 +50,7 @@ import {
48
50
  getRealtimeRegistry,
49
51
  type RealtimeRegistryEntry,
50
52
  registerRealtime,
53
+ updateRealtimeRegistryOptions,
51
54
  } from "./registry";
52
55
  import type {RealtimeEvent} from "./types";
53
56
 
@@ -586,6 +589,24 @@ describe("realtimeRegistry", () => {
586
589
  expect(getRealtimeRegistry()).toHaveLength(0);
587
590
  });
588
591
  });
592
+
593
+ describe("updateRealtimeRegistryOptions", () => {
594
+ it("replaces options on an existing entry by route path", () => {
595
+ registerRealtime(makeEntry({routePath: "/todos"}));
596
+ const updatedOptions = {permissions: {list: []}} as ModelRouterOptions<unknown>;
597
+ updateRealtimeRegistryOptions("/todos", updatedOptions);
598
+
599
+ expect(getRealtimeRegistry()[0]?.options).toBe(updatedOptions);
600
+ });
601
+
602
+ it("no-ops when the route path is not registered", () => {
603
+ registerRealtime(makeEntry({routePath: "/todos"}));
604
+ const originalOptions = getRealtimeRegistry()[0]?.options;
605
+ updateRealtimeRegistryOptions("/missing", {permissions: {}} as ModelRouterOptions<unknown>);
606
+
607
+ expect(getRealtimeRegistry()[0]?.options).toBe(originalOptions);
608
+ });
609
+ });
589
610
  });
590
611
 
591
612
  // ─────────────────────────────────────────────────────────────────────────────
@@ -1865,12 +1886,15 @@ describe("emitToDocumentAndQueryRooms", () => {
1865
1886
  ...modelEntry,
1866
1887
  options: {
1867
1888
  permissions: {
1868
- ...modelEntry.options.permissions,
1889
+ create: [() => true],
1890
+ delete: [() => true],
1891
+ list: [() => true],
1869
1892
  read: [
1870
1893
  (_method, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
1871
1894
  user?.admin === true ||
1872
1895
  user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
1873
1896
  ],
1897
+ update: [() => true],
1874
1898
  },
1875
1899
  },
1876
1900
  };
@@ -8,7 +8,7 @@ import {Server, type Socket} from "socket.io";
8
8
  import type {User} from "../auth";
9
9
  import {APIError} from "../errors";
10
10
  import {logger} from "../logger";
11
- import {checkPermissions} from "../permissions";
11
+ import {canSubscribeRealtime} from "../rbac/realtimeAccess";
12
12
  import {warnOnSyncScopesWithoutUserModel} from "../sync/registry";
13
13
  import {installSyncSocketHandlers} from "../sync/socketHandlers";
14
14
  import {getSyncAppOptions} from "../sync/syncApp";
@@ -77,10 +77,7 @@ const canSubscribe = async (
77
77
  entry: RealtimeRegistryEntry,
78
78
  method: "list" | "read",
79
79
  user?: User
80
- ): Promise<boolean> => {
81
- const permissions = entry.options.permissions[method];
82
- return checkPermissions(method, permissions, user);
83
- };
80
+ ): Promise<boolean> => canSubscribeRealtime(entry, method, user);
84
81
 
85
82
  const getAuthorizedQuery = async (
86
83
  entry: RealtimeRegistryEntry,
@@ -30,6 +30,21 @@ export const registerRealtime = (entry: RealtimeRegistryEntry): void => {
30
30
  realtimeRegistry.push(entry);
31
31
  };
32
32
 
33
+ /**
34
+ * Replace options on an existing registry entry (e.g. after TerrenoApp injects accessControl).
35
+ * Matches by routePath; no-op if the route was never registered.
36
+ */
37
+ export const updateRealtimeRegistryOptions = (
38
+ routePath: string,
39
+ options: ModelRouterOptions<unknown>
40
+ ): void => {
41
+ const existing = realtimeRegistry.find((entry) => entry.routePath === routePath);
42
+ if (!existing) {
43
+ return;
44
+ }
45
+ existing.options = options;
46
+ };
47
+
33
48
  /**
34
49
  * Get all registered real-time models.
35
50
  */
@@ -0,0 +1,113 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import {model, Schema} from "mongoose";
3
+
4
+ import type {AdminConfig} from "./adminTypes";
5
+ import {scrubAdminFields, stripAdminBodyFields} from "./scrubAdminFields";
6
+
7
+ const userSchema = new Schema({
8
+ email: String,
9
+ hash: String,
10
+ name: String,
11
+ salt: String,
12
+ });
13
+
14
+ model("ScrubUser", userSchema);
15
+
16
+ const todoSchema = new Schema({
17
+ ownerId: {ref: "ScrubUser", type: Schema.Types.ObjectId},
18
+ title: String,
19
+ });
20
+
21
+ const Todo = model("ScrubTodo", todoSchema);
22
+
23
+ describe("scrubAdminFields", () => {
24
+ const todoAdmin: AdminConfig = {
25
+ displayName: "Todos",
26
+ excludeFields: ["secret"],
27
+ hiddenFields: ["internalNote"],
28
+ listFields: ["title"],
29
+ };
30
+
31
+ const userAdmin: AdminConfig = {
32
+ displayName: "Users",
33
+ excludeFields: ["hash", "salt"],
34
+ listFields: ["email", "name"],
35
+ };
36
+
37
+ it("strips exclude and hidden fields at the top level", () => {
38
+ const result = scrubAdminFields(
39
+ {internalNote: "n", secret: "x", title: "Buy milk"},
40
+ {admin: todoAdmin}
41
+ );
42
+ expect(result).toEqual({title: "Buy milk"});
43
+ });
44
+
45
+ it("scrubs nested arrays", () => {
46
+ const result = scrubAdminFields(
47
+ [
48
+ {secret: "1", title: "a"},
49
+ {internalNote: "2", title: "b"},
50
+ ],
51
+ {admin: todoAdmin}
52
+ );
53
+ expect(result).toEqual([{title: "a"}, {title: "b"}]);
54
+ });
55
+
56
+ it("scrubs populated refs using the referenced model admin config", () => {
57
+ const populated = {
58
+ ownerId: {
59
+ _id: "507f1f77bcf86cd799439011",
60
+ email: "a@b.com",
61
+ hash: "hidden",
62
+ name: "Alice",
63
+ salt: "hidden",
64
+ },
65
+ title: "Task",
66
+ };
67
+
68
+ const result = scrubAdminFields(populated, {
69
+ admin: todoAdmin,
70
+ allModelAdmins: {ScrubUser: userAdmin},
71
+ schema: Todo.schema,
72
+ }) as {ownerId: Record<string, unknown>; title: string};
73
+
74
+ expect(result.title).toBe("Task");
75
+ expect(result.ownerId).toEqual({
76
+ _id: "507f1f77bcf86cd799439011",
77
+ email: "a@b.com",
78
+ name: "Alice",
79
+ });
80
+ });
81
+
82
+ it("returns unconfigured populated docs unchanged", () => {
83
+ const populated = {
84
+ ownerId: {_id: "507f1f77bcf86cd799439011", hash: "keep", name: "Alice"},
85
+ title: "Task",
86
+ };
87
+
88
+ const result = scrubAdminFields(populated, {
89
+ admin: todoAdmin,
90
+ schema: Todo.schema,
91
+ }) as {ownerId: Record<string, unknown>};
92
+
93
+ expect(result.ownerId.hash).toBe("keep");
94
+ });
95
+ });
96
+
97
+ describe("stripAdminBodyFields", () => {
98
+ const admin: AdminConfig = {
99
+ displayName: "Todos",
100
+ excludeFields: ["role"],
101
+ hiddenFields: ["internal"],
102
+ listFields: ["title"],
103
+ readonlyFields: ["slug"],
104
+ };
105
+
106
+ it("removes readonly, exclude, and hidden keys from objects", () => {
107
+ const result = stripAdminBodyFields(
108
+ {internal: "n", role: "admin", slug: "fixed", title: "x"},
109
+ admin
110
+ );
111
+ expect(result).toEqual({title: "x"});
112
+ });
113
+ });