@terreno/api 57.4.0 → 57.6.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 (208) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +598 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/audit/auditApp.test.ts +5 -5
  173. package/src/audit/auditEventModel.ts +7 -3
  174. package/src/audit/auditRouter.test.ts +5 -5
  175. package/src/audit/rbacSink.test.ts +2 -2
  176. package/src/audit/record.test.ts +2 -2
  177. package/src/audit/record.ts +3 -2
  178. package/src/auth.ts +1 -1
  179. package/src/authRecovery.test.ts +43 -0
  180. package/src/authRecovery.ts +16 -10
  181. package/src/authTokens.ts +6 -2
  182. package/src/authVerification.test.ts +22 -0
  183. package/src/browserLogsRoute.ts +110 -0
  184. package/src/configurationPlugin.test.ts +1 -11
  185. package/src/expressServer.ts +10 -0
  186. package/src/frameworkModelNames.test.ts +62 -0
  187. package/src/frameworkModelNames.ts +33 -0
  188. package/src/index.ts +7 -0
  189. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  190. package/src/mcp/auth.test.ts +34 -1
  191. package/src/migrations/cli.test.ts +0 -23
  192. package/src/models/mcpServiceToken.ts +4 -3
  193. package/src/models/notification.ts +3 -2
  194. package/src/models/notificationPreference.ts +1 -1
  195. package/src/notifications/notificationsApp.test.ts +24 -1
  196. package/src/notifiers/slackNotifier.test.ts +186 -1
  197. package/src/notifiers/slackNotifier.ts +167 -8
  198. package/src/orgs/orgPlugin.ts +1 -1
  199. package/src/orgs/organizationModel.ts +11 -6
  200. package/src/plugins.test.ts +5 -0
  201. package/src/plugins.ts +3 -0
  202. package/src/realtime/realtimeApp.ts +1 -1
  203. package/src/sync/integration.test.ts +2 -2
  204. package/src/terrenoApp.ts +3 -0
  205. package/src/types.d.ts +1 -0
  206. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  207. package/tsconfig.json +13 -54
  208. package/tsconfig.typedoc.json +2 -0
