@terreno/api 57.20.0 → 58.0.0-beta.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/CHANGELOG.md +93 -0
- package/README.md +1 -1
- package/biome.jsonc +3 -2
- package/dist/api.d.ts +3 -16
- package/dist/api.js +0 -9
- package/dist/auth.d.ts +3 -2
- package/dist/auth.js +95 -5
- package/dist/authRecovery.d.ts +2 -1
- package/dist/authRecovery.js +35 -17
- package/dist/collectionRegistry.d.ts +3 -4
- package/dist/collectionRegistry.js +0 -1
- package/dist/consentApp.d.ts +1 -1
- package/dist/consentApp.js +58 -2
- package/dist/frameworkModelNames.d.ts +4 -0
- package/dist/frameworkModelNames.js +4 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +14 -20
- package/dist/mcp/adminTracking.d.ts +28 -0
- package/dist/mcp/adminTracking.js +80 -0
- package/dist/mcp/auth.d.ts +6 -0
- package/dist/mcp/auth.js +12 -2
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +48 -4
- package/dist/mcp/serviceTokens.d.ts +21 -1
- package/dist/mcp/serviceTokens.js +159 -183
- package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
- package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
- package/dist/models/mcpOAuthToken.js +27 -0
- package/dist/models/mcpRequestLog.d.ts +2 -0
- package/dist/models/mcpRequestLog.js +73 -0
- package/dist/models/mcpServiceToken.js +40 -4
- package/dist/models/mcpToolSetting.d.ts +2 -0
- package/dist/models/mcpToolSetting.js +119 -0
- package/dist/models/versionConfig.d.ts +2 -0
- package/dist/openApiBuilder.d.ts +4 -0
- package/dist/openApiBuilder.js +2 -0
- package/dist/rbac/auditModel.d.ts +2 -1
- package/dist/rbac/realtimeAccess.d.ts +5 -4
- package/dist/rbac/realtimeAccess.js +17 -64
- package/dist/realtime/changeStreamWatcher.d.ts +8 -63
- package/dist/realtime/changeStreamWatcher.js +32 -391
- package/dist/realtime/realtimeApp.d.ts +14 -27
- package/dist/realtime/realtimeApp.js +14 -220
- package/dist/realtime/types.d.ts +0 -64
- package/dist/sync/executors.js +14 -2
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/socketHandlers.js +1 -1
- package/dist/terrenoApp.d.ts +19 -5
- package/dist/terrenoApp.js +21 -14
- package/dist/tests/models.d.ts +17 -22
- package/dist/tests/models.js +7 -1
- package/dist/tests/openApiResponseSchema.d.ts +39 -0
- package/dist/tests/openApiResponseSchema.js +56 -0
- package/dist/tests/testHelper.d.ts +6 -12
- package/dist/tests.d.ts +2 -0
- package/dist/tests.js +6 -1
- package/dist/types/mcpAdmin.d.ts +58 -0
- package/dist/types/mcpAdmin.js +2 -0
- package/dist/types/mcpOAuth.d.ts +2 -0
- package/dist/types/mcpServiceToken.d.ts +9 -4
- package/dist/versionCheckPlugin.d.ts +1 -1
- package/dist/versionCheckPlugin.js +25 -2
- package/e2e/smoke.ts +193 -0
- package/package.json +14 -8
- package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
- package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
- package/src/__tests__/openApiResponseSchema.test.ts +148 -0
- package/src/__tests__/versionCheckPlugin.test.ts +72 -0
- package/src/adminModelRouter.test.ts +8 -6
- package/src/api.arrayOperations.test.ts +31 -22
- package/src/api.hooks.test.ts +12 -11
- package/src/api.query.test.ts +2 -2
- package/src/api.test.ts +17 -14
- package/src/api.ts +3 -27
- package/src/audit/auditApp.test.ts +1 -1
- package/src/audit/cloudTasksEnqueue.test.ts +19 -14
- package/src/auth.test.ts +21 -7
- package/src/auth.ts +116 -5
- package/src/authOpenApi.test.ts +316 -0
- package/src/authRecovery.test.ts +10 -10
- package/src/authRecovery.ts +47 -19
- package/src/authVerification.test.ts +7 -7
- package/src/betterAuthFeatures.test.ts +3 -2
- package/src/betterAuthLinking.test.ts +3 -1
- package/src/betterAuthOAuthHandoff.test.ts +13 -5
- package/src/betterAuthSetup.test.ts +77 -51
- package/src/collectionRegistry.test.ts +4 -4
- package/src/collectionRegistry.ts +3 -5
- package/src/consentApp.test.ts +98 -0
- package/src/consentApp.ts +67 -2
- package/src/frameworkModelNames.test.ts +8 -0
- package/src/frameworkModelNames.ts +4 -0
- package/src/githubAuth.test.ts +11 -11
- package/src/index.ts +14 -28
- package/src/isolated/migrateCliConnect.isolated.ts +3 -2
- package/src/mcp/actionTools.test.ts +13 -7
- package/src/mcp/adminTracking.test.ts +272 -0
- package/src/mcp/adminTracking.ts +104 -0
- package/src/mcp/auth.test.ts +7 -3
- package/src/mcp/auth.ts +18 -2
- package/src/mcp/oauth.test.ts +13 -13
- package/src/mcp/server.ts +67 -4
- package/src/mcp/serviceTokens.sync.test.ts +230 -0
- package/src/mcp/serviceTokens.test.ts +114 -62
- package/src/mcp/serviceTokens.ts +193 -212
- package/src/mcp/toolGenerator.test.ts +9 -5
- package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
- package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
- package/src/migrations/cli.test.ts +15 -14
- package/src/migrations/cli.ts +1 -1
- package/src/migrations/generate.test.ts +2 -2
- package/src/migrations/load.test.ts +1 -1
- package/src/migrations/lock.test.ts +8 -3
- package/src/migrations/runner.test.ts +16 -5
- package/src/migrations/schemaCatalog.test.ts +4 -1
- package/src/models/mcpOAuthToken.test.ts +42 -0
- package/src/models/mcpOAuthToken.ts +32 -0
- package/src/models/mcpRequestLog.ts +81 -0
- package/src/models/mcpServiceToken.test.ts +75 -5
- package/src/models/mcpServiceToken.ts +61 -14
- package/src/models/mcpToolSetting.test.ts +69 -0
- package/src/models/mcpToolSetting.ts +138 -0
- package/src/models/versionConfig.ts +2 -0
- package/src/notifications/notificationsApp.test.ts +5 -8
- package/src/notifiers/slackWebApi.test.ts +30 -8
- package/src/openApi.test.ts +4 -4
- package/src/openApiBuilder.test.ts +34 -1
- package/src/openApiBuilder.ts +5 -0
- package/src/openApiValidator.test.ts +3 -3
- package/src/orgs/orgPermissions.test.ts +2 -2
- package/src/orgs/orgPlugin.test.ts +4 -3
- package/src/orgs/orgSecurityDefects.test.ts +3 -1
- package/src/orgs/organizationSettings.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +5 -3
- package/src/permissions.test.ts +2 -2
- package/src/rateLimit/rateLimit.test.ts +25 -10
- package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
- package/src/rbac/assertAllowed.test.ts +1 -1
- package/src/rbac/auditModel.ts +10 -2
- package/src/rbac/realtimeAccess.test.ts +20 -171
- package/src/rbac/realtimeAccess.ts +17 -82
- package/src/rbac/routes.test.ts +1 -1
- package/src/rbac/userWriteGuards.test.ts +8 -5
- package/src/realtime/changeStreamWatcher.ts +43 -506
- package/src/realtime/realtime.test.ts +211 -2547
- package/src/realtime/realtimeApp.ts +16 -295
- package/src/realtime/types.ts +0 -72
- package/src/scrubAdminFields.test.ts +1 -1
- package/src/sync/adminWindowMutation.test.ts +4 -3
- package/src/sync/executors.test.ts +29 -1
- package/src/sync/executors.ts +23 -2
- package/src/sync/scripts/compactTombstones.test.ts +4 -3
- package/src/sync/socketHandlers.ts +1 -1
- package/src/sync/sync.test.ts +1 -1
- package/src/sync/syncPhaseC.test.ts +14 -11
- package/src/sync/syncRoutes.test.ts +8 -8
- package/src/sync/syncSeqPlugin.test.ts +1 -2
- package/src/sync/syncSocket.test.ts +78 -113
- package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
- package/src/terrenoApp.migrations.test.ts +8 -7
- package/src/terrenoApp.ts +38 -18
- package/src/tests/betterAuthStubs.ts +3 -2
- package/src/tests/bunSetup.ts +1 -1
- package/src/tests/models.ts +10 -0
- package/src/tests/openApiResponseSchema.ts +104 -0
- package/src/tests/testEnv.ts +7 -0
- package/src/tests.ts +8 -0
- package/src/types/mcpAdmin.ts +80 -0
- package/src/types/mcpOAuth.ts +5 -0
- package/src/types/mcpServiceToken.ts +12 -4
- package/src/versionCheckPlugin.ts +41 -2
- package/src/webhooks/verifiers/hmac.test.ts +1 -1
- package/tsconfig.typecheck.json +14 -0
- package/dist/realtime/deprecation.d.ts +0 -13
- package/dist/realtime/deprecation.js +0 -31
- package/dist/realtime/queryStore.d.ts +0 -37
- package/dist/realtime/queryStore.js +0 -103
- package/dist/realtime/registry.d.ts +0 -15
- package/dist/realtime/registry.js +0 -52
- package/src/realtime/deprecation.test.ts +0 -60
- package/src/realtime/deprecation.ts +0 -33
- package/src/realtime/queryStore.ts +0 -122
- package/src/realtime/registry.ts +0 -84
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
expectDocumentedResponse,
|
|
5
|
+
type OpenApiResponseSpec,
|
|
6
|
+
validateDocumentedResponse,
|
|
7
|
+
} from "../tests/openApiResponseSchema";
|
|
8
|
+
|
|
9
|
+
const spec: OpenApiResponseSpec = {
|
|
10
|
+
components: {
|
|
11
|
+
schemas: {
|
|
12
|
+
Tag: {
|
|
13
|
+
properties: {label: {type: "string"}},
|
|
14
|
+
required: ["label"],
|
|
15
|
+
type: "object",
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
paths: {
|
|
20
|
+
"/items/{id}": {
|
|
21
|
+
get: {
|
|
22
|
+
responses: {
|
|
23
|
+
"200": {
|
|
24
|
+
content: {
|
|
25
|
+
"application/json": {
|
|
26
|
+
schema: {
|
|
27
|
+
properties: {
|
|
28
|
+
data: {
|
|
29
|
+
properties: {
|
|
30
|
+
created: {format: "date-time", type: "string"},
|
|
31
|
+
note: {nullable: true, type: "string"},
|
|
32
|
+
tags: {items: {$ref: "#/components/schemas/Tag"}, type: "array"},
|
|
33
|
+
},
|
|
34
|
+
required: ["tags"],
|
|
35
|
+
type: "object",
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
required: ["data"],
|
|
39
|
+
type: "object",
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
"204": {description: "No content"},
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
"/plain": {get: {}},
|
|
49
|
+
},
|
|
50
|
+
} as unknown as OpenApiResponseSpec;
|
|
51
|
+
|
|
52
|
+
const valid = {
|
|
53
|
+
data: {created: "2026-01-02T03:04:05.000Z", note: null, tags: [{label: "a"}]},
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
describe("validateDocumentedResponse", () => {
|
|
57
|
+
it("accepts a body that matches the documented schema, refs and nullable included", () => {
|
|
58
|
+
const result = validateDocumentedResponse({
|
|
59
|
+
method: "GET",
|
|
60
|
+
path: "/items/{id}",
|
|
61
|
+
response: {body: valid, status: 200},
|
|
62
|
+
spec,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
expect(result).toEqual({errors: [], valid: true});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("reports every violation with its JSON pointer, following component refs", () => {
|
|
69
|
+
const result = validateDocumentedResponse({
|
|
70
|
+
method: "get",
|
|
71
|
+
path: "/items/{id}",
|
|
72
|
+
response: {body: {data: {created: "yesterday", tags: [{}]}}, status: 200},
|
|
73
|
+
spec,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
expect(result.valid).toBe(false);
|
|
77
|
+
expect(result.errors).toEqual(
|
|
78
|
+
expect.arrayContaining([
|
|
79
|
+
'/data/created must match format "date-time"',
|
|
80
|
+
"/data/tags/0 must have required property 'label'",
|
|
81
|
+
])
|
|
82
|
+
);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("labels root-level violations", () => {
|
|
86
|
+
const result = validateDocumentedResponse({
|
|
87
|
+
method: "get",
|
|
88
|
+
path: "/items/{id}",
|
|
89
|
+
response: {body: {}, status: 200},
|
|
90
|
+
spec,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
expect(result.errors).toEqual(["(root) must have required property 'data'"]);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("throws when the route, status, or media type is not documented", () => {
|
|
97
|
+
const check = (path: string, status: number, contentType?: string): (() => unknown) => {
|
|
98
|
+
return () =>
|
|
99
|
+
validateDocumentedResponse({
|
|
100
|
+
contentType,
|
|
101
|
+
method: "get",
|
|
102
|
+
path,
|
|
103
|
+
response: {body: {}, status},
|
|
104
|
+
spec,
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
expect(check("/missing", 200)).toThrow("GET /missing is not documented in the OpenAPI spec");
|
|
109
|
+
expect(check("/items/{id}", 404)).toThrow(
|
|
110
|
+
"GET /items/{id} has no documented 404 response (documented: 200, 204)"
|
|
111
|
+
);
|
|
112
|
+
expect(check("/plain", 200)).toThrow(
|
|
113
|
+
"GET /plain has no documented 200 response (documented: none)"
|
|
114
|
+
);
|
|
115
|
+
expect(check("/items/{id}", 204)).toThrow(
|
|
116
|
+
"GET /items/{id} 204 response has no application/json schema"
|
|
117
|
+
);
|
|
118
|
+
expect(check("/items/{id}", 200, "text/csv")).toThrow(
|
|
119
|
+
"GET /items/{id} 200 response has no text/csv schema"
|
|
120
|
+
);
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
describe("expectDocumentedResponse", () => {
|
|
125
|
+
it("passes silently for a documented body", () => {
|
|
126
|
+
expect(() =>
|
|
127
|
+
expectDocumentedResponse({
|
|
128
|
+
method: "get",
|
|
129
|
+
path: "/items/{id}",
|
|
130
|
+
response: {body: valid, status: 200},
|
|
131
|
+
spec,
|
|
132
|
+
})
|
|
133
|
+
).not.toThrow();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("throws with the violations and the body", () => {
|
|
137
|
+
expect(() =>
|
|
138
|
+
expectDocumentedResponse({
|
|
139
|
+
method: "get",
|
|
140
|
+
path: "/items/{id}",
|
|
141
|
+
response: {body: {data: {tags: "nope"}}, status: 200},
|
|
142
|
+
spec,
|
|
143
|
+
})
|
|
144
|
+
).toThrow(
|
|
145
|
+
'GET /items/{id} 200 response does not match its OpenAPI schema:\n- /data/tags must be array\nBody: {"data":{"tags":"nope"}}'
|
|
146
|
+
);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
@@ -3,8 +3,10 @@ import {assert} from "chai";
|
|
|
3
3
|
import supertest from "supertest";
|
|
4
4
|
import type {UserModel as UserModelType} from "../auth";
|
|
5
5
|
import {VersionConfig} from "../models/versionConfig";
|
|
6
|
+
import {configureOpenApiValidator, resetOpenApiValidatorConfig} from "../openApiValidator";
|
|
6
7
|
import {TerrenoApp} from "../terrenoApp";
|
|
7
8
|
import {setupDb, UserModel} from "../tests";
|
|
9
|
+
import {expectDocumentedResponse} from "../tests/openApiResponseSchema";
|
|
8
10
|
import {VersionCheckPlugin} from "../versionCheckPlugin";
|
|
9
11
|
|
|
10
12
|
const typedUserModel = UserModel as unknown as UserModelType;
|
|
@@ -353,3 +355,73 @@ describe("VersionCheckPlugin direct usage", () => {
|
|
|
353
355
|
expect(res.body.status).toBe("required");
|
|
354
356
|
});
|
|
355
357
|
});
|
|
358
|
+
|
|
359
|
+
describe("VersionCheckPlugin OpenAPI", () => {
|
|
360
|
+
const buildApp = (): ReturnType<TerrenoApp["build"]> =>
|
|
361
|
+
new TerrenoApp({skipListen: true, userModel: typedUserModel})
|
|
362
|
+
.register(new VersionCheckPlugin())
|
|
363
|
+
.build();
|
|
364
|
+
|
|
365
|
+
beforeEach(async () => {
|
|
366
|
+
await setupDb();
|
|
367
|
+
await VersionConfig.deleteMany({});
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
it("documents GET /version-check in /openapi.json", async () => {
|
|
371
|
+
const res = await supertest(buildApp()).get("/openapi.json").expect(200);
|
|
372
|
+
const operation = res.body.paths["/version-check"]?.get;
|
|
373
|
+
expect(operation).toBeDefined();
|
|
374
|
+
const parameters = operation.parameters as {in: string; name: string; schema: unknown}[];
|
|
375
|
+
expect(parameters.map((parameter) => `${parameter.in}:${parameter.name}`)).toEqual([
|
|
376
|
+
"query:platform",
|
|
377
|
+
"query:version",
|
|
378
|
+
]);
|
|
379
|
+
expect(parameters[0]?.schema).toEqual({enum: ["web", "mobile"], type: "string"});
|
|
380
|
+
const schema = operation.responses["200"].content["application/json"].schema;
|
|
381
|
+
expect(schema.required).toEqual(["status"]);
|
|
382
|
+
expect(schema.properties.status.enum).toEqual(["ok", "warning", "required"]);
|
|
383
|
+
expect(Object.keys(schema.properties).sort()).toEqual([
|
|
384
|
+
"message",
|
|
385
|
+
"pollingIntervalMs",
|
|
386
|
+
"requiredVersion",
|
|
387
|
+
"status",
|
|
388
|
+
"updateUrl",
|
|
389
|
+
"warningVersion",
|
|
390
|
+
]);
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
it("returns ok, warning, and required bodies that match the documented schema", async () => {
|
|
394
|
+
const agent = supertest(buildApp());
|
|
395
|
+
const spec = (await agent.get("/openapi.json").expect(200)).body;
|
|
396
|
+
await VersionConfig.create({
|
|
397
|
+
requiredMessage: "Update required",
|
|
398
|
+
updateUrl: "https://example.com/update",
|
|
399
|
+
warningMessage: "Please update",
|
|
400
|
+
webRequiredVersion: 50,
|
|
401
|
+
webWarningVersion: 100,
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
for (const [version, status] of [
|
|
405
|
+
[150, "ok"],
|
|
406
|
+
[80, "warning"],
|
|
407
|
+
[10, "required"],
|
|
408
|
+
] as const) {
|
|
409
|
+
const res = await agent.get("/version-check").query({platform: "web", version}).expect(200);
|
|
410
|
+
expect(res.body.status).toBe(status);
|
|
411
|
+
expectDocumentedResponse({method: "get", path: "/version-check", response: res, spec});
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
it("does not validate documented query params: a non-numeric version is still ok", async () => {
|
|
416
|
+
configureOpenApiValidator({logValidationErrors: false});
|
|
417
|
+
try {
|
|
418
|
+
const res = await supertest(buildApp())
|
|
419
|
+
.get("/version-check")
|
|
420
|
+
.query({platform: "tv", version: "abc"});
|
|
421
|
+
expect(res.status).toBe(200);
|
|
422
|
+
expect(res.body.status).toBe("ok");
|
|
423
|
+
} finally {
|
|
424
|
+
resetOpenApiValidatorConfig();
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
});
|
|
@@ -2,7 +2,7 @@ import {describe, expect, it} from "bun:test";
|
|
|
2
2
|
import mongoose from "mongoose";
|
|
3
3
|
|
|
4
4
|
import {enrichModelRouterOptions} from "./adminModelRouter";
|
|
5
|
-
import type {ModelRouterOptions} from "./api";
|
|
5
|
+
import type {ModelRouterOptions, OpenApiMiddleware} from "./api";
|
|
6
6
|
|
|
7
7
|
interface Widget {
|
|
8
8
|
secret?: string;
|
|
@@ -34,10 +34,9 @@ describe("enrichModelRouterOptions", () => {
|
|
|
34
34
|
const options: ModelRouterOptions<Widget> = {
|
|
35
35
|
permissions: {create: [], delete: [], list: [], read: [], update: []},
|
|
36
36
|
};
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
expect(enriched.openApi).toEqual({enabled: true});
|
|
37
|
+
const openApi = {enabled: true} as unknown as OpenApiMiddleware;
|
|
38
|
+
const enriched = enrichModelRouterOptions(WidgetModel, options, {openApi});
|
|
39
|
+
expect(enriched.openApi).toEqual(openApi);
|
|
41
40
|
});
|
|
42
41
|
|
|
43
42
|
it("scrubs admin fields in preCreate/preUpdate and honors user hooks", async () => {
|
|
@@ -49,7 +48,10 @@ describe("enrichModelRouterOptions", () => {
|
|
|
49
48
|
listFields: ["title"],
|
|
50
49
|
},
|
|
51
50
|
permissions: {create: [], delete: [], list: [], read: [], update: []},
|
|
52
|
-
preCreate: async (body) =>
|
|
51
|
+
preCreate: async (body) => {
|
|
52
|
+
const widget = body as Partial<Widget>;
|
|
53
|
+
return {...widget, title: `${widget.title}-created`};
|
|
54
|
+
},
|
|
53
55
|
preUpdate: async () => null,
|
|
54
56
|
};
|
|
55
57
|
const enriched = enrichModelRouterOptions(WidgetModel, options, {});
|
|
@@ -20,6 +20,14 @@ import {AdminOwnerTransformer} from "./transformers";
|
|
|
20
20
|
|
|
21
21
|
type TestUser = Awaited<ReturnType<typeof setupDb>>[number];
|
|
22
22
|
|
|
23
|
+
/** Returns a document a postUpdate hook captured, failing the test if the hook never ran. */
|
|
24
|
+
const captured = (doc: Food | undefined): Food => {
|
|
25
|
+
if (!doc) {
|
|
26
|
+
throw new Error("Expected postUpdate to capture a document");
|
|
27
|
+
}
|
|
28
|
+
return doc;
|
|
29
|
+
};
|
|
30
|
+
|
|
23
31
|
describe("model array operations", () => {
|
|
24
32
|
let _server: TestAgent;
|
|
25
33
|
let app: express.Application;
|
|
@@ -219,7 +227,7 @@ describe("model array operations", () => {
|
|
|
219
227
|
|
|
220
228
|
expect(updatedCategory.updated).not.toBe(updatedCategory.created);
|
|
221
229
|
expect(unchangedCategory.updated).toBe(unchangedCategory.created);
|
|
222
|
-
expect(updatedCategory
|
|
230
|
+
expect(updatedCategory?.name).toBe("Updated Category");
|
|
223
231
|
// Unchanged.
|
|
224
232
|
expect(updatedCategory.show).toBe(true);
|
|
225
233
|
expect(unchangedCategory.show).toBe(true);
|
|
@@ -268,8 +276,8 @@ describe("model array operations", () => {
|
|
|
268
276
|
expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
|
|
269
277
|
|
|
270
278
|
// Verify the content is different (new category added)
|
|
271
|
-
expect(postUpdateDoc.categories).toHaveLength(3);
|
|
272
|
-
expect(postUpdatePrevDoc.categories).toHaveLength(2);
|
|
279
|
+
expect(captured(postUpdateDoc).categories).toHaveLength(3);
|
|
280
|
+
expect(captured(postUpdatePrevDoc).categories).toHaveLength(2);
|
|
273
281
|
|
|
274
282
|
// Reset for next test
|
|
275
283
|
postUpdateCalled = false;
|
|
@@ -294,15 +302,15 @@ describe("model array operations", () => {
|
|
|
294
302
|
expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
|
|
295
303
|
|
|
296
304
|
// Verify the content is different (category updated)
|
|
297
|
-
const updatedCategory = postUpdateDoc.categories.find(
|
|
298
|
-
(c: FoodCategory) => c._id
|
|
305
|
+
const updatedCategory = captured(postUpdateDoc).categories.find(
|
|
306
|
+
(c: FoodCategory) => c._id?.toString() === categoryId.toString()
|
|
299
307
|
);
|
|
300
|
-
const prevCategory = postUpdatePrevDoc.categories.find(
|
|
301
|
-
(c: FoodCategory) => c._id
|
|
308
|
+
const prevCategory = captured(postUpdatePrevDoc).categories.find(
|
|
309
|
+
(c: FoodCategory) => c._id?.toString() === categoryId.toString()
|
|
302
310
|
);
|
|
303
311
|
|
|
304
|
-
expect(updatedCategory
|
|
305
|
-
expect(prevCategory
|
|
312
|
+
expect(updatedCategory?.name).toBe("Updated Category");
|
|
313
|
+
expect(prevCategory?.name).toBe("Fruit");
|
|
306
314
|
|
|
307
315
|
// Reset for next test
|
|
308
316
|
postUpdateCalled = false;
|
|
@@ -320,11 +328,11 @@ describe("model array operations", () => {
|
|
|
320
328
|
expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
|
|
321
329
|
|
|
322
330
|
// Verify the content is different (category removed)
|
|
323
|
-
const remainingCategories = postUpdateDoc.categories.filter(
|
|
324
|
-
(c: FoodCategory) => c._id
|
|
331
|
+
const remainingCategories = captured(postUpdateDoc).categories.filter(
|
|
332
|
+
(c: FoodCategory) => c._id?.toString() === categoryId.toString()
|
|
325
333
|
);
|
|
326
|
-
const prevCategories = postUpdatePrevDoc.categories.filter(
|
|
327
|
-
(c: FoodCategory) => c._id
|
|
334
|
+
const prevCategories = captured(postUpdatePrevDoc).categories.filter(
|
|
335
|
+
(c: FoodCategory) => c._id?.toString() === categoryId.toString()
|
|
328
336
|
);
|
|
329
337
|
|
|
330
338
|
expect(remainingCategories).toHaveLength(0);
|
|
@@ -371,10 +379,10 @@ describe("model array operations", () => {
|
|
|
371
379
|
expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
|
|
372
380
|
|
|
373
381
|
// Verify the content is different (new tag added)
|
|
374
|
-
expect(postUpdateDoc.tags).toHaveLength(3);
|
|
375
|
-
expect(postUpdatePrevDoc.tags).toHaveLength(2);
|
|
376
|
-
expect(postUpdateDoc.tags).toContain("organic");
|
|
377
|
-
expect(postUpdatePrevDoc.tags).not.toContain("organic");
|
|
382
|
+
expect(captured(postUpdateDoc).tags).toHaveLength(3);
|
|
383
|
+
expect(captured(postUpdatePrevDoc).tags).toHaveLength(2);
|
|
384
|
+
expect(captured(postUpdateDoc).tags).toContain("organic");
|
|
385
|
+
expect(captured(postUpdatePrevDoc).tags).not.toContain("organic");
|
|
378
386
|
|
|
379
387
|
// Reset for next test
|
|
380
388
|
postUpdateCalled = false;
|
|
@@ -388,10 +396,10 @@ describe("model array operations", () => {
|
|
|
388
396
|
expect(postUpdateDoc).not.toBe(postUpdatePrevDoc);
|
|
389
397
|
|
|
390
398
|
// Verify the content is different (tag updated)
|
|
391
|
-
expect(postUpdateDoc.tags).toContain("super-healthy");
|
|
392
|
-
expect(postUpdatePrevDoc.tags).toContain("healthy");
|
|
393
|
-
expect(postUpdateDoc.tags).not.toContain("healthy");
|
|
394
|
-
expect(postUpdatePrevDoc.tags).not.toContain("super-healthy");
|
|
399
|
+
expect(captured(postUpdateDoc).tags).toContain("super-healthy");
|
|
400
|
+
expect(captured(postUpdatePrevDoc).tags).toContain("healthy");
|
|
401
|
+
expect(captured(postUpdateDoc).tags).not.toContain("healthy");
|
|
402
|
+
expect(captured(postUpdatePrevDoc).tags).not.toContain("super-healthy");
|
|
395
403
|
});
|
|
396
404
|
});
|
|
397
405
|
|
|
@@ -829,7 +837,8 @@ describe("array subdocument PATCH with a stripping preUpdate", () => {
|
|
|
829
837
|
read: [Permissions.IsAdmin],
|
|
830
838
|
update: [Permissions.IsAdmin],
|
|
831
839
|
},
|
|
832
|
-
|
|
840
|
+
// The hook returns the stripped update body, not a whole document.
|
|
841
|
+
preUpdate: (body) => preUpdate(body) as Food,
|
|
833
842
|
})
|
|
834
843
|
);
|
|
835
844
|
agent = await authAsUser(app, "admin");
|
package/src/api.hooks.test.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it, type mock} from "bun:test";
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
3
|
import type express from "express";
|
|
4
|
+
import type {HydratedDocument} from "mongoose";
|
|
4
5
|
import supertest from "supertest";
|
|
5
6
|
import type TestAgent from "supertest/lib/agent";
|
|
6
7
|
|
|
@@ -48,8 +49,9 @@ describe("pre and post hooks", () => {
|
|
|
48
49
|
update: [Permissions.IsAny],
|
|
49
50
|
},
|
|
50
51
|
preCreate: (data) => {
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
const food = data as Partial<Food>;
|
|
53
|
+
food.calories = 14;
|
|
54
|
+
return food as Food;
|
|
53
55
|
},
|
|
54
56
|
preDelete: (data) => {
|
|
55
57
|
deleteCalled = true;
|
|
@@ -57,7 +59,7 @@ describe("pre and post hooks", () => {
|
|
|
57
59
|
},
|
|
58
60
|
preUpdate: (data) => {
|
|
59
61
|
data.calories = 15;
|
|
60
|
-
return data;
|
|
62
|
+
return data as Food;
|
|
61
63
|
},
|
|
62
64
|
})
|
|
63
65
|
);
|
|
@@ -158,18 +160,17 @@ describe("pre and post hooks", () => {
|
|
|
158
160
|
update: [Permissions.IsAny],
|
|
159
161
|
},
|
|
160
162
|
postCreate: async (data) => {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
163
|
+
const food = data as HydratedDocument<Food>;
|
|
164
|
+
food.calories = 14;
|
|
165
|
+
await food.save();
|
|
164
166
|
},
|
|
165
|
-
postDelete: (
|
|
167
|
+
postDelete: () => {
|
|
166
168
|
deleteCalled = true;
|
|
167
|
-
return data;
|
|
168
169
|
},
|
|
169
170
|
postUpdate: async (data) => {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
171
|
+
const food = data as HydratedDocument<Food>;
|
|
172
|
+
food.calories = 15;
|
|
173
|
+
await food.save();
|
|
173
174
|
},
|
|
174
175
|
})
|
|
175
176
|
);
|
package/src/api.query.test.ts
CHANGED
|
@@ -471,7 +471,7 @@ describe("query and list methods", () => {
|
|
|
471
471
|
.get(`/food?${qs.stringify({$or: [{name: "Carrots"}, {name: "Pizza"}]})}`)
|
|
472
472
|
.expect(200);
|
|
473
473
|
expect(res.body.data).toHaveLength(2);
|
|
474
|
-
const ids1 = res.body.data.map((d:
|
|
474
|
+
const ids1 = res.body.data.map((d: {id: string}) => d.id);
|
|
475
475
|
expect(ids1).toEqual(expect.arrayContaining([carrots?._id.toString(), pizza?._id.toString()]));
|
|
476
476
|
expect(ids1).toHaveLength(2);
|
|
477
477
|
});
|
|
@@ -486,7 +486,7 @@ describe("query and list methods", () => {
|
|
|
486
486
|
)
|
|
487
487
|
.expect(200);
|
|
488
488
|
expect(res.body.data).toHaveLength(2);
|
|
489
|
-
const ids2 = res.body.data.map((d:
|
|
489
|
+
const ids2 = res.body.data.map((d: {id: string}) => d.id);
|
|
490
490
|
expect(ids2).toEqual(
|
|
491
491
|
expect.arrayContaining([carrots?._id.toString(), spinach?._id.toString()])
|
|
492
492
|
);
|
package/src/api.test.ts
CHANGED
|
@@ -5,11 +5,13 @@ import mongoose, {type Model} from "mongoose";
|
|
|
5
5
|
import supertest from "supertest";
|
|
6
6
|
import type TestAgent from "supertest/lib/agent";
|
|
7
7
|
|
|
8
|
-
import {addPopulateToQuery, modelRouter} from "./api";
|
|
8
|
+
import {addPopulateToQuery, type JSONValue, modelRouter} from "./api";
|
|
9
9
|
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
10
|
+
import {clearCollectionRegistry, getCollection} from "./collectionRegistry";
|
|
10
11
|
import {APIError} from "./errors";
|
|
11
12
|
import {clearMCPRegistry, getMCPRegistry} from "./mcp/registry";
|
|
12
13
|
import {Permissions} from "./permissions";
|
|
14
|
+
import type {AnyTerrenoAccess} from "./rbac/types";
|
|
13
15
|
import {
|
|
14
16
|
authAsUser,
|
|
15
17
|
type Food,
|
|
@@ -403,7 +405,7 @@ describe("@terreno/api", () => {
|
|
|
403
405
|
read: [Permissions.IsAny],
|
|
404
406
|
update: [Permissions.IsAny],
|
|
405
407
|
},
|
|
406
|
-
responseHandler: async (_data, method) => {
|
|
408
|
+
responseHandler: async (_data, method): Promise<JSONValue> => {
|
|
407
409
|
if (method === "list") {
|
|
408
410
|
return {custom: "response"};
|
|
409
411
|
}
|
|
@@ -1443,7 +1445,7 @@ describe("@terreno/api", () => {
|
|
|
1443
1445
|
|
|
1444
1446
|
it("model.create validation error is handled", async () => {
|
|
1445
1447
|
// Use a model that has required fields
|
|
1446
|
-
const {RequiredModel} = await import("./tests");
|
|
1448
|
+
const {RequiredModel} = await import("./tests.js");
|
|
1447
1449
|
|
|
1448
1450
|
app.use(
|
|
1449
1451
|
"/required",
|
|
@@ -2190,7 +2192,7 @@ describe("@terreno/api", () => {
|
|
|
2190
2192
|
});
|
|
2191
2193
|
|
|
2192
2194
|
describe("three-arg modelRouter registration", () => {
|
|
2193
|
-
it("returns a ModelRouterRegistration with path
|
|
2195
|
+
it("returns a ModelRouterRegistration with path", () => {
|
|
2194
2196
|
const registration = modelRouter("/food", FoodModel, {
|
|
2195
2197
|
permissions: {
|
|
2196
2198
|
create: [Permissions.IsAny],
|
|
@@ -2199,7 +2201,6 @@ describe("@terreno/api", () => {
|
|
|
2199
2201
|
read: [Permissions.IsAny],
|
|
2200
2202
|
update: [Permissions.IsAny],
|
|
2201
2203
|
},
|
|
2202
|
-
realtime: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
2203
2204
|
});
|
|
2204
2205
|
expect(registration).toHaveProperty("__type", "modelRouter");
|
|
2205
2206
|
expect(registration).toHaveProperty("path", "/food");
|
|
@@ -2234,8 +2235,8 @@ describe("@terreno/api", () => {
|
|
|
2234
2235
|
}),
|
|
2235
2236
|
queryFilter: async (): Promise<Record<string, unknown>> => ({}),
|
|
2236
2237
|
statements: {food: ["list", "read", "create", "update", "delete"]},
|
|
2237
|
-
};
|
|
2238
|
-
registration._buildWithContext({accessControl
|
|
2238
|
+
} as unknown as AnyTerrenoAccess;
|
|
2239
|
+
registration._buildWithContext({accessControl});
|
|
2239
2240
|
|
|
2240
2241
|
const after = getMCPRegistry()[0];
|
|
2241
2242
|
expect(after?.options.accessControl).toBe(accessControl);
|
|
@@ -2253,10 +2254,10 @@ describe("@terreno/api", () => {
|
|
|
2253
2254
|
}),
|
|
2254
2255
|
queryFilter: async (): Promise<Record<string, unknown>> => ({}),
|
|
2255
2256
|
statements: {food: ["list", "read", "create", "update", "delete"]},
|
|
2256
|
-
};
|
|
2257
|
+
} as unknown as AnyTerrenoAccess;
|
|
2257
2258
|
modelRouter(FoodModel, {
|
|
2258
2259
|
access: {resource: "food"},
|
|
2259
|
-
accessControl
|
|
2260
|
+
accessControl,
|
|
2260
2261
|
mcp: {methods: ["list"]},
|
|
2261
2262
|
permissions: {
|
|
2262
2263
|
create: [Permissions.IsAny],
|
|
@@ -2271,8 +2272,9 @@ describe("@terreno/api", () => {
|
|
|
2271
2272
|
expect(registered?.options.permissions.list).not.toEqual([Permissions.IsAny]);
|
|
2272
2273
|
});
|
|
2273
2274
|
|
|
2274
|
-
it("
|
|
2275
|
-
|
|
2275
|
+
it("rejects the removed realtime option and registers no realtime surface", () => {
|
|
2276
|
+
clearCollectionRegistry();
|
|
2277
|
+
const registration = modelRouter("/food", FoodModel, {
|
|
2276
2278
|
permissions: {
|
|
2277
2279
|
create: [Permissions.IsAny],
|
|
2278
2280
|
delete: [Permissions.IsAny],
|
|
@@ -2280,11 +2282,12 @@ describe("@terreno/api", () => {
|
|
|
2280
2282
|
read: [Permissions.IsAny],
|
|
2281
2283
|
update: [Permissions.IsAny],
|
|
2282
2284
|
},
|
|
2285
|
+
// @ts-expect-error `realtime` was removed in Terreno 58; use `sync` with @terreno/syncdb.
|
|
2283
2286
|
realtime: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
2284
2287
|
});
|
|
2285
|
-
|
|
2286
|
-
expect(
|
|
2287
|
-
|
|
2288
|
+
expect(registration).toHaveProperty("path", "/food");
|
|
2289
|
+
expect(getCollection("/food")?.surfaces).toEqual({mcp: false, sync: false});
|
|
2290
|
+
clearCollectionRegistry();
|
|
2288
2291
|
});
|
|
2289
2292
|
});
|
|
2290
2293
|
|
package/src/api.ts
CHANGED
|
@@ -56,8 +56,6 @@ import type {PopulatePath} from "./populate";
|
|
|
56
56
|
import {resolveModelRouterAccess, validateAccessWriteBody} from "./rbac/modelRouterAccess";
|
|
57
57
|
import type {AnyTerrenoAccess, ModelRouterAccessOptions} from "./rbac/types";
|
|
58
58
|
import {assertCanWriteTargetUser, assertCanWriteUserIdentity} from "./rbac/userWriteGuards";
|
|
59
|
-
import {warnRealtimeDeprecated} from "./realtime/deprecation";
|
|
60
|
-
import type {RealtimeConfig} from "./realtime/types";
|
|
61
59
|
import {checkSortFields, getAllowedSortFields} from "./sortFields";
|
|
62
60
|
import {
|
|
63
61
|
type ExecutorConcurrencyCheck,
|
|
@@ -264,7 +262,7 @@ export interface ModelRouterOptions<T> {
|
|
|
264
262
|
preCreate?: (
|
|
265
263
|
value: Partial<T> | (Partial<T> | undefined)[] | null | undefined,
|
|
266
264
|
request: express.Request
|
|
267
|
-
) => T | Promise<T
|
|
265
|
+
) => T | null | Promise<T | null>;
|
|
268
266
|
/**
|
|
269
267
|
* Hook that runs after `transformer.transform` but before changes are made for update operations.
|
|
270
268
|
* Can update the body fields based on the request or the user.
|
|
@@ -274,7 +272,7 @@ export interface ModelRouterOptions<T> {
|
|
|
274
272
|
* @param value - The request body relative to the model update (type: Partial<T>). Note: this does not contain the entire document to be updated, only the fields being updated.
|
|
275
273
|
* @param request - The Express request object.
|
|
276
274
|
*/
|
|
277
|
-
preUpdate?: (value: Partial<T>, request: express.Request) => T | Promise<T
|
|
275
|
+
preUpdate?: (value: Partial<T>, request: express.Request) => T | null | Promise<T | null>;
|
|
278
276
|
/**
|
|
279
277
|
* Hook that runs after `transformer.transform` but before the object is deleted.
|
|
280
278
|
* Return null to return a generic 403 error.
|
|
@@ -283,7 +281,7 @@ export interface ModelRouterOptions<T> {
|
|
|
283
281
|
* @param value - The document to be deleted, before the soft update of deleted: true (type: T).
|
|
284
282
|
* @param request - The Express request object.
|
|
285
283
|
*/
|
|
286
|
-
preDelete?: (value: T, request: express.Request) => T | Promise<T
|
|
284
|
+
preDelete?: (value: T, request: express.Request) => T | null | Promise<T | null>;
|
|
287
285
|
/**
|
|
288
286
|
* Hook that runs after the object is created but before the responseHandler serializes and
|
|
289
287
|
* returned. This is a good spot to perform dependent changes to other models or performing async
|
|
@@ -404,18 +402,6 @@ export interface ModelRouterOptions<T> {
|
|
|
404
402
|
* ```
|
|
405
403
|
*/
|
|
406
404
|
mcp?: MCPConfig;
|
|
407
|
-
/**
|
|
408
|
-
* Enable real-time sync for this model via WebSocket events.
|
|
409
|
-
* When configured, CRUD operations will emit events to connected clients
|
|
410
|
-
* through the RealtimeApp plugin's change stream watcher.
|
|
411
|
-
*
|
|
412
|
-
* Requires the RealtimeApp plugin to be registered with TerrenoApp.
|
|
413
|
-
*
|
|
414
|
-
* @deprecated Removed in Terreno 58. Use `sync` with
|
|
415
|
-
* `@terreno/syncdb` instead. `RealtimeApp` remains required for sync sockets.
|
|
416
|
-
* See docs/how-to/migrate-rtk-to-syncdb.md.
|
|
417
|
-
*/
|
|
418
|
-
realtime?: RealtimeConfig;
|
|
419
405
|
/**
|
|
420
406
|
* Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
|
|
421
407
|
* into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
|
|
@@ -746,9 +732,6 @@ export function modelRouter<T>(
|
|
|
746
732
|
const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
|
|
747
733
|
|
|
748
734
|
if (path !== undefined) {
|
|
749
|
-
if (options.realtime) {
|
|
750
|
-
warnRealtimeDeprecated(model.modelName, path);
|
|
751
|
-
}
|
|
752
735
|
registerCollection({model, options, routePath: path});
|
|
753
736
|
}
|
|
754
737
|
|
|
@@ -777,13 +760,6 @@ export function modelRouter<T>(
|
|
|
777
760
|
};
|
|
778
761
|
}
|
|
779
762
|
|
|
780
|
-
if (options.realtime) {
|
|
781
|
-
warnRealtimeDeprecated(model.modelName);
|
|
782
|
-
logger.warn(
|
|
783
|
-
`modelRouter for ${model.modelName} has realtime config but was called without a path. ` +
|
|
784
|
-
"Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)"
|
|
785
|
-
);
|
|
786
|
-
}
|
|
787
763
|
if (options.sync) {
|
|
788
764
|
logger.warn(
|
|
789
765
|
`modelRouter for ${model.modelName} has sync config but was called without a path. ` +
|
|
@@ -48,7 +48,7 @@ describe("AuditApp", () => {
|
|
|
48
48
|
|
|
49
49
|
it("does not register AuditEvent on the default connection when @terreno/api is imported", async () => {
|
|
50
50
|
deleteAuditEventModel();
|
|
51
|
-
await import("../index");
|
|
51
|
+
await import("../index.js");
|
|
52
52
|
assert.isUndefined(mongoose.connection.models.TerrenoAuditEvent);
|
|
53
53
|
});
|
|
54
54
|
|