@terreno/api 57.21.0 → 58.0.0-beta.2

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 (121) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -1
  3. package/dist/api.d.ts +0 -13
  4. package/dist/api.js +0 -9
  5. package/dist/auth.d.ts +3 -2
  6. package/dist/auth.js +95 -5
  7. package/dist/authRecovery.d.ts +2 -1
  8. package/dist/authRecovery.js +35 -17
  9. package/dist/collectionRegistry.d.ts +3 -4
  10. package/dist/collectionRegistry.js +0 -1
  11. package/dist/consentApp.d.ts +1 -1
  12. package/dist/consentApp.js +58 -2
  13. package/dist/index.d.ts +4 -5
  14. package/dist/index.js +8 -20
  15. package/dist/mcp/adminTracking.js +1 -1
  16. package/dist/mcp/serviceTokens.d.ts +21 -1
  17. package/dist/mcp/serviceTokens.js +159 -183
  18. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  19. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  20. package/dist/models/mcpRequestLog.js +1 -1
  21. package/dist/models/mcpServiceToken.js +36 -4
  22. package/dist/openApiBuilder.d.ts +4 -0
  23. package/dist/openApiBuilder.js +2 -0
  24. package/dist/rbac/realtimeAccess.d.ts +5 -4
  25. package/dist/rbac/realtimeAccess.js +17 -64
  26. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  27. package/dist/realtime/changeStreamWatcher.js +32 -391
  28. package/dist/realtime/realtimeApp.d.ts +14 -27
  29. package/dist/realtime/realtimeApp.js +14 -220
  30. package/dist/realtime/types.d.ts +0 -64
  31. package/dist/sync/entityIds.d.ts +14 -0
  32. package/dist/sync/entityIds.js +17 -0
  33. package/dist/sync/executors.js +14 -2
  34. package/dist/sync/models.d.ts +1 -0
  35. package/dist/sync/models.js +4 -0
  36. package/dist/sync/mutationHandler.js +51 -2
  37. package/dist/sync/routes.js +12 -17
  38. package/dist/sync/socketHandlers.d.ts +1 -1
  39. package/dist/sync/socketHandlers.js +1 -1
  40. package/dist/sync/types.d.ts +8 -0
  41. package/dist/terrenoApp.d.ts +7 -5
  42. package/dist/terrenoApp.js +18 -14
  43. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  44. package/dist/tests/openApiResponseSchema.js +56 -0
  45. package/dist/tests.d.ts +1 -0
  46. package/dist/tests.js +4 -1
  47. package/dist/types/mcpAdmin.d.ts +1 -1
  48. package/dist/types/mcpServiceToken.d.ts +7 -4
  49. package/dist/versionCheckPlugin.d.ts +1 -1
  50. package/dist/versionCheckPlugin.js +25 -2
  51. package/package.json +17 -6
  52. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  53. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  54. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  55. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  56. package/src/api.test.ts +9 -7
  57. package/src/api.ts +0 -24
  58. package/src/auth.ts +116 -5
  59. package/src/authOpenApi.test.ts +316 -0
  60. package/src/authRecovery.ts +47 -19
  61. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  62. package/src/collectionRegistry.ts +3 -5
  63. package/src/consentApp.test.ts +98 -0
  64. package/src/consentApp.ts +67 -2
  65. package/src/index.ts +6 -28
  66. package/src/mcp/actionTools.test.ts +2 -2
  67. package/src/mcp/adminTracking.ts +1 -1
  68. package/src/mcp/auth.test.ts +7 -3
  69. package/src/mcp/oauth.test.ts +12 -12
  70. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  71. package/src/mcp/serviceTokens.test.ts +112 -61
  72. package/src/mcp/serviceTokens.ts +193 -212
  73. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  74. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  75. package/src/models/mcpRequestLog.ts +1 -1
  76. package/src/models/mcpServiceToken.test.ts +52 -5
  77. package/src/models/mcpServiceToken.ts +51 -14
  78. package/src/openApiBuilder.test.ts +34 -1
  79. package/src/openApiBuilder.ts +5 -0
  80. package/src/rateLimit/rateLimit.test.ts +25 -10
  81. package/src/rbac/realtimeAccess.test.ts +20 -172
  82. package/src/rbac/realtimeAccess.ts +17 -82
  83. package/src/realtime/changeStreamWatcher.ts +43 -506
  84. package/src/realtime/realtime.test.ts +205 -2545
  85. package/src/realtime/realtimeApp.ts +16 -295
  86. package/src/realtime/types.ts +0 -72
  87. package/src/sync/entityIds.ts +18 -0
  88. package/src/sync/executors.test.ts +28 -0
  89. package/src/sync/executors.ts +23 -2
  90. package/src/sync/models.ts +6 -0
  91. package/src/sync/mutationHandler.test.ts +84 -0
  92. package/src/sync/mutationHandler.ts +57 -2
  93. package/src/sync/routes.ts +12 -17
  94. package/src/sync/socketHandlers.ts +1 -1
  95. package/src/sync/syncRoutes.test.ts +8 -4
  96. package/src/sync/syncSocket.test.ts +77 -113
  97. package/src/sync/types.ts +9 -0
  98. package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
  99. package/src/terrenoApp.ts +24 -18
  100. package/src/tests/openApiResponseSchema.ts +104 -0
  101. package/src/tests.ts +7 -0
  102. package/src/types/mcpAdmin.ts +1 -1
  103. package/src/types/mcpServiceToken.ts +7 -4
  104. package/src/versionCheckPlugin.ts +41 -2
  105. package/biome.jsonc +0 -22
  106. package/bunfig.toml +0 -10
  107. package/bunfig.unit.toml +0 -3
  108. package/dist/realtime/deprecation.d.ts +0 -13
  109. package/dist/realtime/deprecation.js +0 -31
  110. package/dist/realtime/queryStore.d.ts +0 -37
  111. package/dist/realtime/queryStore.js +0 -103
  112. package/dist/realtime/registry.d.ts +0 -15
  113. package/dist/realtime/registry.js +0 -52
  114. package/e2e/smoke.ts +0 -193
  115. package/src/realtime/deprecation.test.ts +0 -60
  116. package/src/realtime/deprecation.ts +0 -33
  117. package/src/realtime/queryStore.ts +0 -122
  118. package/src/realtime/registry.ts +0 -84
  119. package/tsconfig.json +0 -19
  120. package/tsconfig.typecheck.json +0 -14
  121. package/tsconfig.typedoc.json +0 -13