@@ -144,13 +144,17 @@ export const createAuditEventModel = (
144
144
  connection: mongoose.Connection,
145
145
  options: {retentionDays?: number} = {}
146
146
  ): AuditEventModel => {
147
- if (connection.models.AuditEvent) {
148
- return connection.models.AuditEvent as AuditEventModel;
147
+ if (connection.models.TerrenoAuditEvent) {
148
+ return connection.models.TerrenoAuditEvent as AuditEventModel;
149
149
  }
150
150
  const schema = auditEventSchema.clone();
151
151
  const expireAfterSeconds = ttlExpireAfterSeconds(options.retentionDays);
152
152
  if (expireAfterSeconds !== undefined) {
153
153
  replaceCreatedIndexWithTtl(schema as unknown as mongoose.Schema, expireAfterSeconds);
154
154
  }
155
- return connection.model<AuditEventDocument, AuditEventModel>("AuditEvent", schema);
155
+ return connection.model<AuditEventDocument, AuditEventModel>(
156
+ "TerrenoAuditEvent",
157
+ schema,
158
+ "auditevents"
159
+ );
156
160
  };
@@ -133,7 +133,7 @@ describe("modelRouter audit", () => {
133
133
  beforeEach(async () => {
134
134
  resetAuditRecorderForTests();
135
135
  deleteNamedModel("Note");
136
- deleteNamedModel("AuditEvent");
136
+ deleteNamedModel("TerrenoAuditEvent");
137
137
  await setupDb();
138
138
  await mongoose.connection.collection("auditevents").deleteMany({});
139
139
  });
@@ -141,7 +141,7 @@ describe("modelRouter audit", () => {
141
141
  afterEach(() => {
142
142
  resetAuditRecorderForTests();
143
143
  deleteNamedModel("Note");
144
- deleteNamedModel("AuditEvent");
144
+ deleteNamedModel("TerrenoAuditEvent");
145
145
  });
146
146
 
147
147
  it("writes a create event with after only and strips secrets", async () => {
@@ -232,7 +232,7 @@ describe("modelRouter audit", () => {
232
232
  await agent.post("/notes").send({title: "A"}).expect(201);
233
233
  await agent.post("/notes").send({title: "B"}).expect(201);
234
234
  await flushAuditRecorderForTests();
235
- assert.isUndefined(mongoose.connection.models.AuditEvent);
235
+ assert.isUndefined(mongoose.connection.models.TerrenoAuditEvent);
236
236
  const auditLogs = errorSpy.mock.calls.filter((call) =>
237
237
  String(call[0]).includes("requires AuditApp")
238
238
  );
@@ -387,7 +387,7 @@ describe("modelRouter audit", () => {
387
387
  describe("maybeRecordAdminAudit", () => {
388
388
  beforeEach(async () => {
389
389
  deleteNamedModel("Note");
390
- deleteNamedModel("AuditEvent");
390
+ deleteNamedModel("TerrenoAuditEvent");
391
391
  resetAuditRecorderForTests();
392
392
  await setupDb();
393
393
  await mongoose.connection.collection("auditevents").deleteMany({});
@@ -396,7 +396,7 @@ describe("maybeRecordAdminAudit", () => {
396
396
  afterEach(() => {
397
397
  resetAuditRecorderForTests();
398
398
  deleteNamedModel("Note");
399
- deleteNamedModel("AuditEvent");
399
+ deleteNamedModel("TerrenoAuditEvent");
400
400
  });
401
401
 
402
402
  it("does not write when AuditApp is not registered", async () => {
@@ -12,8 +12,8 @@ import {flushAuditRecorderForTests, resetAuditRecorderForTests} from "./record";
12
12
  const typedUserModel = UserModel as unknown as AuthUserModel;
13
13
 
14
14
  const deleteAuditEventModel = (): void => {
15
- if (mongoose.connection.models.AuditEvent) {
16
- mongoose.connection.deleteModel("AuditEvent");
15
+ if (mongoose.connection.models.TerrenoAuditEvent) {
16
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
17
17
  }
18
18
  };
19
19
 
@@ -24,8 +24,8 @@ import {
24
24
  const typedUserModel = UserModel as unknown as AuthUserModel;
25
25
 
26
26
  const deleteAuditEventModel = (): void => {
27
- if (mongoose.connection.models.AuditEvent) {
28
- mongoose.connection.deleteModel("AuditEvent");
27
+ if (mongoose.connection.models.TerrenoAuditEvent) {
28
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
29
29
  }
30
30
  };
31
31
 
@@ -34,6 +34,7 @@ export interface AuditEventWrite {
34
34
 
35
35
  const MISSING_PLUGIN_MESSAGE =
36
36
  "modelRouter audit: true requires AuditApp to be registered; skipping AuditEvent write";
37
+ const AUDIT_EVENT_MODEL_NAMES = new Set(["AuditEvent", "TerrenoAuditEvent"]);
37
38
 
38
39
  let auditEventModel: AuditEventModel | undefined;
39
40
  let auditEnqueue: AuditEnqueue | undefined;
@@ -92,7 +93,7 @@ export const maybeRecordAdminAudit = async ({
92
93
  if (!auditEventModel) {
93
94
  return;
94
95
  }
95
- if (modelName === "AuditEvent") {
96
+ if (AUDIT_EVENT_MODEL_NAMES.has(modelName)) {
96
97
  return;
97
98
  }
98
99
  const beforePlain = toAuditPlain(before);
@@ -233,7 +234,7 @@ export const snapshotAuditBefore = ({
233
234
  };
234
235
 
235
236
  const persistAuditEvent = async (write: AuditEventWrite): Promise<void> => {
236
- if (write.modelName === "AuditEvent") {
237
+ if (AUDIT_EVENT_MODEL_NAMES.has(write.modelName)) {
237
238
  return;
238
239
  }
239
240
  if (!auditEventModel) {
package/src/auth.ts CHANGED
@@ -695,7 +695,7 @@ export const addAuthRoutes = (
695
695
  )(req, res, next);
696
696
  },
697
697
  async (req: express.Request, res: express.Response) => {
698
- if (req.user) {
698
+ if (req.user && authOptions?.emailVerification !== false) {
699
699
  try {
700
700
  await sendVerificationEmail(req.user, authOptions);
701
701
  } catch (error: unknown) {
@@ -143,6 +143,49 @@ describe("password reset routes", () => {
143
143
  .expect(200);
144
144
  });
145
145
 
146
+ it("can disable only the legacy POST /resetPassword alias", async () => {
147
+ const noLegacyAliasApp = new TerrenoApp({
148
+ authOptions: {
149
+ legacyResetPasswordRoute: false,
150
+ publicAppUrl: "https://app.example.com",
151
+ },
152
+ skipListen: true,
153
+ userModel: UserModel,
154
+ }).build();
155
+
156
+ await supertest(noLegacyAliasApp).post("/resetPassword").send({}).expect(404);
157
+ await supertest(noLegacyAliasApp).post("/auth/resetPassword").send({}).expect(400);
158
+ });
159
+
160
+ it("can disable all password reset routes", async () => {
161
+ const noPasswordResetApp = new TerrenoApp({
162
+ authOptions: {
163
+ passwordReset: false,
164
+ publicAppUrl: "https://app.example.com",
165
+ },
166
+ skipListen: true,
167
+ userModel: UserModel,
168
+ }).build();
169
+
170
+ await supertest(noPasswordResetApp).post("/auth/forgotPassword").send({}).expect(404);
171
+ await supertest(noPasswordResetApp).post("/auth/resetPassword").send({}).expect(404);
172
+ await supertest(noPasswordResetApp).post("/resetPassword").send({}).expect(404);
173
+ });
174
+
175
+ it("can disable all email verification routes", async () => {
176
+ const noEmailVerificationApp = new TerrenoApp({
177
+ authOptions: {
178
+ emailVerification: false,
179
+ publicAppUrl: "https://app.example.com",
180
+ },
181
+ skipListen: true,
182
+ userModel: UserModel,
183
+ }).build();
184
+
185
+ await supertest(noEmailVerificationApp).post("/auth/sendVerification").send({}).expect(404);
186
+ await supertest(noEmailVerificationApp).post("/auth/verifyEmail").send({}).expect(404);
187
+ });
188
+
146
189
  it("syncs a successful JWT reset to Better Auth when a bridge is configured", async () => {
147
190
  const synced: Array<{email?: string; password: string}> = [];
148
191
  const bridgedApp = new TerrenoApp({
@@ -265,15 +265,21 @@ export const addAuthRecoveryRoutes = (
265
265
  .build();
266
266
 
267
267
  const router = express.Router();
268
- router.post("/forgotPassword", forgotOpenApi, forgotPassword);
269
- router.post("/resetPassword", resetOpenApi, resetPassword);
270
- router.post(
271
- "/sendVerification",
272
- authenticateMiddleware(),
273
- sendVerificationOpenApi,
274
- sendVerification
275
- );
276
- router.post("/verifyEmail", verifyEmailOpenApi, verifyEmail);
268
+ if (authOptions?.passwordReset !== false) {
269
+ router.post("/forgotPassword", forgotOpenApi, forgotPassword);
270
+ router.post("/resetPassword", resetOpenApi, resetPassword);
271
+ }
272
+ if (authOptions?.emailVerification !== false) {
273
+ router.post(
274
+ "/sendVerification",
275
+ authenticateMiddleware(),
276
+ sendVerificationOpenApi,
277
+ sendVerification
278
+ );
279
+ router.post("/verifyEmail", verifyEmailOpenApi, verifyEmail);
280
+ }
277
281
  app.use("/auth", router);
278
- app.post("/resetPassword", resetOpenApi, resetPassword);
282
+ if (authOptions?.passwordReset !== false && authOptions?.legacyResetPasswordRoute !== false) {
283
+ app.post("/resetPassword", resetOpenApi, resetPassword);
284
+ }
279
285
  };
package/src/authTokens.ts CHANGED
@@ -114,5 +114,9 @@ authTokenSchema.statics = {
114
114
  };
115
115
 
116
116
  export const AuthToken =
117
- (mongoose.models.AuthToken as AuthTokenModel | undefined) ??
118
- mongoose.model<AuthTokenDocument, AuthTokenModel>("AuthToken", authTokenSchema);
117
+ (mongoose.models.TerrenoAuthToken as AuthTokenModel | undefined) ??
118
+ mongoose.model<AuthTokenDocument, AuthTokenModel>(
119
+ "TerrenoAuthToken",
120
+ authTokenSchema,
121
+ "authtokens"
122
+ );
@@ -99,6 +99,28 @@ describe("email verification gating", () => {
99
99
  .expect(200);
100
100
  });
101
101
 
102
+ it("does not issue an unusable verification token on signup when routes are disabled", async () => {
103
+ const noVerificationRoutesApp = new TerrenoApp({
104
+ authOptions: {
105
+ emailVerification: false,
106
+ publicAppUrl: "https://app.example.com",
107
+ sendMail: async (message) => {
108
+ openMail.push(message);
109
+ },
110
+ },
111
+ skipListen: true,
112
+ userModel: UserModel,
113
+ }).build();
114
+
115
+ await supertest(noVerificationRoutesApp)
116
+ .post("/auth/signup")
117
+ .send({email: "custom-verification@example.com", password: "password"})
118
+ .expect(200);
119
+
120
+ assert.equal(openMail.length, 0);
121
+ assert.equal(await AuthToken.countDocuments({type: "emailVerification"}), 0);
122
+ });
123
+
102
124
  it("resends verification mail for an authenticated unverified user", async () => {
103
125
  const login = await supertest(openApp)
104
126
  .post("/auth/login")
@@ -0,0 +1,110 @@
1
+ import {appendFileSync, existsSync, mkdirSync, statSync, writeFileSync} from "node:fs";
2
+ import {join} from "node:path";
3
+ import express from "express";
4
+ import {DateTime} from "luxon";
5
+
6
+ const MAX_BATCH_ENTRIES = 100;
7
+ const MAX_LEVEL_LENGTH = 32;
8
+ const MAX_MESSAGE_LENGTH = 8000;
9
+ const MAX_STACK_LENGTH = 16_000;
10
+ const BROWSER_LOG_BODY_LIMIT_BYTES = 256 * 1024;
11
+ const BROWSER_LOG_BODY_LIMIT = "256kb";
12
+ const MAX_BROWSER_LOG_FILE_BYTES = 5 * 1024 * 1024;
13
+
14
+ const shouldEnableBrowserLogs = (): boolean => {
15
+ if (process.env.NODE_ENV === "production") {
16
+ return false;
17
+ }
18
+ if (process.env.TERRENO_BROWSER_LOGS === "false" || process.env.TERRENO_BROWSER_LOGS === "0") {
19
+ return false;
20
+ }
21
+ if (process.env.TERRENO_BROWSER_LOGS === "true" || process.env.TERRENO_BROWSER_LOGS === "1") {
22
+ return true;
23
+ }
24
+ return process.env.NODE_ENV === "development";
25
+ };
26
+
27
+ interface BrowserLogPayload {
28
+ level?: string;
29
+ message?: unknown;
30
+ stack?: string;
31
+ timestamp?: string;
32
+ }
33
+
34
+ const isLoopbackAddress = (address: string | undefined): boolean => {
35
+ return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
36
+ };
37
+
38
+ const isBrowserLogRequestAllowed = (req: express.Request): boolean => {
39
+ return Boolean(req.user) || isLoopbackAddress(req.socket.remoteAddress);
40
+ };
41
+
42
+ /**
43
+ * Dev-only ingestion for the Terreno MCP `read_logs` tool: POST batches of client
44
+ * console / global error lines as JSONL under `.terreno/logs/browser.log`.
45
+ */
46
+ export const addTerrenoDevBrowserLogsRoute = (app: express.Application): void => {
47
+ if (!shouldEnableBrowserLogs()) {
48
+ return;
49
+ }
50
+
51
+ app.post("/__terreno/browser-logs", express.json({limit: BROWSER_LOG_BODY_LIMIT}), (req, res) => {
52
+ if (!isBrowserLogRequestAllowed(req)) {
53
+ res
54
+ .status(403)
55
+ .json({error: "Browser log ingestion requires a local or authenticated client"});
56
+ return;
57
+ }
58
+ const parsedBodySize = Buffer.byteLength(JSON.stringify(req.body ?? null));
59
+ if (parsedBodySize > BROWSER_LOG_BODY_LIMIT_BYTES) {
60
+ res.status(413).json({error: "Browser log payload may not exceed 256 kB"});
61
+ return;
62
+ }
63
+ const body = req.body as {entries?: unknown} | undefined;
64
+ if (!Array.isArray(body?.entries) || body.entries.length === 0) {
65
+ res.status(400).json({error: "Expected { entries: [...] }"});
66
+ return;
67
+ }
68
+ if (body.entries.length > MAX_BATCH_ENTRIES) {
69
+ res.status(413).json({error: `A batch may contain at most ${MAX_BATCH_ENTRIES} entries`});
70
+ return;
71
+ }
72
+
73
+ const logDir = join(process.cwd(), ".terreno", "logs");
74
+ mkdirSync(logDir, {recursive: true});
75
+ const path = join(logDir, "browser.log");
76
+ const lines: string[] = [];
77
+
78
+ for (const row of body.entries) {
79
+ if (typeof row !== "object" || row === null) {
80
+ continue;
81
+ }
82
+ const r = row as BrowserLogPayload;
83
+ const level = (typeof r.level === "string" ? r.level : "info").slice(0, MAX_LEVEL_LENGTH);
84
+ const rawMessage =
85
+ typeof r.message === "string" ? r.message : JSON.stringify(r.message ?? "");
86
+ lines.push(
87
+ JSON.stringify({
88
+ level,
89
+ message: rawMessage.slice(0, MAX_MESSAGE_LENGTH),
90
+ source: "browser",
91
+ stack: typeof r.stack === "string" ? r.stack.slice(0, MAX_STACK_LENGTH) : undefined,
92
+ timestamp:
93
+ typeof r.timestamp === "string" && r.timestamp ? r.timestamp : DateTime.now().toISO(),
94
+ })
95
+ );
96
+ }
97
+
98
+ if (lines.length > 0) {
99
+ const payload = `${lines.join("\n")}\n`;
100
+ const currentSize = existsSync(path) ? statSync(path).size : 0;
101
+ if (currentSize + Buffer.byteLength(payload) > MAX_BROWSER_LOG_FILE_BYTES) {
102
+ writeFileSync(path, payload, {encoding: "utf-8", mode: 0o600});
103
+ } else {
104
+ appendFileSync(path, payload, {encoding: "utf-8", mode: 0o600});
105
+ }
106
+ }
107
+
108
+ res.status(204).end();
109
+ });
110
+ };
@@ -1,4 +1,4 @@
1
- import {afterAll, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
1
+ import {beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
2
2
  import mongoose, {model, Schema} from "mongoose";
3
3
  import type {ConfigurationModel, Paths, SecretProvider} from "./configurationPlugin";
4
4
  import {configurationPlugin, flattenToDotPaths} from "./configurationPlugin";
@@ -300,16 +300,6 @@ describe("configurationPlugin", () => {
300
300
  }
301
301
  });
302
302
 
303
- afterAll(async () => {
304
- if (dbConnected && mongoose.connection.readyState === 1) {
305
- try {
306
- await mongoose.connection.db?.dropDatabase();
307
- } catch {
308
- // ignore
309
- }
310
- }
311
- });
312
-
313
303
  beforeEach(async () => {
314
304
  if (!dbConnected) {
315
305
  return;
@@ -219,6 +219,16 @@ export interface AuthOptions {
219
219
  generateJWTPayload?: (user: User) => Record<string, unknown>;
220
220
  generateTokenExpiration?: (user: User) => number | jwt.SignOptions["expiresIn"];
221
221
  generateRefreshTokenExpiration?: (user: User) => number | jwt.SignOptions["expiresIn"];
222
+ /** Register JWT forgot-password and token-reset routes. Default true. */
223
+ passwordReset?: boolean;
224
+ /**
225
+ * Register the deprecated `POST /resetPassword` RTK compatibility alias.
226
+ * Default true. Set false when the host owns that path; `/auth/resetPassword`
227
+ * remains available when `passwordReset` is enabled.
228
+ */
229
+ legacyResetPasswordRoute?: boolean;
230
+ /** Register JWT send-verification and verify-email routes. Default true. */
231
+ emailVerification?: boolean;
222
232
  /** Public web/app origin used in password-reset and verification links. */
223
233
  publicAppUrl?: string;
224
234
  /**
@@ -0,0 +1,62 @@
1
+ import {afterAll, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import mongoose from "mongoose";
4
+
5
+ import {createAuditEventModel} from "./audit/auditEventModel";
6
+ import {AuthToken} from "./authTokens";
7
+ import {FRAMEWORK_MODEL_PUBLIC_NAMES, publicFrameworkModelName} from "./frameworkModelNames";
8
+ import {McpServiceToken} from "./models/mcpServiceToken";
9
+ import {Notification} from "./models/notification";
10
+ import {NotificationPreference} from "./models/notificationPreference";
11
+ import {getMembershipModel, getOrganizationModel} from "./orgs/organizationModel";
12
+ import {getWebhookReceiptModel} from "./webhooks/idempotency/webhookReceipt";
13
+
14
+ const CONSUMER_MODEL_NAMES = [
15
+ "AuditEvent",
16
+ "AuthToken",
17
+ "McpServiceToken",
18
+ "Membership",
19
+ "Notification",
20
+ "NotificationPreference",
21
+ "Organization",
22
+ "WebhookReceipt",
23
+ ] as const;
24
+
25
+ afterAll(() => {
26
+ for (const modelName of CONSUMER_MODEL_NAMES) {
27
+ if (mongoose.models[modelName]) {
28
+ mongoose.deleteModel(modelName);
29
+ }
30
+ }
31
+ });
32
+
33
+ describe("framework model names", () => {
34
+ it("uses Terreno-specific names without changing existing collection names", () => {
35
+ const models = [
36
+ [createAuditEventModel(mongoose.connection), "TerrenoAuditEvent", "auditevents"],
37
+ [AuthToken, "TerrenoAuthToken", "authtokens"],
38
+ [McpServiceToken, "TerrenoMcpServiceToken", "mcpservicetokens"],
39
+ [getMembershipModel(), "TerrenoMembership", "memberships"],
40
+ [Notification, "TerrenoInboxNotification", "notifications"],
41
+ [NotificationPreference, "TerrenoNotificationPreference", "notificationpreferences"],
42
+ [getOrganizationModel(), "TerrenoOrganization", "organizations"],
43
+ [getWebhookReceiptModel(), "TerrenoWebhookReceipt", "webhookReceipts"],
44
+ ] as const;
45
+
46
+ for (const [model, modelName, collectionName] of models) {
47
+ assert.equal(model.modelName, modelName);
48
+ assert.equal(model.collection.collectionName, collectionName);
49
+ assert.equal(publicFrameworkModelName(modelName), FRAMEWORK_MODEL_PUBLIC_NAMES[modelName]);
50
+ }
51
+ assert.equal(publicFrameworkModelName("Todo"), "Todo");
52
+ assert.equal(publicFrameworkModelName("TerrenoInboxNotification"), "Notification");
53
+ assert.equal(publicFrameworkModelName("TerrenoAnnouncement"), "Announcement");
54
+ assert.equal(publicFrameworkModelName("TerrenoJob"), "Job");
55
+ });
56
+
57
+ it("allows consumers to register the former generic model names", () => {
58
+ for (const modelName of CONSUMER_MODEL_NAMES) {
59
+ assert.doesNotThrow(() => mongoose.model(modelName, new mongoose.Schema({})));
60
+ }
61
+ });
62
+ });
@@ -0,0 +1,33 @@
1
+ /** Mongoose compiled names for framework models that used to be generic. */
2
+ export const FRAMEWORK_MODEL_PUBLIC_NAMES = {
3
+ TerrenoAnnouncement: "Announcement",
4
+ TerrenoAnnouncementAcknowledgement: "AnnouncementAcknowledgement",
5
+ TerrenoAnnouncementClickEvent: "AnnouncementClickEvent",
6
+ TerrenoAnnouncementImpression: "AnnouncementImpression",
7
+ TerrenoAuditEvent: "AuditEvent",
8
+ TerrenoAuthToken: "AuthToken",
9
+ TerrenoInboxNotification: "Notification",
10
+ TerrenoJob: "Job",
11
+ TerrenoJobSchedule: "JobSchedule",
12
+ TerrenoMcpServiceToken: "McpServiceToken",
13
+ TerrenoMembership: "Membership",
14
+ TerrenoNotificationPreference: "NotificationPreference",
15
+ TerrenoOrganization: "Organization",
16
+ TerrenoWebhookReceipt: "WebhookReceipt",
17
+ } as const;
18
+
19
+ export type FrameworkModelCompiledName = keyof typeof FRAMEWORK_MODEL_PUBLIC_NAMES;
20
+
21
+ export type FrameworkModelPublicName =
22
+ (typeof FRAMEWORK_MODEL_PUBLIC_NAMES)[FrameworkModelCompiledName];
23
+
24
+ /**
25
+ * Admin UI keys and `admin<ModelName>` RBAC resources keep the pre-namespace names so
26
+ * consumer statements and `/admin/AuditEvent` routes stay stable.
27
+ */
28
+ export const publicFrameworkModelName = (modelName: string): string => {
29
+ if (modelName in FRAMEWORK_MODEL_PUBLIC_NAMES) {
30
+ return FRAMEWORK_MODEL_PUBLIC_NAMES[modelName as FrameworkModelCompiledName];
31
+ }
32
+ return modelName;
33
+ };
package/src/index.ts CHANGED
@@ -36,6 +36,7 @@ export * from "./authTokens";
36
36
  export * from "./betterAuth";
37
37
  export * from "./betterAuthApp";
38
38
  export * from "./betterAuthSetup";
39
+ export * from "./browserLogsRoute";
39
40
  export * from "./config";
40
41
  export * from "./configurationApp";
41
42
  export * from "./configurationPlugin";
@@ -43,6 +44,12 @@ export * from "./consentApp";
43
44
  export * from "./envConfigurationPlugin";
44
45
  export * from "./errors";
45
46
  export * from "./expressServer";
47
+ export {
48
+ FRAMEWORK_MODEL_PUBLIC_NAMES,
49
+ type FrameworkModelCompiledName,
50
+ type FrameworkModelPublicName,
51
+ publicFrameworkModelName,
52
+ } from "./frameworkModelNames";
46
53
  export * from "./githubAuth";
47
54
  export * from "./httpClient";
48
55
  export * from "./logger";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Isolated because `runMigrateCli` disconnects the default mongoose connection
3
+ * when it opens Mongo from a URI. Sharing that with the rest of `bun test` races
4
+ * org/notification/MCP suites.
5
+ */
6
+ import {describe, it} from "bun:test";
7
+ import {join} from "node:path";
8
+ import {assert} from "chai";
9
+ import mongoose from "mongoose";
10
+ import {runMigrateCli} from "../migrations/cli";
11
+ import {setupDb} from "../tests";
12
+
13
+ const fixtures = (...parts: string[]): string => {
14
+ return join(import.meta.dir, "..", "migrations", "fixtures", ...parts);
15
+ };
16
+
17
+ describe("runMigrateCli Mongo URI connect", () => {
18
+ it("connects and disconnects itself when given a Mongo URI", async () => {
19
+ await setupDb();
20
+ const {host, name, port} = mongoose.connection;
21
+ const uri = `mongodb://${host}:${port}/${name}`;
22
+ await mongoose.disconnect();
23
+ assert.equal(mongoose.connection.readyState, 0);
24
+
25
+ try {
26
+ const out: string[] = [];
27
+ const err: string[] = [];
28
+ const code = await runMigrateCli({
29
+ argv: ["status", "--dir", fixtures("valid")],
30
+ env: {MONGODB_URI: uri, NODE_ENV: "test"},
31
+ stderr: {
32
+ write: (chunk: string): void => {
33
+ err.push(chunk);
34
+ },
35
+ },
36
+ stdout: {
37
+ write: (chunk: string): void => {
38
+ out.push(chunk);
39
+ },
40
+ },
41
+ });
42
+ assert.equal(code, 0);
43
+ assert.include(out.join(""), "Applied (0)");
44
+ assert.include(out.join(""), "Pending (2)");
45
+ assert.equal(err.join(""), "");
46
+ assert.equal(mongoose.connection.readyState, 0);
47
+ } finally {
48
+ await mongoose.connect(uri);
49
+ }
50
+ });
51
+ });
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, expect, it} from "bun:test";
1
+ import {beforeEach, describe, expect, it, spyOn} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import jwt from "jsonwebtoken";
4
4
  import mongoose, {Schema} from "mongoose";
@@ -234,6 +234,39 @@ describe("extractUserFromHeaders", () => {
234
234
  expect(user).toBeUndefined();
235
235
  });
236
236
 
237
+ it("returns undefined when the JWT references a user that no longer exists", async () => {
238
+ const token = signToken({id: new mongoose.Types.ObjectId().toString()});
239
+
240
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
241
+
242
+ assert.isUndefined(user);
243
+ });
244
+
245
+ it("still resolves the MCP service token owner when the last-used update fails", async () => {
246
+ const created = await UserTestModel.create({email: "last-used-fails@example.com"});
247
+ const issued = await McpServiceToken.issueFor({_id: created._id}, {name: "Flaky"});
248
+ const updateSpy = spyOn(McpServiceToken, "updateOne").mockImplementation(
249
+ () =>
250
+ ({
251
+ catch: (handler: (error: unknown) => void) => {
252
+ handler(new Error("write failed"));
253
+ },
254
+ }) as unknown as ReturnType<typeof McpServiceToken.updateOne>
255
+ );
256
+
257
+ try {
258
+ const user = await extractUserFromHeaders(
259
+ {authorization: `Bearer ${issued.token}`},
260
+ {mcpServiceTokens: true, userModel}
261
+ );
262
+
263
+ assert.equal(String((user as unknown as MCPAuthUserFields)?._id), created._id.toString());
264
+ assert.equal(updateSpy.mock.calls.length, 1);
265
+ } finally {
266
+ updateSpy.mockRestore();
267
+ }
268
+ });
269
+
237
270
  it("returns undefined when Better Auth has no session and no JWT is present", async () => {
238
271
  const betterAuth = fakeBetterAuth(async () => null);
239
272
 
@@ -216,29 +216,6 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
216
216
  }
217
217
  });
218
218
 
219
- it("connects and disconnects itself when given a Mongo URI", async () => {
220
- const {host, name, port} = mongoose.connection;
221
- const uri = `mongodb://${host}:${port}/${name}`;
222
- await mongoose.disconnect();
223
- expect(mongoose.connection.readyState).toBe(0);
224
-
225
- try {
226
- const io = capture();
227
- const code = await runMigrateCli({
228
- argv: ["status", "--dir", fixtures("valid")],
229
- env: {MONGODB_URI: uri, NODE_ENV: "test"},
230
- stderr: {write: io.writeErr},
231
- stdout: {write: io.writeOut},
232
- });
233
- expect(code).toBe(0);
234
- expect(io.stdout).toContain("Applied (0)");
235
- expect(io.stdout).toContain("Pending (2)");
236
- expect(mongoose.connection.readyState).toBe(0);
237
- } finally {
238
- await mongoose.connect(uri);
239
- }
240
- });
241
-
242
219
  it("writes help to process stdout when io is omitted", async () => {
243
220
  expect(await runMigrateCli({argv: ["--help"]})).toBe(0);
244
221
  expect(await runMigrateCli({argv: ["nope"]})).toBe(1);
@@ -151,8 +151,9 @@ mcpServiceTokenSchema.statics = {
151
151
  };
152
152
 
153
153
  export const McpServiceToken =
154
- (mongoose.models.McpServiceToken as McpServiceTokenModel | undefined) ??
154
+ (mongoose.models.TerrenoMcpServiceToken as McpServiceTokenModel | undefined) ??
155
155
  mongoose.model<McpServiceTokenDocument, McpServiceTokenModel>(
156
- "McpServiceToken",
157
- mcpServiceTokenSchema
156
+ "TerrenoMcpServiceToken",
157
+ mcpServiceTokenSchema,
158
+ "mcpservicetokens"
158
159
  );