@terreno/api 57.3.0 → 57.4.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.
- package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
- package/README.md +6 -0
- package/dist/adminTypes.d.ts +7 -0
- package/dist/adminTypes.js +6 -1
- package/dist/api.d.ts +10 -0
- package/dist/api.js +99 -36
- package/dist/audit/auditApp.d.ts +30 -0
- package/dist/audit/auditApp.js +155 -0
- package/dist/audit/auditEventModel.d.ts +29 -0
- package/dist/audit/auditEventModel.js +102 -0
- package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
- package/dist/audit/cloudTasksEnqueue.js +162 -0
- package/dist/audit/diff.d.ts +10 -0
- package/dist/audit/diff.js +230 -0
- package/dist/audit/processQueue.d.ts +6 -0
- package/dist/audit/processQueue.js +101 -0
- package/dist/audit/rbacSink.d.ts +2 -0
- package/dist/audit/rbacSink.js +82 -0
- package/dist/audit/record.d.ts +56 -0
- package/dist/audit/record.js +373 -0
- package/dist/betterAuth.d.ts +6 -0
- package/dist/betterAuthSetup.js +1 -1
- package/dist/collectionRegistry.d.ts +3 -1
- package/dist/collectionRegistry.js +25 -0
- package/dist/index.d.ts +26 -1
- package/dist/index.js +48 -2
- package/dist/mcp/query.d.ts +0 -13
- package/dist/mcp/query.js +8 -8
- package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
- package/dist/migrations/fixtures/all-down/20260910120000-one.js +49 -0
- package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
- package/dist/migrations/fixtures/all-down/20260910120001-two.js +49 -0
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +45 -0
- package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
- package/dist/migrations/fixtures/bad-name/not-a-migration.js +45 -0
- package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
- package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
- package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
- package/dist/migrations/fixtures/valid/20260910120000-alpha.js +45 -0
- package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
- package/dist/migrations/fixtures/valid/20260910120001-beta.js +49 -0
- package/dist/migrations/generate.d.ts +17 -0
- package/dist/migrations/generate.js +277 -0
- package/dist/migrations/load.d.ts +20 -0
- package/dist/migrations/load.js +236 -0
- package/dist/migrations/lock.d.ts +13 -0
- package/dist/migrations/lock.js +145 -0
- package/dist/migrations/runner.d.ts +42 -0
- package/dist/migrations/runner.js +503 -0
- package/dist/migrations/schemaCatalog.d.ts +44 -0
- package/dist/migrations/schemaCatalog.js +326 -0
- package/dist/migrations/types.d.ts +87 -0
- package/dist/migrations/types.js +7 -0
- package/dist/models/notification.d.ts +2 -0
- package/dist/models/notification.js +62 -0
- package/dist/models/notificationPreference.d.ts +2 -0
- package/dist/models/notificationPreference.js +49 -0
- package/dist/notifications/notificationService.d.ts +40 -0
- package/dist/notifications/notificationService.js +323 -0
- package/dist/notifications/notificationsApp.d.ts +18 -0
- package/dist/notifications/notificationsApp.js +250 -0
- package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
- package/dist/notifications/notificationsBeforeSend.js +77 -0
- package/dist/openApi.d.ts +1 -7
- package/dist/openApi.js +7 -6
- package/dist/openApiBuilder.d.ts +14 -3
- package/dist/openApiValidator.d.ts +13 -1
- package/dist/openApiValidator.js +200 -36
- package/dist/orgs/orgContext.d.ts +23 -0
- package/dist/orgs/orgContext.js +198 -0
- package/dist/orgs/orgPermissions.d.ts +4 -0
- package/dist/orgs/orgPermissions.js +77 -0
- package/dist/orgs/orgPlugin.d.ts +13 -0
- package/dist/orgs/orgPlugin.js +84 -0
- package/dist/orgs/organizationModel.d.ts +13 -0
- package/dist/orgs/organizationModel.js +301 -0
- package/dist/orgs/organizationSettings.d.ts +19 -0
- package/dist/orgs/organizationSettings.js +120 -0
- package/dist/orgs/orgsApp.d.ts +28 -0
- package/dist/orgs/orgsApp.js +678 -0
- package/dist/permissions.d.ts +7 -13
- package/dist/permissions.js +8 -31
- package/dist/rateLimit/middleware.d.ts +0 -8
- package/dist/rateLimit/middleware.js +2 -3
- package/dist/rateLimit/mongoStore.d.ts +1 -0
- package/dist/rateLimit/mongoStore.js +1 -0
- package/dist/rateLimit/policies.d.ts +0 -4
- package/dist/rateLimit/policies.js +5 -7
- package/dist/rateLimit/redisStore.d.ts +1 -0
- package/dist/rateLimit/redisStore.js +1 -0
- package/dist/rbac/access.js +30 -13
- package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
- package/dist/rbac/membershipOrgAdminSource.js +122 -0
- package/dist/rbac/modelRouterAccess.d.ts +3 -0
- package/dist/rbac/modelRouterAccess.js +3 -0
- package/dist/rbac/resolve.js +60 -31
- package/dist/rbac/roleModel.d.ts +2 -5
- package/dist/rbac/roleModel.js +18 -4
- package/dist/rbac/statements.d.ts +10 -1
- package/dist/rbac/statements.js +19 -2
- package/dist/rbac/types.d.ts +5 -0
- package/dist/realtime/changeStreamWatcher.d.ts +10 -4
- package/dist/realtime/changeStreamWatcher.js +110 -64
- package/dist/realtime/deprecation.d.ts +1 -0
- package/dist/realtime/deprecation.js +1 -0
- package/dist/realtime/realtimeApp.d.ts +1 -0
- package/dist/realtime/realtimeApp.js +1 -0
- package/dist/schemaMetadata.js +16 -5
- package/dist/sync/adminBroadcastScope.d.ts +40 -0
- package/dist/sync/adminBroadcastScope.js +194 -0
- package/dist/sync/adminWindowAccess.d.ts +13 -0
- package/dist/sync/adminWindowAccess.js +96 -0
- package/dist/sync/adminWindowMutation.d.ts +88 -0
- package/dist/sync/adminWindowMutation.js +247 -0
- package/dist/sync/executors.d.ts +9 -3
- package/dist/sync/executors.js +190 -159
- package/dist/sync/mutationHandler.d.ts +5 -2
- package/dist/sync/mutationHandler.js +191 -71
- package/dist/sync/registry.js +4 -0
- package/dist/sync/routes.d.ts +13 -0
- package/dist/sync/routes.js +113 -56
- package/dist/sync/socketHandlers.d.ts +8 -2
- package/dist/sync/socketHandlers.js +144 -50
- package/dist/sync/streams.d.ts +2 -0
- package/dist/sync/streams.js +7 -1
- package/dist/sync/syncApp.d.ts +2 -1
- package/dist/sync/syncApp.js +2 -1
- package/dist/sync/syncBatch.d.ts +5 -2
- package/dist/sync/syncBatch.js +4 -4
- package/dist/sync/types.d.ts +18 -0
- package/dist/terrenoApp.d.ts +29 -0
- package/dist/terrenoApp.js +91 -54
- package/dist/tests/createTestData.d.ts +1 -3
- package/dist/tests/createTestData.js +3 -5
- package/dist/tests/models.d.ts +1 -0
- package/dist/tests/models.js +9 -2
- package/dist/tests/testHelper.d.ts +0 -5
- package/dist/tests/testHelper.js +2 -9
- package/dist/types/authToken.d.ts +3 -3
- package/dist/types/mcpServiceToken.d.ts +2 -2
- package/dist/types/membership.d.ts +23 -0
- package/dist/types/membership.js +2 -0
- package/dist/types/notification.d.ts +28 -0
- package/dist/types/notification.js +2 -0
- package/dist/types/notificationPreference.d.ts +20 -0
- package/dist/types/notificationPreference.js +2 -0
- package/dist/types/organization.d.ts +36 -0
- package/dist/types/organization.js +2 -0
- package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
- package/dist/webhooks/idempotency/webhookReceipt.js +7 -7
- package/dist/webhooks/rawBody.d.ts +1 -0
- package/dist/webhooks/rawBody.js +1 -0
- package/package.json +31 -25
- package/src/__snapshots__/openApi.test.ts.snap +192 -54
- package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
- package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
- package/src/adminTypes.ts +8 -0
- package/src/api.test.ts +39 -2
- package/src/api.ts +68 -0
- package/src/audit/auditApp.test.ts +243 -0
- package/src/audit/auditApp.ts +139 -0
- package/src/audit/auditEventModel.ts +156 -0
- package/src/audit/auditRouter.test.ts +456 -0
- package/src/audit/cloudTasksEnqueue.test.ts +124 -0
- package/src/audit/cloudTasksEnqueue.ts +104 -0
- package/src/audit/diff.ts +163 -0
- package/src/audit/processQueue.ts +69 -0
- package/src/audit/rbacSink.test.ts +86 -0
- package/src/audit/rbacSink.ts +42 -0
- package/src/audit/record.test.ts +402 -0
- package/src/audit/record.ts +328 -0
- package/src/auth.test.ts +1 -1
- package/src/betterAuth.ts +7 -0
- package/src/betterAuthSetup.test.ts +27 -0
- package/src/betterAuthSetup.ts +1 -0
- package/src/collectionRegistry.test.ts +8 -9
- package/src/collectionRegistry.ts +21 -1
- package/src/express.d.ts +2 -0
- package/src/expressServer.test.ts +50 -2
- package/src/index.ts +69 -0
- package/src/mcp/handlers.test.ts +275 -0
- package/src/mcp/query.ts +3 -3
- package/src/mcp/toolGenerator.test.ts +81 -0
- package/src/migrations/cli.test.ts +376 -0
- package/src/migrations/cli.ts +283 -0
- package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
- package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
- package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
- package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
- package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
- package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
- package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
- package/src/migrations/generate.test.ts +333 -0
- package/src/migrations/generate.ts +216 -0
- package/src/migrations/load.test.ts +103 -0
- package/src/migrations/load.ts +124 -0
- package/src/migrations/lock.test.ts +133 -0
- package/src/migrations/lock.ts +118 -0
- package/src/migrations/runner.test.ts +504 -0
- package/src/migrations/runner.ts +358 -0
- package/src/migrations/schemaCatalog.test.ts +159 -0
- package/src/migrations/schemaCatalog.ts +262 -0
- package/src/migrations/types.ts +94 -0
- package/src/models/notification.ts +68 -0
- package/src/models/notificationPreference.ts +62 -0
- package/src/notifications/notificationService.ts +254 -0
- package/src/notifications/notificationsApp.test.ts +505 -0
- package/src/notifications/notificationsApp.ts +200 -0
- package/src/notifications/notificationsBeforeSend.ts +51 -0
- package/src/openApi.test.ts +0 -1
- package/src/openApi.ts +2 -1
- package/src/openApiBuilder.ts +14 -3
- package/src/openApiValidator.test.ts +221 -2
- package/src/openApiValidator.ts +218 -33
- package/src/orgs/orgAccessOptIn.test.ts +87 -0
- package/src/orgs/orgContext.test.ts +259 -0
- package/src/orgs/orgContext.ts +151 -0
- package/src/orgs/orgPermissions.test.ts +105 -0
- package/src/orgs/orgPermissions.ts +40 -0
- package/src/orgs/orgPlugin.test.ts +130 -0
- package/src/orgs/orgPlugin.ts +70 -0
- package/src/orgs/orgRbac.test.ts +267 -0
- package/src/orgs/orgSecurityDefects.test.ts +415 -0
- package/src/orgs/organizationModel.test.ts +205 -0
- package/src/orgs/organizationModel.ts +257 -0
- package/src/orgs/organizationSettings.test.ts +113 -0
- package/src/orgs/organizationSettings.ts +126 -0
- package/src/orgs/orgsApp.test.ts +382 -0
- package/src/orgs/orgsApp.ts +563 -0
- package/src/permissions.test.ts +62 -36
- package/src/permissions.ts +8 -30
- package/src/rateLimit/middleware.ts +1 -1
- package/src/rateLimit/mongoStore.ts +1 -0
- package/src/rateLimit/policies.ts +2 -2
- package/src/rateLimit/redisStore.ts +1 -0
- package/src/rbac/access.ts +11 -3
- package/src/rbac/membershipOrgAdminSource.ts +59 -0
- package/src/rbac/modelRouterAccess.ts +3 -0
- package/src/rbac/permissionUtils.test.ts +26 -5
- package/src/rbac/resolve.test.ts +34 -2
- package/src/rbac/resolve.ts +26 -7
- package/src/rbac/roleModel.test.ts +34 -1
- package/src/rbac/roleModel.ts +17 -1
- package/src/rbac/statements.test.ts +19 -0
- package/src/rbac/statements.ts +19 -1
- package/src/rbac/types.ts +5 -0
- package/src/realtime/changeStreamWatcher.ts +73 -33
- package/src/realtime/deprecation.ts +1 -0
- package/src/realtime/realtime.test.ts +357 -185
- package/src/realtime/realtimeApp.ts +1 -0
- package/src/schemaMetadata.test.ts +14 -0
- package/src/schemaMetadata.ts +5 -5
- package/src/sync/adminBroadcastConfig.test.ts +96 -0
- package/src/sync/adminBroadcastScope.test.ts +155 -0
- package/src/sync/adminBroadcastScope.ts +123 -0
- package/src/sync/adminWindowAccess.test.ts +57 -0
- package/src/sync/adminWindowAccess.ts +32 -0
- package/src/sync/adminWindowMutation.test.ts +450 -0
- package/src/sync/adminWindowMutation.ts +283 -0
- package/src/sync/executors.ts +33 -6
- package/src/sync/mutationHandler.test.ts +277 -1
- package/src/sync/mutationHandler.ts +171 -29
- package/src/sync/registry.ts +4 -0
- package/src/sync/routes.ts +52 -8
- package/src/sync/socketHandlers.ts +154 -58
- package/src/sync/streams.ts +6 -0
- package/src/sync/sync.test.ts +3 -2
- package/src/sync/syncApp.ts +2 -1
- package/src/sync/syncBatch.ts +7 -2
- package/src/sync/syncRoutes.test.ts +297 -3
- package/src/sync/syncSocket.test.ts +229 -0
- package/src/sync/types.ts +20 -0
- package/src/terrenoApp.migrations.test.ts +114 -0
- package/src/terrenoApp.test.ts +41 -0
- package/src/terrenoApp.ts +94 -31
- package/src/tests/createTestData.ts +2 -2
- package/src/tests/models.ts +10 -2
- package/src/tests/testHelper.ts +1 -7
- package/src/types/authToken.ts +2 -4
- package/src/types/mcpServiceToken.ts +1 -7
- package/src/types/membership.ts +48 -0
- package/src/types/notification.ts +34 -0
- package/src/types/notificationPreference.ts +28 -0
- package/src/types/organization.ts +49 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +4 -7
- package/src/webhooks/rawBody.test.ts +33 -0
- package/src/webhooks/rawBody.ts +1 -0
- package/tsconfig.json +1 -1
- package/tsconfig.typedoc.json +2 -1
- package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
- package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
- package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
package/src/openApiValidator.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Validation is always installed as middleware but only activates after
|
|
8
8
|
* `configureOpenApiValidator()` is called. This makes it safe to include
|
|
9
|
-
* in modelRouter by default.
|
|
9
|
+
* in modelRouter by default. Create bodies enforce Mongoose required fields;
|
|
10
|
+
* PATCH/update bodies are partial (present fields only).
|
|
10
11
|
*
|
|
11
12
|
* @module openApiValidator
|
|
12
13
|
*
|
|
@@ -38,12 +39,11 @@ import Ajv, {type ErrorObject, type ValidateFunction} from "ajv";
|
|
|
38
39
|
import addFormats from "ajv-formats";
|
|
39
40
|
import type {NextFunction, Request, Response} from "express";
|
|
40
41
|
import type {Model} from "mongoose";
|
|
41
|
-
import
|
|
42
|
-
|
|
42
|
+
import {ADMIN_LIST_CHOICE_EMPTY_VALUE} from "./adminTypes";
|
|
43
43
|
import {APIError} from "./errors";
|
|
44
44
|
import {logger} from "./logger";
|
|
45
45
|
import type {OpenApiSchema, OpenApiSchemaProperty} from "./openApiBuilder";
|
|
46
|
-
import {
|
|
46
|
+
import {getOpenApiSpecForModel} from "./populate";
|
|
47
47
|
|
|
48
48
|
/**
|
|
49
49
|
* Global configuration for OpenAPI validation.
|
|
@@ -185,6 +185,11 @@ const getAjvInstance = (): Ajv => {
|
|
|
185
185
|
validateSchema: false,
|
|
186
186
|
});
|
|
187
187
|
addFormats(instance as unknown as Parameters<typeof addFormats>[0]);
|
|
188
|
+
instance.addKeyword({
|
|
189
|
+
keyword: ESCAPED_REGEX_LITERAL_KEYWORD,
|
|
190
|
+
type: "string",
|
|
191
|
+
validate: (_enabled: boolean, data: string) => isEscapedRegexLiteral(data),
|
|
192
|
+
});
|
|
188
193
|
ajvCache.set(key, instance);
|
|
189
194
|
}
|
|
190
195
|
|
|
@@ -211,6 +216,44 @@ const VALID_JSON_SCHEMA_TYPES = new Set([
|
|
|
211
216
|
"null",
|
|
212
217
|
]);
|
|
213
218
|
|
|
219
|
+
const REGEX_META_CHARACTERS = new Set([
|
|
220
|
+
"\\",
|
|
221
|
+
".",
|
|
222
|
+
"*",
|
|
223
|
+
"+",
|
|
224
|
+
"?",
|
|
225
|
+
"^",
|
|
226
|
+
"$",
|
|
227
|
+
"{",
|
|
228
|
+
"}",
|
|
229
|
+
"(",
|
|
230
|
+
")",
|
|
231
|
+
"|",
|
|
232
|
+
"[",
|
|
233
|
+
"]",
|
|
234
|
+
]);
|
|
235
|
+
|
|
236
|
+
/** Accepts literal text and escaped metacharacters (e.g. `\\.`), rejects executable patterns. */
|
|
237
|
+
export const isEscapedRegexLiteral = (value: string): boolean => {
|
|
238
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
239
|
+
const character = value[index];
|
|
240
|
+
if (character === "\\") {
|
|
241
|
+
const escapedCharacter = value[index + 1];
|
|
242
|
+
if (!escapedCharacter || !REGEX_META_CHARACTERS.has(escapedCharacter)) {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
index += 1;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (REGEX_META_CHARACTERS.has(character)) {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return true;
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const ESCAPED_REGEX_LITERAL_KEYWORD = "escapedRegexLiteral";
|
|
256
|
+
|
|
214
257
|
// mongoose-to-swagger emits non-standard type strings for some Mongoose types
|
|
215
258
|
const MONGOOSE_TYPE_MAP: Record<string, {type: string; format?: string}> = {
|
|
216
259
|
dateonly: {format: "date", type: "string"},
|
|
@@ -261,9 +304,61 @@ const sanitizeSchemaForAjv = (schema: Record<string, unknown>): Record<string, u
|
|
|
261
304
|
);
|
|
262
305
|
}
|
|
263
306
|
|
|
307
|
+
if (Array.isArray(result.oneOf)) {
|
|
308
|
+
result.oneOf = result.oneOf.map((entry) =>
|
|
309
|
+
typeof entry === "object" && entry !== null
|
|
310
|
+
? sanitizeSchemaForAjv(entry as Record<string, unknown>)
|
|
311
|
+
: entry
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (typeof result.required === "boolean") {
|
|
316
|
+
delete result.required;
|
|
317
|
+
}
|
|
318
|
+
|
|
264
319
|
return result;
|
|
265
320
|
};
|
|
266
321
|
|
|
322
|
+
const stripBooleanRequiredFlag = (schema: OpenApiSchemaProperty): OpenApiSchemaProperty => {
|
|
323
|
+
if (schema.required === true || schema.required === false) {
|
|
324
|
+
const {required: _, ...rest} = schema;
|
|
325
|
+
const cleaned = {...rest} as OpenApiSchemaProperty;
|
|
326
|
+
if (cleaned.properties) {
|
|
327
|
+
cleaned.properties = Object.fromEntries(
|
|
328
|
+
Object.entries(cleaned.properties).map(([key, value]) => [
|
|
329
|
+
key,
|
|
330
|
+
stripBooleanRequiredFlag(value),
|
|
331
|
+
])
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
if (cleaned.items) {
|
|
335
|
+
cleaned.items = stripBooleanRequiredFlag(cleaned.items);
|
|
336
|
+
}
|
|
337
|
+
if (cleaned.oneOf) {
|
|
338
|
+
cleaned.oneOf = cleaned.oneOf.map((entry) => stripBooleanRequiredFlag(entry));
|
|
339
|
+
}
|
|
340
|
+
return cleaned;
|
|
341
|
+
}
|
|
342
|
+
if (schema.properties) {
|
|
343
|
+
return {
|
|
344
|
+
...schema,
|
|
345
|
+
properties: Object.fromEntries(
|
|
346
|
+
Object.entries(schema.properties).map(([key, value]) => [
|
|
347
|
+
key,
|
|
348
|
+
stripBooleanRequiredFlag(value),
|
|
349
|
+
])
|
|
350
|
+
),
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (schema.items) {
|
|
354
|
+
return {...schema, items: stripBooleanRequiredFlag(schema.items)};
|
|
355
|
+
}
|
|
356
|
+
if (schema.oneOf) {
|
|
357
|
+
return {...schema, oneOf: schema.oneOf.map((entry) => stripBooleanRequiredFlag(entry))};
|
|
358
|
+
}
|
|
359
|
+
return schema;
|
|
360
|
+
};
|
|
361
|
+
|
|
267
362
|
/**
|
|
268
363
|
* Get or create a compiled validator for a schema.
|
|
269
364
|
* Uses the current config so changes take effect on next call.
|
|
@@ -315,20 +410,25 @@ const formatValidationErrors = (errors: ErrorObject[]): string => {
|
|
|
315
410
|
*/
|
|
316
411
|
const propertiesToSchema = (
|
|
317
412
|
properties: Record<string, OpenApiSchemaProperty>,
|
|
318
|
-
requiredFields?: string[]
|
|
413
|
+
requiredFields?: string[],
|
|
414
|
+
options?: {partial?: boolean}
|
|
319
415
|
): OpenApiSchema => {
|
|
320
|
-
// Extract required fields from properties
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
416
|
+
// Extract required fields from properties marked required: true (OpenAPI builder style).
|
|
417
|
+
// PATCH bodies are partial: omit mongoose/OpenAPI required so one field can be sent.
|
|
418
|
+
const autoRequired = options?.partial
|
|
419
|
+
? []
|
|
420
|
+
: Object.entries(properties)
|
|
421
|
+
.filter(([_, prop]) => prop.required === true)
|
|
422
|
+
.map(([key]) => key);
|
|
423
|
+
|
|
424
|
+
const allRequired = options?.partial
|
|
425
|
+
? []
|
|
426
|
+
: [...new Set([...(requiredFields ?? []), ...autoRequired])];
|
|
427
|
+
|
|
428
|
+
// Strip boolean `required` from individual properties — AJV only accepts `required` arrays on objects
|
|
328
429
|
const cleanedProperties: Record<string, OpenApiSchemaProperty> = {};
|
|
329
430
|
for (const [key, prop] of Object.entries(properties)) {
|
|
330
|
-
|
|
331
|
-
cleanedProperties[key] = rest as OpenApiSchemaProperty;
|
|
431
|
+
cleanedProperties[key] = stripBooleanRequiredFlag(prop);
|
|
332
432
|
}
|
|
333
433
|
|
|
334
434
|
const schema: OpenApiSchema = {
|
|
@@ -360,6 +460,12 @@ export interface RequestBodyValidatorOptions {
|
|
|
360
460
|
*/
|
|
361
461
|
required?: string[];
|
|
362
462
|
|
|
463
|
+
/**
|
|
464
|
+
* When true, skip schema-level `required` (PATCH / partial update bodies).
|
|
465
|
+
* Present fields are still type-checked.
|
|
466
|
+
*/
|
|
467
|
+
partial?: boolean;
|
|
468
|
+
|
|
363
469
|
/**
|
|
364
470
|
* Fields to exclude from validation (e.g. fields set by preCreate hooks).
|
|
365
471
|
* Excluded fields are removed from both the schema properties and the required array.
|
|
@@ -392,7 +498,9 @@ export const validateRequestBody = (
|
|
|
392
498
|
schema: Record<string, OpenApiSchemaProperty>,
|
|
393
499
|
options?: RequestBodyValidatorOptions
|
|
394
500
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
395
|
-
const fullSchema = propertiesToSchema(schema, options?.required
|
|
501
|
+
const fullSchema = propertiesToSchema(schema, options?.required, {
|
|
502
|
+
partial: options?.partial,
|
|
503
|
+
});
|
|
396
504
|
|
|
397
505
|
return (req: Request, _res: Response, next: NextFunction): void => {
|
|
398
506
|
// No-op if not configured
|
|
@@ -700,10 +808,6 @@ export const validateResponseData = (
|
|
|
700
808
|
return {valid: true};
|
|
701
809
|
};
|
|
702
810
|
|
|
703
|
-
const m2sOptions = {
|
|
704
|
-
props: ["readOnly", "required", "enum", "default"],
|
|
705
|
-
};
|
|
706
|
-
|
|
707
811
|
/**
|
|
708
812
|
* Extract an OpenAPI-compatible schema from a Mongoose model.
|
|
709
813
|
* This allows you to use the same schema definitions for both documentation
|
|
@@ -713,17 +817,16 @@ const m2sOptions = {
|
|
|
713
817
|
* @returns Schema properties suitable for validation
|
|
714
818
|
*/
|
|
715
819
|
export const getSchemaFromModel = <T>(model: Model<T>): Record<string, OpenApiSchemaProperty> => {
|
|
716
|
-
const
|
|
717
|
-
|
|
718
|
-
return modelSwagger.properties as Record<string, OpenApiSchemaProperty>;
|
|
820
|
+
const {properties} = getOpenApiSpecForModel(model);
|
|
821
|
+
return properties as Record<string, OpenApiSchemaProperty>;
|
|
719
822
|
};
|
|
720
823
|
|
|
721
824
|
/**
|
|
722
825
|
* Extract required field names from a Mongoose model's swagger schema.
|
|
723
826
|
*/
|
|
724
827
|
const getRequiredFieldsFromModel = <T>(model: Model<T>): string[] => {
|
|
725
|
-
const
|
|
726
|
-
return
|
|
828
|
+
const {required} = getOpenApiSpecForModel(model);
|
|
829
|
+
return required;
|
|
727
830
|
};
|
|
728
831
|
|
|
729
832
|
/**
|
|
@@ -739,7 +842,7 @@ export const validateModelRequestBody = <T>(
|
|
|
739
842
|
options?: RequestBodyValidatorOptions
|
|
740
843
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
741
844
|
let schema = getSchemaFromModel(model);
|
|
742
|
-
let requiredFields = getRequiredFieldsFromModel(model);
|
|
845
|
+
let requiredFields = options?.partial ? [] : getRequiredFieldsFromModel(model);
|
|
743
846
|
|
|
744
847
|
if (options?.excludeFields?.length) {
|
|
745
848
|
const excluded = new Set(options.excludeFields);
|
|
@@ -749,7 +852,7 @@ export const validateModelRequestBody = <T>(
|
|
|
749
852
|
|
|
750
853
|
return validateRequestBody(schema, {
|
|
751
854
|
...options,
|
|
752
|
-
required: [...(options?.required ?? []), ...requiredFields],
|
|
855
|
+
required: options?.partial ? [] : [...(options?.required ?? []), ...requiredFields],
|
|
753
856
|
});
|
|
754
857
|
};
|
|
755
858
|
|
|
@@ -824,10 +927,86 @@ export const createModelValidators = <T>(
|
|
|
824
927
|
enabled: options?.validateUpdate,
|
|
825
928
|
onAdditionalPropertiesRemoved: options?.onAdditionalPropertiesRemoved,
|
|
826
929
|
onError: options?.onError,
|
|
930
|
+
partial: true,
|
|
827
931
|
}),
|
|
828
932
|
};
|
|
829
933
|
};
|
|
830
934
|
|
|
935
|
+
const choiceEmptyInItemSchema = (baseItem: OpenApiSchemaProperty): OpenApiSchemaProperty => {
|
|
936
|
+
if (baseItem.enum) {
|
|
937
|
+
return {
|
|
938
|
+
oneOf: [
|
|
939
|
+
{enum: baseItem.enum, type: "string"},
|
|
940
|
+
{enum: [ADMIN_LIST_CHOICE_EMPTY_VALUE], type: "string"},
|
|
941
|
+
],
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
return {
|
|
945
|
+
oneOf: [
|
|
946
|
+
stripBooleanRequiredFlag(baseItem),
|
|
947
|
+
{enum: [ADMIN_LIST_CHOICE_EMPTY_VALUE], type: "string"},
|
|
948
|
+
],
|
|
949
|
+
};
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
const buildInOperatorSchema = (itemSchema: OpenApiSchemaProperty): OpenApiSchemaProperty => ({
|
|
953
|
+
additionalProperties: false,
|
|
954
|
+
properties: {
|
|
955
|
+
$in: {
|
|
956
|
+
items: itemSchema,
|
|
957
|
+
minItems: 1,
|
|
958
|
+
type: "array",
|
|
959
|
+
},
|
|
960
|
+
},
|
|
961
|
+
required: ["$in"],
|
|
962
|
+
type: "object",
|
|
963
|
+
});
|
|
964
|
+
|
|
965
|
+
const buildRegexOperatorSchema = (): OpenApiSchemaProperty => ({
|
|
966
|
+
additionalProperties: false,
|
|
967
|
+
properties: {
|
|
968
|
+
$options: {enum: ["i"], type: "string"},
|
|
969
|
+
$regex: {escapedRegexLiteral: true, type: "string"},
|
|
970
|
+
},
|
|
971
|
+
required: ["$regex", "$options"],
|
|
972
|
+
type: "object",
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
const buildRangeOperatorSchema = (valueSchema: OpenApiSchemaProperty): OpenApiSchemaProperty => ({
|
|
976
|
+
additionalProperties: false,
|
|
977
|
+
properties: {
|
|
978
|
+
$gt: valueSchema,
|
|
979
|
+
$gte: valueSchema,
|
|
980
|
+
$lt: valueSchema,
|
|
981
|
+
$lte: valueSchema,
|
|
982
|
+
},
|
|
983
|
+
type: "object",
|
|
984
|
+
});
|
|
985
|
+
|
|
986
|
+
/** Query schema for string/enum fields: scalar, `$in`, or escaped `$regex`. */
|
|
987
|
+
export const buildStringListQueryFieldSchema = (
|
|
988
|
+
fieldSchema: OpenApiSchemaProperty
|
|
989
|
+
): OpenApiSchemaProperty => {
|
|
990
|
+
const scalar = stripBooleanRequiredFlag(fieldSchema);
|
|
991
|
+
const inItems = fieldSchema.enum
|
|
992
|
+
? choiceEmptyInItemSchema(fieldSchema)
|
|
993
|
+
: stripBooleanRequiredFlag(fieldSchema);
|
|
994
|
+
return {
|
|
995
|
+
oneOf: [scalar, buildInOperatorSchema(inItems), buildRegexOperatorSchema()],
|
|
996
|
+
};
|
|
997
|
+
};
|
|
998
|
+
|
|
999
|
+
/** Query schema for number/date fields: scalar or comparison operators. */
|
|
1000
|
+
export const buildNumericListQueryFieldSchema = (
|
|
1001
|
+
fieldSchema: OpenApiSchemaProperty
|
|
1002
|
+
): OpenApiSchemaProperty => {
|
|
1003
|
+
const scalar = stripBooleanRequiredFlag(fieldSchema);
|
|
1004
|
+
const valueSchema = stripBooleanRequiredFlag(fieldSchema);
|
|
1005
|
+
return {
|
|
1006
|
+
oneOf: [scalar, buildRangeOperatorSchema(valueSchema)],
|
|
1007
|
+
};
|
|
1008
|
+
};
|
|
1009
|
+
|
|
831
1010
|
/**
|
|
832
1011
|
* Build a query parameter schema from a model's Mongoose schema and queryFields array.
|
|
833
1012
|
* Always includes pagination parameters (limit, page, sort).
|
|
@@ -849,13 +1028,19 @@ export const buildQuerySchemaFromFields = <T>(
|
|
|
849
1028
|
|
|
850
1029
|
for (const field of queryFields) {
|
|
851
1030
|
const modelField = modelSchema[field];
|
|
852
|
-
if (modelField) {
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
querySchema[field] =
|
|
1031
|
+
if (!modelField) {
|
|
1032
|
+
querySchema[field] = buildStringListQueryFieldSchema({type: "string"});
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
if (modelField.type === "boolean") {
|
|
1036
|
+
querySchema[field] = stripBooleanRequiredFlag(modelField);
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
if (modelField.type === "number" || modelField.format === "date-time") {
|
|
1040
|
+
querySchema[field] = buildNumericListQueryFieldSchema(modelField);
|
|
1041
|
+
continue;
|
|
858
1042
|
}
|
|
1043
|
+
querySchema[field] = buildStringListQueryFieldSchema(modelField);
|
|
859
1044
|
}
|
|
860
1045
|
|
|
861
1046
|
return querySchema;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import {describe, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
3
|
+
import mongoose from "mongoose";
|
|
4
|
+
|
|
5
|
+
import type {User} from "../auth";
|
|
6
|
+
import {createAccess} from "../rbac/access";
|
|
7
|
+
import {createRbacRoleModel} from "../rbac/roleModel";
|
|
8
|
+
import {terrenoStatements} from "../rbac/statements";
|
|
9
|
+
import {setupDb} from "../tests";
|
|
10
|
+
import type {MembershipDocument} from "../types/membership";
|
|
11
|
+
import type {OrganizationDocument} from "../types/organization";
|
|
12
|
+
import {type ResolvedOrgContext, runWithOrgContext} from "./orgContext";
|
|
13
|
+
|
|
14
|
+
const createTestUser = (
|
|
15
|
+
overrides: Partial<User & {roles: string[]}> = {}
|
|
16
|
+
): User & {roles: string[]} => {
|
|
17
|
+
const id = new mongoose.Types.ObjectId();
|
|
18
|
+
return {
|
|
19
|
+
_id: id as unknown as User["_id"],
|
|
20
|
+
admin: false,
|
|
21
|
+
id: id.toString(),
|
|
22
|
+
roles: [],
|
|
23
|
+
...overrides,
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const orgAdminContext = (): ResolvedOrgContext => ({
|
|
28
|
+
membership: {roleName: "org-admin", status: "active"} as MembershipDocument,
|
|
29
|
+
organization: {_id: new mongoose.Types.ObjectId()} as OrganizationDocument,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe("optional organizations", () => {
|
|
33
|
+
it("does not seed operator or grant membership org-admin without organizations: true", async () => {
|
|
34
|
+
await setupDb();
|
|
35
|
+
const access = createAccess({
|
|
36
|
+
connection: mongoose.connection,
|
|
37
|
+
statements: terrenoStatements,
|
|
38
|
+
});
|
|
39
|
+
await access.roles.seedDefaults();
|
|
40
|
+
|
|
41
|
+
const RbacRole = createRbacRoleModel(mongoose.connection);
|
|
42
|
+
assert.isNull(await RbacRole.findOne({name: "operator"}));
|
|
43
|
+
|
|
44
|
+
const operatorList = await access.can({
|
|
45
|
+
permissions: {organization: ["list"]},
|
|
46
|
+
user: createTestUser({roles: ["operator"]}),
|
|
47
|
+
});
|
|
48
|
+
assert.isFalse(operatorList.allowed);
|
|
49
|
+
|
|
50
|
+
const orgAdminUpdate = await runWithOrgContext(orgAdminContext(), () =>
|
|
51
|
+
access.can({
|
|
52
|
+
permissions: {organization: ["update"]},
|
|
53
|
+
user: createTestUser(),
|
|
54
|
+
})
|
|
55
|
+
);
|
|
56
|
+
assert.isFalse(orgAdminUpdate.allowed);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("seeds operator and grants membership org-admin when organizations is true", async () => {
|
|
60
|
+
await setupDb();
|
|
61
|
+
const access = createAccess({
|
|
62
|
+
connection: mongoose.connection,
|
|
63
|
+
organizations: true,
|
|
64
|
+
statements: terrenoStatements,
|
|
65
|
+
});
|
|
66
|
+
await access.roles.seedDefaults();
|
|
67
|
+
|
|
68
|
+
const RbacRole = createRbacRoleModel(mongoose.connection);
|
|
69
|
+
const operator = await RbacRole.findExactlyOne({name: "operator"});
|
|
70
|
+
assert.isTrue(operator.isLocked);
|
|
71
|
+
assert.deepEqual(operator.permissions.organization, [...terrenoStatements.organization]);
|
|
72
|
+
|
|
73
|
+
const operatorList = await access.can({
|
|
74
|
+
permissions: {organization: ["list"]},
|
|
75
|
+
user: createTestUser({roles: ["operator"]}),
|
|
76
|
+
});
|
|
77
|
+
assert.isTrue(operatorList.allowed);
|
|
78
|
+
|
|
79
|
+
const orgAdminUpdate = await runWithOrgContext(orgAdminContext(), () =>
|
|
80
|
+
access.can({
|
|
81
|
+
permissions: {organization: ["update"]},
|
|
82
|
+
user: createTestUser(),
|
|
83
|
+
})
|
|
84
|
+
);
|
|
85
|
+
assert.isTrue(orgAdminUpdate.allowed);
|
|
86
|
+
});
|
|
87
|
+
});
|