@@ -0,0 +1,316 @@
1
+ /** Verifies `/openapi.json` documents the auth, me, and recovery routes TerrenoApp mounts. */
2
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
3
+ import type express from "express";
4
+ import mongoose from "mongoose";
5
+ import supertest from "supertest";
6
+
7
+ import type {UserModel as UserModelType} from "./auth";
8
+ import {AuthToken} from "./authTokens";
9
+ import {createAccess} from "./rbac/access";
10
+ import {terrenoStatements} from "./rbac/statements";
11
+ import {TerrenoApp} from "./terrenoApp";
12
+ import {authAsUser, setupDb, UserModel} from "./tests";
13
+ import {expectDocumentedResponse, type OpenApiResponseSpec} from "./tests/openApiResponseSchema";
14
+
15
+ const typedUserModel = UserModel as unknown as UserModelType;
16
+
17
+ interface OpenApiSchemaNode {
18
+ properties?: Record<string, OpenApiSchemaNode>;
19
+ required?: string[];
20
+ type?: string;
21
+ }
22
+
23
+ interface OpenApiOperation {
24
+ parameters?: {in: string; name: string}[];
25
+ requestBody?: {content: Record<string, {schema: OpenApiSchemaNode}>};
26
+ responses: Record<string, {content?: Record<string, {schema: OpenApiSchemaNode}>}>;
27
+ tags?: string[];
28
+ }
29
+
30
+ type OpenApiPaths = Record<string, Record<string, OpenApiOperation>>;
31
+
32
+ const fetchPaths = async (app: express.Application): Promise<OpenApiPaths> => {
33
+ const res = await supertest(app).get("/openapi.json").expect(200);
34
+ return res.body.paths as OpenApiPaths;
35
+ };
36
+
37
+ const jsonSchema = (
38
+ operation: OpenApiOperation | undefined,
39
+ status: string
40
+ ): OpenApiSchemaNode | undefined => {
41
+ return operation?.responses[status]?.content?.["application/json"]?.schema;
42
+ };
43
+
44
+ describe("auth OpenAPI documentation", () => {
45
+ const originalEnv = process.env;
46
+
47
+ beforeEach(async () => {
48
+ process.env = {
49
+ ...originalEnv,
50
+ REFRESH_TOKEN_SECRET: "test-refresh-secret",
51
+ SESSION_SECRET: "test-session-secret",
52
+ TOKEN_EXPIRES_IN: "1h",
53
+ TOKEN_ISSUER: "test-issuer",
54
+ TOKEN_SECRET: "test-secret",
55
+ };
56
+ await setupDb();
57
+ });
58
+
59
+ afterEach(() => {
60
+ process.env = originalEnv;
61
+ });
62
+
63
+ describe("/auth/me", () => {
64
+ it("documents GET with the user model fields inside a data envelope", async () => {
65
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
66
+ const paths = await fetchPaths(app);
67
+
68
+ const getMe = paths["/auth/me"]?.get;
69
+ expect(getMe?.tags).toEqual(["auth"]);
70
+ const body = jsonSchema(getMe, "200");
71
+ expect(body?.required).toEqual(["data"]);
72
+ const user = body?.properties?.data;
73
+ expect(user?.type).toBe("object");
74
+ expect(user?.properties?.email?.type).toBe("string");
75
+ expect(user?.properties?.admin?.type).toBe("boolean");
76
+ expect(user?.properties?.id?.type).toBe("string");
77
+ expect(user?.properties?._id?.type).toBe("string");
78
+ expect(user?.required).toEqual(expect.arrayContaining(["_id", "id"]));
79
+ // passport-local-mongoose stores these with select: false, so /auth/me never returns them.
80
+ expect(user?.properties?.hash).toBeUndefined();
81
+ expect(user?.properties?.salt).toBeUndefined();
82
+ // Without accessControl the handler adds no roles/permissions.
83
+ expect(user?.properties?.permissions).toBeUndefined();
84
+ });
85
+
86
+ it("documents every field GET /auth/me actually returns", async () => {
87
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
88
+ const paths = await fetchPaths(app);
89
+ const documented = Object.keys(
90
+ jsonSchema(paths["/auth/me"]?.get, "200")?.properties?.data?.properties ?? {}
91
+ );
92
+
93
+ const agent = await authAsUser(app, "notAdmin");
94
+ const res = await agent.get("/auth/me").expect(200);
95
+ const returned = Object.keys(res.body.data).filter((key) => key !== "__v");
96
+ expect(documented).toEqual(expect.arrayContaining(returned));
97
+ });
98
+
99
+ it("documents PATCH with a partial user body that omits privileged fields", async () => {
100
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
101
+ const paths = await fetchPaths(app);
102
+
103
+ const patchMe = paths["/auth/me"]?.patch;
104
+ const requestSchema = patchMe?.requestBody?.content["application/json"]?.schema;
105
+ expect(requestSchema?.properties?.name?.type).toBe("string");
106
+ expect(requestSchema?.properties?.email?.type).toBe("string");
107
+ expect(requestSchema?.required).toBeUndefined();
108
+ for (const field of ["admin", "emailVerified", "tokenEpoch", "_id", "hash", "salt"]) {
109
+ expect(requestSchema?.properties?.[field]).toBeUndefined();
110
+ }
111
+ const body = jsonSchema(patchMe, "200");
112
+ expect(body?.required).toEqual(["data"]);
113
+ expect(body?.properties?.data?.properties?.id?.type).toBe("string");
114
+ });
115
+
116
+ it("keeps PATCH /auth/me behavior: privileged fields are still ignored", async () => {
117
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
118
+ const agent = await authAsUser(app, "notAdmin");
119
+ const res = await agent.patch("/auth/me").send({admin: true, name: "Renamed"}).expect(200);
120
+ expect(res.body.data.name).toBe("Renamed");
121
+ expect(res.body.data.admin).toBe(false);
122
+ });
123
+
124
+ it("documents roles and permissions when accessControl is configured", async () => {
125
+ const access = createAccess({
126
+ connection: mongoose.connection,
127
+ statements: terrenoStatements,
128
+ userModel: typedUserModel,
129
+ });
130
+ const app = new TerrenoApp({
131
+ accessControl: access,
132
+ skipListen: true,
133
+ userModel: typedUserModel,
134
+ }).build();
135
+ const paths = await fetchPaths(app);
136
+
137
+ const user = jsonSchema(paths["/auth/me"]?.get, "200")?.properties?.data;
138
+ expect(user?.properties?.roles?.type).toBe("array");
139
+ expect(user?.properties?.permissions?.type).toBe("object");
140
+ expect(user?.required).toEqual(expect.arrayContaining(["roles", "permissions"]));
141
+ });
142
+ });
143
+
144
+ describe("recovery routes", () => {
145
+ it("documents forgotPassword, resetPassword, sendVerification, and verifyEmail", async () => {
146
+ const app = new TerrenoApp({
147
+ authOptions: {publicAppUrl: "https://app.example.com"},
148
+ skipListen: true,
149
+ userModel: typedUserModel,
150
+ }).build();
151
+ const paths = await fetchPaths(app);
152
+
153
+ const forgot = paths["/auth/forgotPassword"]?.post;
154
+ expect(forgot?.requestBody?.content["application/json"]?.schema.properties?.email?.type).toBe(
155
+ "string"
156
+ );
157
+ expect(forgot?.responses["200"]).toBeUndefined();
158
+ const forgotBody = jsonSchema(forgot, "202");
159
+ expect(forgotBody?.required).toEqual(["data"]);
160
+ expect(forgotBody?.properties?.data?.properties?.ok?.type).toBe("boolean");
161
+
162
+ for (const path of ["/auth/resetPassword", "/resetPassword"]) {
163
+ const reset = paths[path]?.post;
164
+ expect(
165
+ Object.keys(reset?.requestBody?.content["application/json"]?.schema.properties ?? {})
166
+ ).toEqual(["newPassword", "password", "token"]);
167
+ const resetData = jsonSchema(reset, "200")?.properties?.data;
168
+ expect(resetData?.required).toEqual(["refreshToken", "token", "userId"]);
169
+ }
170
+
171
+ const sendVerification = paths["/auth/sendVerification"]?.post;
172
+ expect(sendVerification?.requestBody).toBeUndefined();
173
+ expect(jsonSchema(sendVerification, "202")?.properties?.data?.properties?.ok?.type).toBe(
174
+ "boolean"
175
+ );
176
+
177
+ const verifyEmail = paths["/auth/verifyEmail"]?.post;
178
+ expect(
179
+ verifyEmail?.requestBody?.content["application/json"]?.schema.properties?.token?.type
180
+ ).toBe("string");
181
+ expect(jsonSchema(verifyEmail, "200")?.properties?.data?.properties?.ok?.type).toBe(
182
+ "boolean"
183
+ );
184
+ });
185
+
186
+ it("omits routes the auth options turn off", async () => {
187
+ const app = new TerrenoApp({
188
+ authOptions: {emailVerification: false, legacyResetPasswordRoute: false},
189
+ skipListen: true,
190
+ userModel: typedUserModel,
191
+ }).build();
192
+ const paths = await fetchPaths(app);
193
+
194
+ expect(paths["/auth/forgotPassword"]?.post).toBeDefined();
195
+ expect(paths["/resetPassword"]).toBeUndefined();
196
+ expect(paths["/auth/sendVerification"]).toBeUndefined();
197
+ expect(paths["/auth/verifyEmail"]).toBeUndefined();
198
+ });
199
+ });
200
+
201
+ describe("documented responses", () => {
202
+ interface CapturedMail {
203
+ text: string;
204
+ }
205
+
206
+ let app: express.Application;
207
+ let spec: OpenApiResponseSpec;
208
+ let sentMail: CapturedMail[];
209
+
210
+ const tokenFromMail = (index: number): string => {
211
+ const match = sentMail[index]?.text.match(/token=([0-9a-f]+)/i);
212
+ expect(match).not.toBeNull();
213
+ return match?.[1] ?? "";
214
+ };
215
+
216
+ beforeEach(async () => {
217
+ await AuthToken.deleteMany({});
218
+ sentMail = [];
219
+ app = new TerrenoApp({
220
+ authOptions: {
221
+ publicAppUrl: "https://app.example.com",
222
+ sendMail: async (message) => {
223
+ sentMail.push(message);
224
+ },
225
+ },
226
+ rateLimit: false,
227
+ skipListen: true,
228
+ userModel: typedUserModel,
229
+ }).build();
230
+ spec = (await supertest(app).get("/openapi.json").expect(200)).body;
231
+ });
232
+
233
+ it("GET and PATCH /auth/me return bodies that match their schemas", async () => {
234
+ const agent = await authAsUser(app, "notAdmin");
235
+
236
+ const me = await agent.get("/auth/me").expect(200);
237
+ expectDocumentedResponse({method: "get", path: "/auth/me", response: me, spec});
238
+
239
+ const patched = await agent.patch("/auth/me").send({name: "Documented"}).expect(200);
240
+ expectDocumentedResponse({method: "patch", path: "/auth/me", response: patched, spec});
241
+ expect(patched.body.data.name).toBe("Documented");
242
+ });
243
+
244
+ it("forgotPassword and both resetPassword paths return documented bodies", async () => {
245
+ for (const email of ["notAdmin@example.com", "nobody@example.com"]) {
246
+ const forgot = await supertest(app).post("/auth/forgotPassword").send({email}).expect(202);
247
+ expectDocumentedResponse({
248
+ method: "post",
249
+ path: "/auth/forgotPassword",
250
+ response: forgot,
251
+ spec,
252
+ });
253
+ }
254
+ expect(sentMail).toHaveLength(1);
255
+
256
+ const reset = await supertest(app)
257
+ .post("/auth/resetPassword")
258
+ .send({password: "new-password-123", token: tokenFromMail(0)})
259
+ .expect(200);
260
+ expectDocumentedResponse({
261
+ method: "post",
262
+ path: "/auth/resetPassword",
263
+ response: reset,
264
+ spec,
265
+ });
266
+
267
+ // Each request issues a fresh token, so the legacy path gets its own.
268
+ await supertest(app)
269
+ .post("/auth/forgotPassword")
270
+ .send({email: "notAdmin@example.com"})
271
+ .expect(202);
272
+ const legacyReset = await supertest(app)
273
+ .post("/resetPassword")
274
+ .send({newPassword: "newer-password-456", token: tokenFromMail(1)})
275
+ .expect(200);
276
+ expectDocumentedResponse({
277
+ method: "post",
278
+ path: "/resetPassword",
279
+ response: legacyReset,
280
+ spec,
281
+ });
282
+
283
+ await supertest(app)
284
+ .post("/auth/login")
285
+ .send({email: "notAdmin@example.com", password: "newer-password-456"})
286
+ .expect(200);
287
+ });
288
+
289
+ it("sendVerification and verifyEmail return documented bodies", async () => {
290
+ const agent = await authAsUser(app, "notAdmin");
291
+
292
+ const sent = await agent.post("/auth/sendVerification").expect(202);
293
+ expectDocumentedResponse({
294
+ method: "post",
295
+ path: "/auth/sendVerification",
296
+ response: sent,
297
+ spec,
298
+ });
299
+ expect(sentMail).toHaveLength(1);
300
+
301
+ const verified = await supertest(app)
302
+ .post("/auth/verifyEmail")
303
+ .send({token: tokenFromMail(0)})
304
+ .expect(200);
305
+ expectDocumentedResponse({
306
+ method: "post",
307
+ path: "/auth/verifyEmail",
308
+ response: verified,
309
+ spec,
310
+ });
311
+
312
+ const me = await agent.get("/auth/me").expect(200);
313
+ expect(me.body.data.emailVerified).toBe(true);
314
+ });
315
+ });
316
+ });
@@ -1,6 +1,6 @@
1
1
  import express from "express";
