@terreno/api 57.2.0 → 57.3.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 (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -0,0 +1,233 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import type express from "express";
3
+ import mongoose, {type Model, model, Schema} from "mongoose";
4
+ import type TestAgent from "supertest/lib/agent";
5
+
6
+ import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "../auth";
7
+ import {apiErrorMiddleware} from "../errors";
8
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "../tests";
9
+ import {createAccess} from "./access";
10
+ import {rbacRouter} from "./routes";
11
+ import {type PermissionSet, terrenoStatements} from "./statements";
12
+ import type {AnyTerrenoAccess} from "./types";
13
+
14
+ interface RouteUser {
15
+ admin: boolean;
16
+ email: string;
17
+ roles: string[];
18
+ }
19
+
20
+ const appStatements = {
21
+ ...terrenoStatements,
22
+ todo: ["create", "read", "update", "delete", "list"],
23
+ } as const;
24
+
25
+ const allPermissions: PermissionSet = Object.fromEntries(
26
+ Object.entries(appStatements).map(([resource, actions]) => [resource, [...actions]])
27
+ );
28
+
29
+ const getRouteUserModel = (): Model<RouteUser> => {
30
+ const modelName = "RbacRoutesTestUser";
31
+ if (mongoose.models[modelName]) {
32
+ return mongoose.models[modelName] as Model<RouteUser>;
33
+ }
34
+
35
+ const schema = new Schema<RouteUser>({
36
+ admin: {default: false, description: "Whether the user is an administrator", type: Boolean},
37
+ email: {description: "The user's email address", required: true, type: String},
38
+ roles: {default: [], description: "The user's RBAC roles", type: [String]},
39
+ });
40
+
41
+ return model<RouteUser>(modelName, schema);
42
+ };
43
+
44
+ const authUserModel = UserModel as unknown as AuthUserModel;
45
+
46
+ const createRequestMutationAccess = (
47
+ access: AnyTerrenoAccess,
48
+ mutate: (request: express.Request) => void
49
+ ): AnyTerrenoAccess => ({
50
+ ...access,
51
+ middleware: (permissions, options) => {
52
+ const accessMiddleware = access.middleware(permissions, options);
53
+ return (request, response, next) => {
54
+ accessMiddleware(request, response, (error?: unknown) => {
55
+ if (error) {
56
+ next(error);
57
+ return;
58
+ }
59
+ mutate(request);
60
+ next();
61
+ });
62
+ };
63
+ },
64
+ });
65
+
66
+ describe("rbacRouter", () => {
67
+ let app: express.Application;
68
+ let adminAgent: TestAgent;
69
+ let routeUserModel: Model<RouteUser>;
70
+ let targetUserId: string;
71
+
72
+ beforeEach(async () => {
73
+ await setupDb();
74
+ routeUserModel = getRouteUserModel();
75
+ await routeUserModel.deleteMany({});
76
+ const targetUser = await routeUserModel.create({
77
+ email: "target@example.com",
78
+ roles: ["member"],
79
+ });
80
+ targetUserId = targetUser.id;
81
+
82
+ const access = createAccess({
83
+ connection: mongoose.connection,
84
+ resolvePermissions: async ({user}) => (user.admin ? allPermissions : {}),
85
+ statements: appStatements,
86
+ userModel: routeUserModel as unknown as AuthUserModel,
87
+ });
88
+ await access.roles.seedDefaults();
89
+
90
+ app = getBaseServer();
91
+ setupAuth(app, authUserModel);
92
+ addAuthRoutes(app, authUserModel);
93
+ rbacRouter({
94
+ access,
95
+ basePath: "/rbac",
96
+ userModel: routeUserModel as unknown as AuthUserModel,
97
+ }).register(app);
98
+ rbacRouter({
99
+ access: createRequestMutationAccess(access, (request) => {
100
+ request.user = undefined;
101
+ }),
102
+ basePath: "/rbac-unauthorized",
103
+ userModel: routeUserModel as unknown as AuthUserModel,
104
+ }).register(app);
105
+ rbacRouter({
106
+ access: createRequestMutationAccess(access, (request) => {
107
+ Reflect.deleteProperty(request.params, "id");
108
+ Reflect.deleteProperty(request.params, "name");
109
+ }),
110
+ basePath: "/rbac-invalid-params",
111
+ userModel: routeUserModel as unknown as AuthUserModel,
112
+ }).register(app);
113
+ app.use(apiErrorMiddleware);
114
+
115
+ adminAgent = await authAsUser(app, "admin");
116
+ });
117
+
118
+ it("serves statements and supports role and user operations", async () => {
119
+ const statementsResponse = await adminAgent.get("/rbac/statements").expect(200);
120
+ expect(statementsResponse.body.data.statements.rbac).toEqual([
121
+ "read",
122
+ "manageRoles",
123
+ "assignRoles",
124
+ ]);
125
+
126
+ const rolesResponse = await adminAgent.get("/rbac/roles").expect(200);
127
+ expect(rolesResponse.body.data.map((role: {name: string}) => role.name)).toEqual(
128
+ expect.arrayContaining(["superadmin", "member"])
129
+ );
130
+
131
+ const createResponse = await adminAgent
132
+ .post("/rbac/roles")
133
+ .send({
134
+ displayName: "Route Editor",
135
+ name: "route-editor",
136
+ permissions: {todo: ["read"]},
137
+ })
138
+ .expect(201);
139
+ expect(createResponse.body.data.name).toBe("route-editor");
140
+
141
+ const updateResponse = await adminAgent
142
+ .patch("/rbac/roles/route-editor")
143
+ .send({displayName: "Updated Route Editor"})
144
+ .expect(200);
145
+ expect(updateResponse.body.data.displayName).toBe("Updated Route Editor");
146
+
147
+ const rolePreviewResponse = await adminAgent
148
+ .post("/rbac/roles/route-editor/preview")
149
+ .send({permissions: {todo: ["read", "update"]}})
150
+ .expect(200);
151
+ expect(rolePreviewResponse.body.data.gained.todo).toEqual(["update"]);
152
+
153
+ const permissionsResponse = await adminAgent
154
+ .get(`/rbac/users/${targetUserId}/permissions`)
155
+ .expect(200);
156
+ expect(permissionsResponse.body.data.roles).toEqual(["member"]);
157
+
158
+ await adminAgent
159
+ .put(`/rbac/users/${targetUserId}/roles`)
160
+ .send({roleNames: ["auditor"]})
161
+ .expect(200);
162
+ const assignedUser = await routeUserModel.findById(targetUserId);
163
+ expect(assignedUser?.roles).toEqual(["auditor"]);
164
+
165
+ const assignmentPreviewResponse = await adminAgent
166
+ .post(`/rbac/users/${targetUserId}/roles/preview`)
167
+ .send({roleNames: ["member"]})
168
+ .expect(200);
169
+ expect(assignmentPreviewResponse.body.data).toHaveProperty("gained");
170
+
171
+ await adminAgent.delete("/rbac/roles/route-editor").expect(204);
172
+ });
173
+
174
+ it("returns unauthorized when a handler has no actor", async () => {
175
+ const actorlessRoutes = [
176
+ {body: {}, method: "post", path: "/rbac-unauthorized/roles"},
177
+ {body: {}, method: "patch", path: "/rbac-unauthorized/roles/member"},
178
+ {method: "delete", path: "/rbac-unauthorized/roles/member"},
179
+ {
180
+ body: {roleNames: ["member"]},
181
+ method: "put",
182
+ path: `/rbac-unauthorized/users/${targetUserId}/roles`,
183
+ },
184
+ ] as const;
185
+
186
+ for (const route of actorlessRoutes) {
187
+ const response =
188
+ route.method === "post"
189
+ ? await adminAgent.post(route.path).send(route.body)
190
+ : route.method === "patch"
191
+ ? await adminAgent.patch(route.path).send(route.body)
192
+ : route.method === "put"
193
+ ? await adminAgent.put(route.path).send(route.body)
194
+ : await adminAgent.delete(route.path);
195
+ expect(response.status).toBe(401);
196
+ expect(response.body.title).toBe("Unauthorized");
197
+ }
198
+ });
199
+
200
+ it("validates missing route parameters", async () => {
201
+ const roleResponse = await adminAgent
202
+ .patch("/rbac-invalid-params/roles/member")
203
+ .send({displayName: "Missing Name"});
204
+ expect(roleResponse.status).toBe(400);
205
+ expect(roleResponse.body.title).toBe("Role name is required");
206
+
207
+ const userResponse = await adminAgent.get(
208
+ `/rbac-invalid-params/users/${targetUserId}/permissions`
209
+ );
210
+ expect(userResponse.status).toBe(400);
211
+ expect(userResponse.body.title).toBe("User id is required");
212
+ });
213
+
214
+ it("validates role assignment bodies and missing users", async () => {
215
+ const missingRoleNamesResponse = await adminAgent
216
+ .put(`/rbac/users/${targetUserId}/roles`)
217
+ .send({});
218
+ expect(missingRoleNamesResponse.status).toBe(400);
219
+ expect(missingRoleNamesResponse.body.title).toBe("roleNames is required");
220
+
221
+ const missingPreviewRoleNamesResponse = await adminAgent
222
+ .post(`/rbac/users/${targetUserId}/roles/preview`)
223
+ .send({});
224
+ expect(missingPreviewRoleNamesResponse.status).toBe(400);
225
+ expect(missingPreviewRoleNamesResponse.body.title).toBe("roleNames is required");
226
+
227
+ const missingUserResponse = await adminAgent.get(
228
+ `/rbac/users/${new mongoose.Types.ObjectId()}/permissions`
229
+ );
230
+ expect(missingUserResponse.status).toBe(404);
231
+ expect(missingUserResponse.body.title).toBe("User not found");
232
+ });
233
+ });
@@ -6,6 +6,13 @@ import {APIError} from "../errors";
6
6
  import type {TerrenoPlugin} from "../terrenoPlugin";
7
7
  import type {AnyTerrenoAccess} from "./types";
8
8
 
9
+ const pathParam = (value: string | string[] | undefined, title: string): string => {
10
+ if (typeof value !== "string" || value.length === 0) {
11
+ throw new APIError({status: 400, title});
12
+ }
13
+ return value;
14
+ };
15
+
9
16
  export interface RbacRouterOptions {
10
17
  access: AnyTerrenoAccess;
11
18
  userModel: UserModel;
@@ -70,7 +77,7 @@ export const rbacRouter = ({
70
77
  const role = await access.roles.update({
71
78
  actor,
72
79
  changes: req.body,
73
- roleName: req.params.name,
80
+ roleName: pathParam(req.params.name, "Role name is required"),
74
81
  });
75
82
  return res.json({data: role});
76
83
  })
@@ -85,7 +92,10 @@ export const rbacRouter = ({
85
92
  if (!actor) {
86
93
  throw new APIError({status: 401, title: "Unauthorized"});
87
94
  }
88
- await access.roles.remove({actor, roleName: req.params.name});
95
+ await access.roles.remove({
96
+ actor,
97
+ roleName: pathParam(req.params.name, "Role name is required"),
98
+ });
89
99
  return res.status(204).send();
90
100
  })
91
101
  );
@@ -97,7 +107,7 @@ export const rbacRouter = ({
97
107
  asyncHandler(async (req, res) => {
98
108
  const diff = await access.roles.previewRoleChange({
99
109
  permissions: req.body.permissions,
100
- roleName: req.params.name,
110
+ roleName: pathParam(req.params.name, "Role name is required"),
101
111
  });
102
112
  return res.json({data: diff});
103
113
  })
@@ -108,7 +118,7 @@ export const rbacRouter = ({
108
118
  authenticateMiddleware(),
109
119
  access.middleware({rbac: ["read"]}),
110
120
  asyncHandler(async (req, res) => {
111
- const user = await userModel.findById(req.params.id);
121
+ const user = await userModel.findById(pathParam(req.params.id, "User id is required"));
112
122
  if (!user) {
113
123
  throw new APIError({status: 404, title: "User not found"});
114
124
  }
@@ -140,7 +150,7 @@ export const rbacRouter = ({
140
150
  await access.roles.assign({
141
151
  actor,
142
152
  roleNames: req.body.roleNames,
143
- userId: req.params.id,
153
+ userId: pathParam(req.params.id, "User id is required"),
144
154
  });
145
155
  return res.json({data: {success: true}});
146
156
  })
@@ -158,7 +168,7 @@ export const rbacRouter = ({
158
168
  const diff = await access.roles.previewAssignment({
159
169
  actor,
160
170
  roleNames: req.body.roleNames,
161
- userId: req.params.id,
171
+ userId: pathParam(req.params.id, "User id is required"),
162
172
  });
163
173
  return res.json({data: diff});
164
174
  })
@@ -0,0 +1,60 @@
1
+ import {afterEach, describe, expect, it, spyOn} from "bun:test";
2
+
3
+ import {modelRouter} from "../api";
4
+ import {logger} from "../logger";
5
+ import {Permissions} from "../permissions";
6
+ import {FoodModel} from "../tests";
7
+ import {
8
+ REALTIME_DEPRECATION_MESSAGE,
9
+ resetRealtimeDeprecationWarningsForTests,
10
+ } from "./deprecation";
11
+ import {clearRealtimeRegistry} from "./registry";
12
+
13
+ const realtimeConfig = {
14
+ methods: ["create", "update", "delete"] as Array<"create" | "update" | "delete">,
15
+ roomStrategy: "model" as const,
16
+ };
17
+
18
+ const permissions = {
19
+ create: [Permissions.IsAny],
20
+ delete: [Permissions.IsAny],
21
+ list: [Permissions.IsAny],
22
+ read: [Permissions.IsAny],
23
+ update: [Permissions.IsAny],
24
+ };
25
+
26
+ describe("modelRouter realtime deprecation", () => {
27
+ afterEach(() => {
28
+ resetRealtimeDeprecationWarningsForTests();
29
+ clearRealtimeRegistry();
30
+ });
31
+
32
+ it("warns once per model and path when realtime is configured", () => {
33
+ const warnSpy = spyOn(logger, "warn").mockImplementation(() => logger);
34
+
35
+ modelRouter("/foods", FoodModel, {permissions, realtime: realtimeConfig});
36
+ modelRouter("/foods", FoodModel, {permissions, realtime: realtimeConfig});
37
+
38
+ const deprecationCalls = warnSpy.mock.calls.filter((args) =>
39
+ String(args[0]).includes(REALTIME_DEPRECATION_MESSAGE)
40
+ );
41
+ expect(deprecationCalls).toHaveLength(1);
42
+ expect(String(deprecationCalls[0]?.[0])).toContain("Food at /foods");
43
+
44
+ warnSpy.mockRestore();
45
+ });
46
+
47
+ it("warns when realtime is used without the path form", () => {
48
+ const warnSpy = spyOn(logger, "warn").mockImplementation(() => logger);
49
+
50
+ modelRouter(FoodModel, {permissions, realtime: realtimeConfig});
51
+
52
+ const deprecationCalls = warnSpy.mock.calls.filter((args) =>
53
+ String(args[0]).includes(REALTIME_DEPRECATION_MESSAGE)
54
+ );
55
+ expect(deprecationCalls).toHaveLength(1);
56
+ expect(String(deprecationCalls[0]?.[0])).toContain("(Food)");
57
+
58
+ warnSpy.mockRestore();
59
+ });
60
+ });
@@ -0,0 +1,32 @@
1
+ import {logger} from "../logger";
2
+
3
+ /**
4
+ * One-line warning for modelRouter `realtime`. Keep in sync with the
5
+ * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
6
+ */
7
+ export const REALTIME_DEPRECATION_MESSAGE =
8
+ "modelRouter `realtime` is deprecated and will be removed in Terreno 58. Use `sync` with `@terreno/syncdb` instead. See docs/how-to/migrate-rtk-to-syncdb.md. RealtimeApp remains required for sync sockets.";
9
+
10
+ const warnedKeys = new Set<string>();
11
+
12
+ const warningKey = (modelName: string, routePath?: string): string =>
13
+ `${modelName}:${routePath ?? ""}`;
14
+
15
+ /**
16
+ * Emits a one-time deprecation warning per model/routePath per process when a
17
+ * consumer enables the legacy RTK cache-patching `realtime` option.
18
+ */
19
+ export const warnRealtimeDeprecated = (modelName: string, routePath?: string): void => {
20
+ const key = warningKey(modelName, routePath);
21
+ if (warnedKeys.has(key)) {
22
+ return;
23
+ }
24
+ warnedKeys.add(key);
25
+ const location = routePath ? `${modelName} at ${routePath}` : modelName;
26
+ logger.warn(`[realtime] ${REALTIME_DEPRECATION_MESSAGE} (${location})`);
27
+ };
28
+
29
+ /** @internal Test helper — clears one-time realtime deprecation warnings. */
30
+ export const resetRealtimeDeprecationWarningsForTests = (): void => {
31
+ warnedKeys.clear();
32
+ };
@@ -2779,14 +2779,16 @@ describe("RealtimeApp.onServerCreated", () => {
2779
2779
  return server;
2780
2780
  };
2781
2781
 
2782
- it("throws when TOKEN_SECRET is missing", () => {
2782
+ it("throws when no socket authentication method is configured", () => {
2783
2783
  const originalSecret = process.env.TOKEN_SECRET;
2784
2784
  process.env.TOKEN_SECRET = "";
2785
2785
 
2786
2786
  const app = new RealtimeApp({tokenSecret: undefined});
2787
2787
  const server = makeServer();
2788
2788
 
2789
- expect(() => app.onServerCreated(server)).toThrow("TOKEN_SECRET is required");
2789
+ expect(() => app.onServerCreated(server)).toThrow(
2790
+ "Socket authentication requires TOKEN_SECRET or Better Auth"
2791
+ );
2790
2792
 
2791
2793
  process.env.TOKEN_SECRET = originalSecret;
2792
2794
  });
@@ -3440,7 +3442,7 @@ describe("RealtimeApp — onServerCreated and setupAdapter", () => {
3440
3442
  server.close();
3441
3443
  });
3442
3444
 
3443
- it("onServerCreated throws when TOKEN_SECRET is missing", () => {
3445
+ it("onServerCreated throws when no socket authentication method is configured", () => {
3444
3446
  const http = require("node:http");
3445
3447
  const origSecret = process.env.TOKEN_SECRET;
3446
3448
  process.env.TOKEN_SECRET = "";
@@ -3449,7 +3451,9 @@ describe("RealtimeApp — onServerCreated and setupAdapter", () => {
3449
3451
  app.register(expressApp);
3450
3452
  const server = http.createServer(expressApp);
3451
3453
 
3452
- expect(() => app.onServerCreated(server)).toThrow("TOKEN_SECRET is required");
3454
+ expect(() => app.onServerCreated(server)).toThrow(
3455
+ "Socket authentication requires TOKEN_SECRET or Better Auth"
3456
+ );
3453
3457
  process.env.TOKEN_SECRET = origSecret;
3454
3458
  server.close();
3455
3459
  });
@@ -1,5 +1,3 @@
1
- // noExplicitAny: Socket.io handler signatures require dynamic args
2
- // biome-ignore-all lint/suspicious/noExplicitAny: Socket.io handler signatures require dynamic args
3
1
  import type http from "node:http";
4
2
  import * as Sentry from "@sentry/bun";
5
3
  import type express from "express";
@@ -323,7 +321,7 @@ export const installRealtimeSocketHandlers = (
323
321
  * TerrenoPlugin that provides real-time sync via Socket.io and MongoDB change streams.
324
322
  *
325
323
  * Attaches a Socket.io server to the HTTP server created by TerrenoApp.start(),
326
- * sets up JWT authentication for socket connections, manages room subscriptions
324
+ * sets up JWT and/or Better Auth authentication for socket connections, manages room subscriptions
327
325
  * (model, document, and query rooms), and starts a change stream watcher that
328
326
  * emits events to connected clients.
329
327
  *
@@ -394,14 +392,14 @@ export class RealtimeApp implements TerrenoPlugin {
394
392
  },
395
393
  });
396
394
 
397
- // Authentication middleware: legacy JWT first, optionally Better Auth sessions.
395
+ // Authentication middleware: legacy JWT first when configured, optionally Better Auth sessions.
398
396
  const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
399
- if (!tokenSecret) {
397
+ if (!tokenSecret && !this.config.betterAuth) {
400
398
  throw new APIError({
401
399
  status: 500,
402
400
  title:
403
- "[realtime] TOKEN_SECRET is required for socket authentication. " +
404
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
401
+ "[realtime] Socket authentication requires TOKEN_SECRET or Better Auth. " +
402
+ "Set process.env.TOKEN_SECRET, pass tokenSecret, or configure betterAuth.",
405
403
  });
406
404
  }
407
405
 
@@ -418,13 +416,14 @@ export class RealtimeApp implements TerrenoPlugin {
418
416
  createSocketAuthMiddleware({
419
417
  betterAuth: this.config.betterAuth,
420
418
  issuer: resolveTokenIssuer,
421
- tokenSecret,
419
+ ...(tokenSecret ? {tokenSecret} : {}),
422
420
  })
423
421
  );
424
422
 
425
- logInfo(
426
- `[realtime] Socket auth middleware added (JWT${this.config.betterAuth ? " + Better Auth" : ""})`
427
- );
423
+ const authKinds = [tokenSecret ? "JWT" : null, this.config.betterAuth ? "Better Auth" : null]
424
+ .filter(Boolean)
425
+ .join(" + ");
426
+ logInfo(`[realtime] Socket auth middleware added (${authKinds})`);
428
427
 
429
428
  // Task 9.21: tenant/custom sync scopes can only be resolved from the full user
430
429
  // document, so warn loudly here (once, at startup) rather than silently serving
@@ -5,8 +5,8 @@
5
5
  * are process-wide and would break later files that need the real implementations).
6
6
  */
7
7
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
8
-
9
8
  import type http from "node:http";
9
+ import {assert} from "chai";
10
10
 
11
11
  import {RealtimeApp} from "./realtimeApp";
12
12
 
@@ -100,7 +100,7 @@ describe("RealtimeApp.onServerCreated", () => {
100
100
  });
101
101
 
102
102
  afterEach(() => {
103
- delete process.env.TOKEN_SECRET;
103
+ Reflect.deleteProperty(process.env, "TOKEN_SECRET");
104
104
  });
105
105
 
106
106
  it("wires up auth middleware, connection handlers, and the change-stream watcher", () => {
@@ -151,9 +151,36 @@ describe("RealtimeApp.onServerCreated", () => {
151
151
  expect(lastIo().handlers.has("connection")).toBe(true);
152
152
  });
153
153
 
154
- it("throws when no token secret is available", () => {
155
- delete process.env.TOKEN_SECRET;
154
+ it("starts with Better Auth when no token secret is available", () => {
155
+ Reflect.deleteProperty(process.env, "TOKEN_SECRET");
156
+ const app = new RealtimeApp(
157
+ testRealtimeOptions({
158
+ betterAuth: {
159
+ auth: {
160
+ api: {
161
+ getSession: async () => ({
162
+ session: {id: "session-1"},
163
+ user: {id: "better-auth-user"},
164
+ }),
165
+ },
166
+ },
167
+ } as unknown as NonNullable<
168
+ NonNullable<ConstructorParameters<typeof RealtimeApp>[0]>["betterAuth"]
169
+ >,
170
+ })
171
+ );
172
+
173
+ assert.doesNotThrow(() => app.onServerCreated(fakeServer));
174
+ assert.lengthOf(lastIo().middleware, 1);
175
+ assert.isTrue(lastIo().handlers.has("connection"));
176
+ });
177
+
178
+ it("throws when no socket authentication method is available", () => {
179
+ Reflect.deleteProperty(process.env, "TOKEN_SECRET");
156
180
  const app = new RealtimeApp(testRealtimeOptions());
157
- expect(() => app.onServerCreated(fakeServer)).toThrow(/TOKEN_SECRET is required/);
181
+ assert.throws(
182
+ () => app.onServerCreated(fakeServer),
183
+ "Socket authentication requires TOKEN_SECRET or Better Auth"
184
+ );
158
185
  });
159
186
  });
@@ -1,78 +1,84 @@
1
+ import type {Model} from "mongoose";
2
+
1
3
  import type {ModelRouterOptions} from "../api";
4
+ import {
5
+ clearCollectionRegistry,
6
+ listCollections,
7
+ registerCollection,
8
+ replaceCollectionOptions,
9
+ } from "../collectionRegistry";
2
10
  import type {RealtimeConfig} from "./types";
3
11
 
4
- /**
5
- * A registered model with real-time sync configuration.
6
- */
7
12
  export interface RealtimeRegistryEntry {
8
- /** Mongoose model name (e.g. "Todo") */
9
13
  modelName: string;
10
- /** Route path (e.g. "/todos") */
11
14
  routePath: string;
12
- /** Collection name in MongoDB (e.g. "todos") */
13
15
  collectionName: string;
14
- /** Real-time configuration from modelRouter options */
15
16
  config: RealtimeConfig;
16
- /**
17
- * Full modelRouter options (for responseHandler, permissions, etc.), erased to
18
- * `unknown` since the registry holds entries for every model.
19
- */
20
17
  options: ModelRouterOptions<unknown>;
21
18
  }
22
19
 
23
- const realtimeRegistry: RealtimeRegistryEntry[] = [];
20
+ const toRealtimeEntry = (record: {
21
+ model: Model<unknown>;
22
+ options: ModelRouterOptions<unknown>;
23
+ routePath: string;
24
+ }): RealtimeRegistryEntry => ({
25
+ collectionName: record.model.collection.collectionName,
26
+ config: record.options.realtime as RealtimeConfig,
27
+ modelName: record.model.modelName,
28
+ options: record.options,
29
+ routePath: record.routePath,
30
+ });
31
+
32
+ const realtimeModelForEntry = (entry: RealtimeRegistryEntry): Model<unknown> => {
33
+ const registered = listCollections().find(
34
+ (record) => record.routePath === entry.routePath
35
+ )?.model;
36
+ if (registered) {
37
+ return registered;
38
+ }
39
+ return {
40
+ collection: {collectionName: entry.collectionName},
41
+ modelName: entry.modelName,
42
+ } as Model<unknown>;
43
+ };
24
44
 
25
- /**
26
- * Register a model for real-time sync. Called automatically by modelRouter
27
- * when the `realtime` option is provided.
28
- */
29
45
  export const registerRealtime = (entry: RealtimeRegistryEntry): void => {
30
- realtimeRegistry.push(entry);
46
+ registerCollection({
47
+ model: realtimeModelForEntry(entry),
48
+ options: {
49
+ ...entry.options,
50
+ realtime: entry.config,
51
+ } as ModelRouterOptions<unknown>,
52
+ routePath: entry.routePath,
53
+ });
31
54
  };
32
55
 
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
56
  export const updateRealtimeRegistryOptions = (
38
57
  routePath: string,
39
58
  options: ModelRouterOptions<unknown>
40
59
  ): void => {
41
- const existing = realtimeRegistry.find((entry) => entry.routePath === routePath);
42
- if (!existing) {
43
- return;
44
- }
45
- existing.options = options;
60
+ replaceCollectionOptions(routePath, options);
46
61
  };
47
62
 
48
- /**
49
- * Get all registered real-time models.
50
- */
51
- export const getRealtimeRegistry = (): RealtimeRegistryEntry[] => realtimeRegistry;
63
+ export const getRealtimeRegistry = (): RealtimeRegistryEntry[] =>
64
+ listCollections()
65
+ .filter((record) => record.surfaces.realtime)
66
+ .map(toRealtimeEntry);
52
67
 
53
- /**
54
- * Find a registry entry by MongoDB collection name.
55
- */
56
68
  export const findRegistryEntryByCollection = (
57
69
  collectionName: string
58
70
  ): RealtimeRegistryEntry | undefined => {
59
- return realtimeRegistry.find((entry) => entry.collectionName === collectionName);
71
+ return getRealtimeRegistry().find((entry) => entry.collectionName === collectionName);
60
72
  };
61
73
 
62
- /**
63
- * Find a registry entry by route path / collection tag (e.g. "todos").
64
- */
65
74
  export const findRegistryEntryByRoutePath = (
66
75
  collection: string
67
76
  ): RealtimeRegistryEntry | undefined => {
68
- return realtimeRegistry.find(
77
+ return getRealtimeRegistry().find(
69
78
  (entry) => entry.routePath === `/${collection}` || entry.routePath === collection
70
79
  );
71
80
  };
72
81
 
73
- /**
74
- * Clear the registry (for testing).
75
- */
76
82
  export const clearRealtimeRegistry = (): void => {
77
- realtimeRegistry.length = 0;
83
+ clearCollectionRegistry();
78
84
  };