@terreno/api 57.4.0 → 57.6.1
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.
- package/README.md +5 -5
- package/bunfig.toml +1 -1
- package/dist/actions.js +197 -368
- package/dist/adminModelRouter.js +88 -173
- package/dist/api.js +617 -852
- package/dist/audit/auditApp.js +48 -89
- package/dist/audit/auditEventModel.js +15 -16
- package/dist/audit/cloudTasksEnqueue.js +56 -149
- package/dist/audit/diff.js +70 -160
- package/dist/audit/processQueue.js +25 -70
- package/dist/audit/rbacSink.js +25 -66
- package/dist/audit/record.js +129 -251
- package/dist/auth.js +432 -681
- package/dist/authRecovery.js +155 -269
- package/dist/authTokens.js +43 -118
- package/dist/betterAuthApp.js +25 -26
- package/dist/betterAuthSetup.js +258 -413
- package/dist/browserLogsRoute.d.ts +6 -0
- package/dist/browserLogsRoute.js +97 -0
- package/dist/collectionRegistry.js +32 -47
- package/dist/config.js +53 -122
- package/dist/configurationApp.js +180 -361
- package/dist/configurationPlugin.js +130 -302
- package/dist/consentApp.js +276 -421
- package/dist/docLoader.js +78 -126
- package/dist/envConfigurationPlugin.js +25 -147
- package/dist/errors.js +151 -247
- package/dist/example.js +28 -34
- package/dist/expressServer.d.ts +10 -0
- package/dist/expressServer.js +109 -255
- package/dist/frameworkModelNames.d.ts +24 -0
- package/dist/frameworkModelNames.js +31 -0
- package/dist/githubAuth.js +152 -216
- package/dist/httpClient.js +176 -264
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -2
- package/dist/logger.js +145 -278
- package/dist/mcp/auth.js +76 -128
- package/dist/mcp/createMCPRequest.js +4 -5
- package/dist/mcp/handlers.js +268 -480
- package/dist/mcp/query.js +56 -150
- package/dist/mcp/registry.js +17 -30
- package/dist/mcp/schemaGenerator.js +95 -181
- package/dist/mcp/server.js +28 -100
- package/dist/mcp/serviceTokens.js +102 -191
- package/dist/mcp/toolGenerator.js +78 -191
- package/dist/middleware.js +15 -27
- package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
- package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
- package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
- package/dist/migrations/generate.js +107 -229
- package/dist/migrations/load.js +75 -201
- package/dist/migrations/lock.js +54 -126
- package/dist/migrations/runner.js +192 -446
- package/dist/migrations/schemaCatalog.js +122 -263
- package/dist/models/consentForm.js +6 -6
- package/dist/models/consentResponse.js +5 -5
- package/dist/models/mcpServiceToken.js +66 -156
- package/dist/models/notification.js +6 -6
- package/dist/models/notificationPreference.js +6 -6
- package/dist/models/versionConfig.js +5 -5
- package/dist/notifications/notificationService.js +133 -273
- package/dist/notifications/notificationsApp.js +85 -179
- package/dist/notifications/notificationsBeforeSend.js +19 -64
- package/dist/notifiers/googleChatNotifier.js +36 -117
- package/dist/notifiers/slackNotifier.d.ts +31 -2
- package/dist/notifiers/slackNotifier.js +170 -119
- package/dist/notifiers/zoomNotifier.js +60 -111
- package/dist/openApi.js +107 -122
- package/dist/openApiBuilder.js +117 -159
- package/dist/openApiCompat.js +81 -148
- package/dist/openApiEtag.js +7 -7
- package/dist/openApiValidator.js +177 -286
- package/dist/orgs/orgContext.js +87 -157
- package/dist/orgs/orgPermissions.js +29 -68
- package/dist/orgs/orgPlugin.js +9 -27
- package/dist/orgs/organizationModel.js +65 -166
- package/dist/orgs/organizationSettings.js +29 -36
- package/dist/orgs/orgsApp.js +346 -608
- package/dist/permissions.js +88 -181
- package/dist/plugins.js +125 -218
- package/dist/populate.js +130 -240
- package/dist/rateLimit/applyTrustProxy.js +1 -1
- package/dist/rateLimit/createStore.js +7 -8
- package/dist/rateLimit/memoryStore.js +22 -100
- package/dist/rateLimit/middleware.js +48 -99
- package/dist/rateLimit/mongoStore.js +54 -112
- package/dist/rateLimit/policies.js +41 -75
- package/dist/rateLimit/redisStore.js +39 -133
- package/dist/rbac/access.js +119 -267
- package/dist/rbac/assertAllowed.js +95 -171
- package/dist/rbac/auditModel.js +14 -58
- package/dist/rbac/backfillAdmins.js +24 -130
- package/dist/rbac/fieldViews.js +46 -141
- package/dist/rbac/membershipOrgAdminSource.js +28 -99
- package/dist/rbac/middleware.js +30 -96
- package/dist/rbac/modelRouterAccess.js +130 -307
- package/dist/rbac/permissionUtils.js +40 -179
- package/dist/rbac/realtimeAccess.js +81 -147
- package/dist/rbac/resolve.d.ts +1 -1
- package/dist/rbac/resolve.js +148 -342
- package/dist/rbac/roleManager.js +318 -700
- package/dist/rbac/roleModel.js +44 -171
- package/dist/rbac/routes.js +93 -196
- package/dist/rbac/scopes.js +39 -133
- package/dist/rbac/statements.js +23 -91
- package/dist/rbac/userPlugin.js +3 -29
- package/dist/realtime/changeStreamWatcher.js +489 -800
- package/dist/realtime/deprecation.js +8 -10
- package/dist/realtime/queryMatcher.js +110 -191
- package/dist/realtime/queryStore.js +35 -118
- package/dist/realtime/realtimeApp.js +247 -401
- package/dist/realtime/registry.js +19 -30
- package/dist/realtime/sessionRevalidation.js +132 -358
- package/dist/realtime/socketAuth.js +89 -208
- package/dist/realtime/socketUser.js +10 -56
- package/dist/requestContext.js +93 -139
- package/dist/schemaMetadata.js +179 -274
- package/dist/scriptRunner.js +96 -266
- package/dist/scrubAdminFields.js +36 -108
- package/dist/secretProviders.js +130 -299
- package/dist/seedRunner.js +221 -514
- package/dist/sync/adminBroadcastScope.js +58 -170
- package/dist/sync/adminWindowAccess.js +15 -86
- package/dist/sync/adminWindowMutation.js +110 -181
- package/dist/sync/executors.js +425 -629
- package/dist/sync/loadHarness.js +392 -689
- package/dist/sync/models.js +181 -341
- package/dist/sync/mutationHandler.js +533 -801
- package/dist/sync/registrationSideEffects.js +41 -95
- package/dist/sync/registry.js +29 -49
- package/dist/sync/routes.js +484 -817
- package/dist/sync/scripts/compactTombstones.js +83 -228
- package/dist/sync/serialize.js +18 -58
- package/dist/sync/socketHandlers.js +253 -478
- package/dist/sync/streams.js +49 -117
- package/dist/sync/syncApp.js +12 -15
- package/dist/sync/syncBatch.js +63 -168
- package/dist/sync/syncSeqPlugin.js +430 -702
- package/dist/syncConsents.js +113 -253
- package/dist/terrenoApp.js +166 -276
- package/dist/tests/createTestData.js +146 -256
- package/dist/tests/models.js +14 -54
- package/dist/tests/mongoTestSetup.js +42 -103
- package/dist/tests/testHelper.js +31 -93
- package/dist/tests.js +12 -51
- package/dist/transformers.js +61 -164
- package/dist/utils.js +31 -93
- package/dist/vendor/wesleytodd-openapi/index.js +37 -51
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
- package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
- package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
- package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
- package/dist/versionCheckPlugin.js +52 -100
- package/dist/webhooks/headerValue.js +2 -2
- package/dist/webhooks/idempotency/memoryStore.js +16 -59
- package/dist/webhooks/idempotency/mongoStore.js +55 -130
- package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
- package/dist/webhooks/rawBody.js +1 -1
- package/dist/webhooks/timingSafeEqual.js +4 -5
- package/dist/webhooks/verifiers/hmac.js +17 -18
- package/dist/webhooks/verifiers/sendgrid.js +20 -22
- package/dist/webhooks/verifiers/stripe.js +31 -65
- package/dist/webhooks/verifiers/twilio.js +23 -73
- package/dist/webhooks/webhooksApp.js +78 -177
- package/dist/zodOpenApi.js +2 -2
- package/package.json +6 -6
- package/src/__tests__/browserLogsRoute.test.ts +165 -0
- package/src/api.arrayOperations.test.ts +44 -0
- package/src/api.ts +64 -39
- package/src/audit/auditApp.test.ts +5 -5
- package/src/audit/auditEventModel.ts +7 -3
- package/src/audit/auditRouter.test.ts +5 -5
- package/src/audit/rbacSink.test.ts +2 -2
- package/src/audit/record.test.ts +2 -2
- package/src/audit/record.ts +3 -2
- package/src/auth.ts +1 -1
- package/src/authRecovery.test.ts +43 -0
- package/src/authRecovery.ts +16 -10
- package/src/authTokens.ts +6 -2
- package/src/authVerification.test.ts +22 -0
- package/src/browserLogsRoute.ts +110 -0
- package/src/configurationPlugin.test.ts +1 -11
- package/src/expressServer.ts +10 -0
- package/src/frameworkModelNames.test.ts +62 -0
- package/src/frameworkModelNames.ts +33 -0
- package/src/index.ts +7 -0
- package/src/isolated/migrateCliConnect.isolated.ts +51 -0
- package/src/mcp/auth.test.ts +34 -1
- package/src/migrations/cli.test.ts +0 -23
- package/src/models/mcpServiceToken.ts +4 -3
- package/src/models/notification.ts +3 -2
- package/src/models/notificationPreference.ts +1 -1
- package/src/notifications/notificationsApp.test.ts +24 -1
- package/src/notifiers/slackNotifier.test.ts +186 -1
- package/src/notifiers/slackNotifier.ts +167 -8
- package/src/orgs/orgPlugin.ts +1 -1
- package/src/orgs/organizationModel.ts +11 -6
- package/src/plugins.test.ts +5 -0
- package/src/plugins.ts +3 -0
- package/src/realtime/realtimeApp.ts +1 -1
- package/src/sync/integration.test.ts +2 -2
- package/src/terrenoApp.ts +3 -0
- package/src/types.d.ts +1 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
- package/tsconfig.json +13 -54
- package/tsconfig.typedoc.json +2 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
2
3
|
import type express from "express";
|
|
3
4
|
import supertest from "supertest";
|
|
4
5
|
import type TestAgent from "supertest/lib/agent";
|
|
@@ -422,6 +423,49 @@ describe("array operation errors", () => {
|
|
|
422
423
|
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
423
424
|
});
|
|
424
425
|
|
|
426
|
+
it("rejects array operations on non-array fields with a structured error", async () => {
|
|
427
|
+
app.use(
|
|
428
|
+
"/food",
|
|
429
|
+
modelRouter(FoodModel, {
|
|
430
|
+
allowAnonymous: true,
|
|
431
|
+
permissions: {
|
|
432
|
+
create: [Permissions.IsAdmin],
|
|
433
|
+
delete: [Permissions.IsAdmin],
|
|
434
|
+
list: [Permissions.IsAdmin],
|
|
435
|
+
read: [Permissions.IsAdmin],
|
|
436
|
+
update: [Permissions.IsAdmin],
|
|
437
|
+
},
|
|
438
|
+
})
|
|
439
|
+
);
|
|
440
|
+
agent = await authAsUser(app, "admin");
|
|
441
|
+
|
|
442
|
+
const res = await agent.post(`/food/${apple._id}/name`).send({name: "Pear"}).expect(400);
|
|
443
|
+
assert.equal(res.body.code, "array-operation-field-not-array");
|
|
444
|
+
assert.equal(res.body.title, "Array operation field is not an array");
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
it("runs preUpdate before rejecting a non-array field", async () => {
|
|
448
|
+
app.use(
|
|
449
|
+
"/food",
|
|
450
|
+
modelRouter(FoodModel, {
|
|
451
|
+
allowAnonymous: true,
|
|
452
|
+
permissions: {
|
|
453
|
+
create: [Permissions.IsAdmin],
|
|
454
|
+
delete: [Permissions.IsAdmin],
|
|
455
|
+
list: [Permissions.IsAdmin],
|
|
456
|
+
read: [Permissions.IsAdmin],
|
|
457
|
+
update: [Permissions.IsAdmin],
|
|
458
|
+
},
|
|
459
|
+
preUpdate: () => null,
|
|
460
|
+
})
|
|
461
|
+
);
|
|
462
|
+
agent = await authAsUser(app, "admin");
|
|
463
|
+
|
|
464
|
+
const res = await agent.post(`/food/${apple._id}/name`).send({name: "Pear"}).expect(403);
|
|
465
|
+
assert.equal(res.body.code, "update-not-allowed");
|
|
466
|
+
assert.equal(res.body.title, "Update not allowed");
|
|
467
|
+
});
|
|
468
|
+
|
|
425
469
|
it("array operation preUpdate returning undefined throws error", async () => {
|
|
426
470
|
app.use(
|
|
427
471
|
"/food",
|
package/src/api.ts
CHANGED
|
@@ -1152,6 +1152,57 @@ const _buildModelRouter = <T>(
|
|
|
1152
1152
|
})
|
|
1153
1153
|
);
|
|
1154
1154
|
|
|
1155
|
+
/**
|
|
1156
|
+
* Applies consumer update transforms and authorization hooks for array subroutes.
|
|
1157
|
+
* Keeping this pipeline shared ensures invalid field requests cannot bypass consumer
|
|
1158
|
+
* authorization before modelRouter returns its own validation error.
|
|
1159
|
+
*/
|
|
1160
|
+
const applyArrayOperationUpdateHooks = async (
|
|
1161
|
+
inputBody: Partial<T>,
|
|
1162
|
+
req: Request
|
|
1163
|
+
): Promise<Partial<T>> => {
|
|
1164
|
+
let body: Partial<T> | null = inputBody;
|
|
1165
|
+
|
|
1166
|
+
try {
|
|
1167
|
+
body = transform<T>(options, body, "update", req.user) as Partial<T>;
|
|
1168
|
+
} catch (error: unknown) {
|
|
1169
|
+
throw passthroughOrWrap(error, {
|
|
1170
|
+
code: "transform-error",
|
|
1171
|
+
status: 403,
|
|
1172
|
+
title: "Transform error",
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
if (options.preUpdate) {
|
|
1177
|
+
try {
|
|
1178
|
+
body = await options.preUpdate(body, req);
|
|
1179
|
+
} catch (error: unknown) {
|
|
1180
|
+
throw passthroughOrWrap(error, {
|
|
1181
|
+
code: "pre-update-hook-error",
|
|
1182
|
+
detail: `preUpdate hook error on ${req.params.id}: ${errorDetail(error)}`,
|
|
1183
|
+
status: 400,
|
|
1184
|
+
title: "preUpdate hook error",
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
if (body === undefined) {
|
|
1188
|
+
throw new ForbiddenError({
|
|
1189
|
+
code: "update-not-allowed",
|
|
1190
|
+
detail: "A body must be returned from preUpdate",
|
|
1191
|
+
title: "Update not allowed",
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
if (body === null) {
|
|
1195
|
+
throw new ForbiddenError({
|
|
1196
|
+
code: "update-not-allowed",
|
|
1197
|
+
detail: `preUpdate hook on ${req.params.id} returned null`,
|
|
1198
|
+
title: "Update not allowed",
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
return body;
|
|
1204
|
+
};
|
|
1205
|
+
|
|
1155
1206
|
const arrayOperation = async (
|
|
1156
1207
|
req: Request,
|
|
1157
1208
|
res: Response,
|
|
@@ -1206,7 +1257,18 @@ const _buildModelRouter = <T>(
|
|
|
1206
1257
|
});
|
|
1207
1258
|
}
|
|
1208
1259
|
|
|
1209
|
-
const
|
|
1260
|
+
const currentFieldValue = (doc as unknown as Record<string, unknown>)[field];
|
|
1261
|
+
if (!Array.isArray(currentFieldValue)) {
|
|
1262
|
+
await applyArrayOperationUpdateHooks(req.body as Partial<T>, req);
|
|
1263
|
+
throw new BadRequestError({
|
|
1264
|
+
code: "array-operation-field-not-array",
|
|
1265
|
+
detail: `Cannot apply an array operation to non-array field ${field}`,
|
|
1266
|
+
meta: {field},
|
|
1267
|
+
title: "Array operation field is not an array",
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
const array = [...currentFieldValue];
|
|
1210
1272
|
if (operation === "POST") {
|
|
1211
1273
|
array.push(req.body[field]);
|
|
1212
1274
|
} else if (operation === "PATCH" || operation === "DELETE") {
|
|
@@ -1243,44 +1305,7 @@ const _buildModelRouter = <T>(
|
|
|
1243
1305
|
title: "Invalid array operation",
|
|
1244
1306
|
});
|
|
1245
1307
|
}
|
|
1246
|
-
let body
|
|
1247
|
-
|
|
1248
|
-
try {
|
|
1249
|
-
body = transform<T>(options, body, "update", req.user) as Partial<T>;
|
|
1250
|
-
} catch (error: unknown) {
|
|
1251
|
-
throw passthroughOrWrap(error, {
|
|
1252
|
-
code: "transform-error",
|
|
1253
|
-
status: 403,
|
|
1254
|
-
title: "Transform error",
|
|
1255
|
-
});
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
if (options.preUpdate) {
|
|
1259
|
-
try {
|
|
1260
|
-
body = await options.preUpdate(body, req);
|
|
1261
|
-
} catch (error: unknown) {
|
|
1262
|
-
throw passthroughOrWrap(error, {
|
|
1263
|
-
code: "pre-update-hook-error",
|
|
1264
|
-
detail: `preUpdate hook error on ${req.params.id}: ${errorDetail(error)}`,
|
|
1265
|
-
status: 400,
|
|
1266
|
-
title: "preUpdate hook error",
|
|
1267
|
-
});
|
|
1268
|
-
}
|
|
1269
|
-
if (body === undefined) {
|
|
1270
|
-
throw new ForbiddenError({
|
|
1271
|
-
code: "update-not-allowed",
|
|
1272
|
-
detail: "A body must be returned from preUpdate",
|
|
1273
|
-
title: "Update not allowed",
|
|
1274
|
-
});
|
|
1275
|
-
}
|
|
1276
|
-
if (body === null) {
|
|
1277
|
-
throw new ForbiddenError({
|
|
1278
|
-
code: "update-not-allowed",
|
|
1279
|
-
detail: `preUpdate hook on ${req.params.id} returned null`,
|
|
1280
|
-
title: "Update not allowed",
|
|
1281
|
-
});
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1308
|
+
let body = await applyArrayOperationUpdateHooks({[field]: array} as unknown as Partial<T>, req);
|
|
1284
1309
|
|
|
1285
1310
|
body = omitUserRolesFromWriteBody(
|
|
1286
1311
|
model.modelName,
|
|
@@ -15,8 +15,8 @@ import {resetAuditRecorderForTests} from "./record";
|
|
|
15
15
|
const typedUserModel = UserModel as unknown as AuthUserModel;
|
|
16
16
|
|
|
17
17
|
const deleteAuditEventModel = (): void => {
|
|
18
|
-
if (mongoose.connection.models.
|
|
19
|
-
mongoose.connection.deleteModel("
|
|
18
|
+
if (mongoose.connection.models.TerrenoAuditEvent) {
|
|
19
|
+
mongoose.connection.deleteModel("TerrenoAuditEvent");
|
|
20
20
|
}
|
|
21
21
|
};
|
|
22
22
|
|
|
@@ -49,7 +49,7 @@ describe("AuditApp", () => {
|
|
|
49
49
|
it("does not register AuditEvent on the default connection when @terreno/api is imported", async () => {
|
|
50
50
|
deleteAuditEventModel();
|
|
51
51
|
await import("../index");
|
|
52
|
-
assert.isUndefined(mongoose.connection.models.
|
|
52
|
+
assert.isUndefined(mongoose.connection.models.TerrenoAuditEvent);
|
|
53
53
|
});
|
|
54
54
|
|
|
55
55
|
it("lets an admin list an empty audit log", async () => {
|
|
@@ -123,14 +123,14 @@ describe("AuditApp", () => {
|
|
|
123
123
|
it("does not add a TTL index by default", () => {
|
|
124
124
|
deleteAuditEventModel();
|
|
125
125
|
createAuditEventModel(mongoose.connection);
|
|
126
|
-
const indexes = mongoose.connection.models.
|
|
126
|
+
const indexes = mongoose.connection.models.TerrenoAuditEvent.schema.indexes();
|
|
127
127
|
assert.isFalse(indexes.some(([, options]) => options && "expireAfterSeconds" in options));
|
|
128
128
|
});
|
|
129
129
|
|
|
130
130
|
it("adds a TTL index on created when retentionDays is greater than 0", () => {
|
|
131
131
|
deleteAuditEventModel();
|
|
132
132
|
createAuditEventModel(mongoose.connection, {retentionDays: 1});
|
|
133
|
-
const indexes = mongoose.connection.models.
|
|
133
|
+
const indexes = mongoose.connection.models.TerrenoAuditEvent.schema.indexes();
|
|
134
134
|
const createdAsc = indexes.filter(
|
|
135
135
|
([fields]) => (fields as {created?: number}).created === 1 && Object.keys(fields).length === 1
|
|
136
136
|
);
|
|
@@ -144,13 +144,17 @@ export const createAuditEventModel = (
|
|
|
144
144
|
connection: mongoose.Connection,
|
|
145
145
|
options: {retentionDays?: number} = {}
|
|
146
146
|
): AuditEventModel => {
|
|
147
|
-
if (connection.models.
|
|
148
|
-
return connection.models.
|
|
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>(
|
|
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("
|
|
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("
|
|
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.
|
|
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("
|
|
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("
|
|
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.
|
|
16
|
-
mongoose.connection.deleteModel("
|
|
15
|
+
if (mongoose.connection.models.TerrenoAuditEvent) {
|
|
16
|
+
mongoose.connection.deleteModel("TerrenoAuditEvent");
|
|
17
17
|
}
|
|
18
18
|
};
|
|
19
19
|
|
package/src/audit/record.test.ts
CHANGED
|
@@ -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.
|
|
28
|
-
mongoose.connection.deleteModel("
|
|
27
|
+
if (mongoose.connection.models.TerrenoAuditEvent) {
|
|
28
|
+
mongoose.connection.deleteModel("TerrenoAuditEvent");
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
31
|
|
package/src/audit/record.ts
CHANGED
|
@@ -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
|
|
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
|
|
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) {
|
package/src/authRecovery.test.ts
CHANGED
|
@@ -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({
|
package/src/authRecovery.ts
CHANGED
|
@@ -265,15 +265,21 @@ export const addAuthRecoveryRoutes = (
|
|
|
265
265
|
.build();
|
|
266
266
|
|
|
267
267
|
const router = express.Router();
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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
|
-
|
|
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.
|
|
118
|
-
mongoose.model<AuthTokenDocument, AuthTokenModel>(
|
|
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 {
|
|
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;
|
package/src/expressServer.ts
CHANGED
|
@@ -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
|
/**
|