2
2
 
3
- import {asyncHandler} from "./api";
3
+ import {asyncHandler, type OpenApiMiddleware} from "./api";
4
4
  import {
5
5
  authenticateMiddleware,
6
6
  generateTokens,
@@ -220,6 +220,14 @@ const incrementTokenEpoch = (user: User): void => {
220
220
  user.tokenEpoch = (user.tokenEpoch ?? 0) + 1;
221
221
  };
222
222
 
223
+ const okResponse = {
224
+ data: {
225
+ properties: {ok: {type: "boolean"}},
226
+ required: ["ok"],
227
+ type: "object",
228
+ },
229
+ };
230
+
223
231
  // The auth options passed to addAuthRoutes, kept on the app so changeUserPassword can reach the
224
232
  // Better Auth credential sync that TerrenoApp wires after the routes are added.
225
233
  const AUTH_OPTIONS_LOCAL_KEY = "terrenoAuthOptions";
@@ -261,8 +269,10 @@ export const changeUserPassword = async (
261
269
  export const addAuthRecoveryRoutes = (
262
270
  app: express.Application,
263
271
  userModel: UserModel,
264
- authOptions?: AuthOptions
272
+ authOptions?: AuthOptions,
273
+ openApi?: OpenApiMiddleware
265
274
  ): void => {
275
+ const openApiOptions = openApi ? {openApi} : {};
266
276
  if (authOptions) {
267
277
  app.locals[AUTH_OPTIONS_LOCAL_KEY] = authOptions;
268
278
  }
@@ -347,26 +357,42 @@ export const addAuthRecoveryRoutes = (
347
357
  });
348
358
  });
349
359
 
350
- const forgotOpenApi = createOpenApiBuilder({})
360
+ const forgotOpenApi = createOpenApiBuilder(openApiOptions)
351
361
  .withTags(["auth"])
352
362
  .withSummary("Request a password reset email")
353
- .withRequestBody({email: {type: "string"}})
354
- .withResponse(202, {ok: {type: "boolean"}})
363
+ .withDescription(
364
+ "Always returns 202, whether or not an account exists for the email, so accounts cannot be probed."
365
+ )
366
+ .withRequestBody({email: {description: "The account's email address", type: "string"}})
367
+ .withResponse(202, okResponse, {description: "Accepted", required: ["data"]})
355
368
  .build();
356
369
 
357
- const resetOpenApi = createOpenApiBuilder({})
370
+ const resetOpenApi = createOpenApiBuilder(openApiOptions)
358
371
  .withTags(["auth"])
359
372
  .withSummary("Reset password with a one-time token")
373
+ .withDescription(
374
+ "Send `token` and either `password` or `newPassword`. Returns fresh tokens for the user."
375
+ )
360
376
  .withRequestBody({
361
- newPassword: {type: "string"},
362
- password: {type: "string"},
363
- token: {type: "string"},
364
- })
365
- .withResponse(200, {
366
- refreshToken: {type: "string"},
367
- token: {type: "string"},
368
- userId: {type: "string"},
377
+ newPassword: {description: "Alias for password", type: "string"},
378
+ password: {description: "The new password", type: "string"},
379
+ token: {description: "One-time reset token from the emailed link", type: "string"},
369
380
  })
381
+ .withResponse(
382
+ 200,
383
+ {
384
+ data: {
385
+ properties: {
386
+ refreshToken: {type: "string"},
387
+ token: {type: "string"},
388
+ userId: {type: "string"},
389
+ },
390
+ required: ["refreshToken", "token", "userId"],
391
+ type: "object",
392
+ },
393
+ },
394
+ {required: ["data"]}
395
+ )
370
396
  .build();
371
397
 
372
398
  const sendVerification = asyncHandler(async (req: express.Request, res: express.Response) => {
@@ -396,17 +422,19 @@ export const addAuthRecoveryRoutes = (
396
422
  return res.json({data: {ok: true}});
397
423
  });
398
424
 
399
- const sendVerificationOpenApi = createOpenApiBuilder({})
425
+ const sendVerificationOpenApi = createOpenApiBuilder(openApiOptions)
400
426
  .withTags(["auth"])
401
427
  .withSummary("Send or resend an email verification link")
402
- .withResponse(202, {ok: {type: "boolean"}})
428
+ .withResponse(202, okResponse, {description: "Accepted", required: ["data"]})
403
429
  .build();
404
430
 
405
- const verifyEmailOpenApi = createOpenApiBuilder({})
431
+ const verifyEmailOpenApi = createOpenApiBuilder(openApiOptions)
406
432
  .withTags(["auth"])
407
433
  .withSummary("Verify email with a one-time token")
408
- .withRequestBody({token: {type: "string"}})
409
- .withResponse(200, {ok: {type: "boolean"}})
434
+ .withRequestBody({
435
+ token: {description: "One-time verification token from the emailed link", type: "string"},
436
+ })
437
+ .withResponse(200, okResponse, {required: ["data"]})
410
438
  .build();
411
439
 
412
440
  const router = express.Router();
@@ -44,7 +44,9 @@ const callbackOverridePlugin = {
44
44
  }
45
45
  }),
46
46
  matcher: (context: {path?: string}): boolean =>
47
- Boolean(context.path?.startsWith("/callback/")),
47
+ Boolean(
48
+ context.path?.startsWith("/callback/") || context.path?.startsWith("/oauth2/callback/")
49
+ ),
48
50
  },
49
51
  ],
50
52
  },
@@ -335,8 +337,12 @@ describe("oauthHandoff on a listed web origin", () => {
335
337
  .get(`/api/auth/callback/${PROVIDER_ID}?error=access_denied&state=${state}`)
336
338
  .set("cookie", cookie);
337
339
 
340
+ // better-auth 1.6 sends a generic-OAuth provider error to its own error page before it reads
341
+ // errorCallbackURL from state (1.7 honors it); either way the redirect carries no token.
338
342
  expect(callback.status).toBe(302);
339
- expect(callback.headers.location).toStartWith(`${WEB_ORIGIN}/error?error=access_denied`);
343
+ expect(callback.headers.location).toContain(
344
+ "https://web.example.com/error?error=access_denied"
345
+ );
340
346
  expect(callback.headers.location).not.toContain("ott=");
341
347
  });
342
348
 
@@ -610,7 +616,7 @@ describe("GET /oauth-handoff/start", () => {
610
616
  expect(verified.headers["set-auth-token"]).toBeTruthy();
611
617
  });
612
618
 
613
- it("sends a failed sign-in to a listed errorCallbackURL without a token", async () => {
619
+ it("sends a failed generic-OAuth sign-in to an error page without a token", async () => {
614
620
  const {app} = buildApp();
615
621
  const started = await start(app, {
616
622
  callbackURL: `${WEB_ORIGIN}/after`,
@@ -623,9 +629,11 @@ describe("GET /oauth-handoff/start", () => {
623
629
  .get(`/api/auth/callback/${PROVIDER_ID}?error=access_denied&state=${state}`)
624
630
  .set("cookie", cookieHeaderFrom(started));
625
631
 
632
+ // better-auth 1.7 honors errorCallbackURL for a generic-OAuth provider error; the redirect
633
+ // still carries no token.
626
634
  expect(returned.status).toBe(302);
627
- expect(returned.headers.location).toStartWith(
628
- `${WEB_ORIGIN}/sign-in-error?error=access_denied`
635
+ expect(returned.headers.location).toContain(
636
+ "https://web.example.com/sign-in-error?error=access_denied"
629
637
  );
630
638
  expect(returned.headers.location).not.toContain("ott=");
631
639
  });
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * Process-global catalog of modelRouter collections, keyed by routePath
3
- * (e.g. `/todos`). MCP, realtime, and Sync read this Map instead of each
3
+ * (e.g. `/todos`). MCP and Sync read this Map instead of each
4
4
  * keeping their own list. `modelRouter` is the writer; surface `register*`
5
5
  * / `update*` / `clear*` helpers are wrappers around this module.
6
6
  *
7
7
  * TerrenoApp later injects `accessControl` into options. That patch goes
8
- * through replaceCollectionOptions so all three surfaces see one options
8
+ * through replaceCollectionOptions so every surface sees one options
9
9
  * object. Surface flags stay sticky (OR) so a later replace cannot drop
10
- * mcp/realtime/sync once enabled. First-time sync enable still runs schema
10
+ * mcp/sync once enabled. First-time sync enable still runs schema
11
11
  * and index guards in registrationSideEffects — not here — so catalog
12
12
  * writes stay a Map update.
13
13
  */
@@ -36,7 +36,6 @@ const applyAdminBroadcastDefault = (options: ModelRouterOptions<unknown>): void
36
36
 
37
37
  interface CollectionSurfaces {
38
38
  mcp: boolean;
39
- realtime: boolean;
40
39
  sync: boolean;
41
40
  }
42
41
 
@@ -55,7 +54,6 @@ const deriveSurfaces = (
55
54
  existing?: CollectionSurfaces
56
55
  ): CollectionSurfaces => ({
57
56
  mcp: Boolean(options.mcp) || (existing?.mcp ?? false),
58
- realtime: Boolean(options.realtime) || (existing?.realtime ?? false),
59
57
  sync: Boolean(options.sync) || (existing?.sync ?? false),
60
58
  });
61
59
 
@@ -14,6 +14,7 @@ import {createAccess} from "./rbac/access";
14
14
  import {terrenoStatements} from "./rbac/statements";
15
15
  import {TerrenoApp} from "./terrenoApp";
16
16
  import {authAsUser, setupDb, type User, UserModel} from "./tests";
17
+ import {expectDocumentedResponse} from "./tests/openApiResponseSchema";
17
18
  import type {ConsentFormDocument} from "./types/consentForm";
18
19
 
19
20
  const buildApp = (consentAppOptions: ConsentAppOptions = {}): express.Application =>
@@ -979,6 +980,103 @@ describe("ConsentApp", () => {
979
980
  await noAuditAdmin.get(`/consents/audit/${notAdmin._id}`).expect(404);
980
981
  });
981
982
  });
983
+
984
+ describe("OpenAPI", () => {
985
+ interface SchemaNode {
986
+ items?: SchemaNode;
987
+ properties?: Record<string, SchemaNode>;
988
+ required?: string[];
989
+ type?: string;
990
+ }
991
+
992
+ const responseSchema = (
993
+ paths: Record<string, Record<string, {responses: Record<string, unknown>}>>,
994
+ path: string,
995
+ method: string
996
+ ): SchemaNode | undefined => {
997
+ const response = paths[path]?.[method]?.responses["200"] as
998
+ | {content?: Record<string, {schema: SchemaNode}>}
999
+ | undefined;
1000
+ return response?.content?.["application/json"]?.schema;
1001
+ };
1002
+
1003
+ it("documents GET /consents/pending and POST /consents/respond", async () => {
1004
+ const res = await supertest(buildApp()).get("/openapi.json").expect(200);
1005
+ const paths = res.body.paths;
1006
+
1007
+ const pending = responseSchema(paths, "/consents/pending", "get");
1008
+ expect(pending?.required).toEqual(["data"]);
1009
+ expect(pending?.properties?.data?.type).toBe("array");
1010
+ const formItem = pending?.properties?.data?.items;
1011
+ expect(formItem?.properties?.slug?.type).toBe("string");
1012
+ expect(formItem?.properties?.version?.type).toBe("number");
1013
+ expect(formItem?.properties?.id?.type).toBe("string");
1014
+
1015
+ const respond = paths["/consents/respond"]?.post;
1016
+ const body = respond?.requestBody?.content?.["application/json"]?.schema;
1017
+ expect(body?.required).toEqual(["agreed", "consentFormId", "locale"]);
1018
+ expect(body?.properties?.agreed?.type).toBe("boolean");
1019
+ expect(body?.properties?.checkboxValues?.additionalProperties).toEqual({type: "boolean"});
1020
+ expect(body?.properties?.signature?.type).toBe("string");
1021
+ const respondData = responseSchema(paths, "/consents/respond", "post")?.properties?.data;
1022
+ expect(respondData?.properties?.agreed?.type).toBe("boolean");
1023
+ expect(respondData?.properties?.consentFormId).toBeDefined();
1024
+ });
1025
+
1026
+ it("documents every field the consent routes return", async () => {
1027
+ const app = buildApp({auditTrail: true});
1028
+ const docRes = await supertest(app).get("/openapi.json").expect(200);
1029
+ const paths = docRes.body.paths;
1030
+ const form = await ConsentForm.create({
1031
+ active: true,
1032
+ captureSignature: true,
1033
+ content: new Map([["en", "# Terms"]]),
1034
+ order: 1,
1035
+ slug: "openapi-terms",
1036
+ title: "Terms",
1037
+ type: "terms",
1038
+ version: 1,
1039
+ });
1040
+ const agent = await authAsUser(app, "notAdmin");
1041
+
1042
+ const pendingRes = await agent.get("/consents/pending").expect(200);
1043
+ expectDocumentedResponse({
1044
+ method: "get",
1045
+ path: "/consents/pending",
1046
+ response: pendingRes,
1047
+ spec: docRes.body,
1048
+ });
1049
+ const pendingDocumented = Object.keys(
1050
+ responseSchema(paths, "/consents/pending", "get")?.properties?.data?.items?.properties ?? {}
1051
+ );
1052
+ expect(pendingDocumented).toEqual(
1053
+ expect.arrayContaining(Object.keys(pendingRes.body.data[0]).filter((key) => key !== "__v"))
1054
+ );
1055
+
1056
+ const respondRes = await agent
1057
+ .post("/consents/respond")
1058
+ .send({
1059
+ agreed: true,
1060
+ consentFormId: form._id,
1061
+ locale: "en",
1062
+ signature: "data:image/png;base64,AA",
1063
+ })
1064
+ .expect(200);
1065
+ expectDocumentedResponse({
1066
+ method: "post",
1067
+ path: "/consents/respond",
1068
+ response: respondRes,
1069
+ spec: docRes.body,
1070
+ });
1071
+ const respondDocumented = Object.keys(
1072
+ responseSchema(paths, "/consents/respond", "post")?.properties?.data?.properties ?? {}
1073
+ );
1074
+ expect(respondDocumented).toEqual(
1075
+ expect.arrayContaining(Object.keys(respondRes.body.data).filter((key) => key !== "__v"))
1076
+ );
1077
+ });
1078
+ });
1079
+
982
1080
  describe("POST /consent-responses/provisional", () => {
983
1081
  const createActiveForm = async (
984
1082
  overrides: Partial<Record<string, unknown>> = {}