@terreno/api 57.2.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 +23 -7
- package/dist/actions.js +19 -7
- package/dist/adminTypes.d.ts +7 -0
- package/dist/adminTypes.js +6 -1
- package/dist/api.d.ts +14 -0
- package/dist/api.js +111 -60
- 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/auth.d.ts +23 -10
- package/dist/auth.js +97 -32
- package/dist/authRecovery.d.ts +5 -0
- package/dist/authRecovery.js +350 -0
- package/dist/authTokens.d.ts +8 -0
- package/dist/authTokens.js +162 -0
- package/dist/betterAuth.d.ts +39 -0
- package/dist/betterAuthApp.d.ts +4 -0
- package/dist/betterAuthApp.js +26 -8
- package/dist/betterAuthSetup.d.ts +44 -2
- package/dist/betterAuthSetup.js +288 -18
- package/dist/collectionRegistry.d.ts +40 -0
- package/dist/collectionRegistry.js +97 -0
- package/dist/configurationApp.d.ts +11 -2
- package/dist/configurationApp.js +2 -4
- package/dist/docLoader.js +35 -6
- package/dist/expressServer.d.ts +26 -3
- package/dist/expressServer.js +79 -11
- package/dist/index.d.ts +42 -1
- package/dist/index.js +84 -2
- package/dist/mcp/auth.d.ts +1 -0
- package/dist/mcp/auth.js +47 -25
- package/dist/mcp/handlers.d.ts +1 -1
- package/dist/mcp/handlers.js +67 -233
- package/dist/mcp/query.d.ts +2 -15
- package/dist/mcp/query.js +8 -8
- package/dist/mcp/registry.d.ts +1 -5
- package/dist/mcp/registry.js +31 -20
- package/dist/mcp/schemaGenerator.d.ts +2 -7
- package/dist/mcp/schemaGenerator.js +41 -116
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +1 -0
- package/dist/mcp/serviceTokens.d.ts +16 -0
- package/dist/mcp/serviceTokens.js +345 -0
- package/dist/mcp/types.d.ts +2 -2
- 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/mcpServiceToken.d.ts +3 -0
- package/dist/models/mcpServiceToken.js +208 -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 +19 -7
- package/dist/openApiBuilder.js +61 -8
- package/dist/openApiCompat.js +1 -1
- package/dist/openApiValidator.d.ts +13 -1
- package/dist/openApiValidator.js +200 -38
- 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/plugins.d.ts +14 -1
- package/dist/plugins.js +17 -6
- package/dist/populate.d.ts +2 -2
- package/dist/populate.js +47 -42
- package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
- package/dist/rateLimit/applyTrustProxy.js +17 -0
- package/dist/rateLimit/createStore.d.ts +2 -0
- package/dist/rateLimit/createStore.js +28 -0
- package/dist/rateLimit/memoryStore.d.ts +2 -0
- package/dist/rateLimit/memoryStore.js +108 -0
- package/dist/rateLimit/middleware.d.ts +3 -0
- package/dist/rateLimit/middleware.js +109 -0
- package/dist/rateLimit/mongoStore.d.ts +4 -0
- package/dist/rateLimit/mongoStore.js +123 -0
- package/dist/rateLimit/policies.d.ts +10 -0
- package/dist/rateLimit/policies.js +149 -0
- package/dist/rateLimit/redisStore.d.ts +4 -0
- package/dist/rateLimit/redisStore.js +156 -0
- package/dist/rateLimit/types.d.ts +54 -0
- package/dist/rateLimit/types.js +9 -0
- package/dist/rbac/access.js +35 -14
- package/dist/rbac/assertAllowed.d.ts +9 -0
- package/dist/rbac/assertAllowed.js +182 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
- package/dist/rbac/membershipOrgAdminSource.js +122 -0
- package/dist/rbac/modelRouterAccess.d.ts +4 -0
- package/dist/rbac/modelRouterAccess.js +11 -4
- package/dist/rbac/permissionUtils.js +3 -2
- package/dist/rbac/resolve.js +65 -35
- package/dist/rbac/roleModel.d.ts +2 -5
- package/dist/rbac/roleModel.js +18 -4
- package/dist/rbac/routes.js +15 -6
- 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 +13 -0
- package/dist/realtime/deprecation.js +33 -0
- package/dist/realtime/realtimeApp.d.ts +2 -1
- package/dist/realtime/realtimeApp.js +11 -11
- package/dist/realtime/registry.d.ts +0 -31
- package/dist/realtime/registry.js +44 -31
- package/dist/realtime/socketAuth.d.ts +5 -5
- package/dist/realtime/socketAuth.js +11 -1
- package/dist/realtime/socketUser.d.ts +5 -1
- package/dist/realtime/types.d.ts +14 -4
- package/dist/schemaMetadata.d.ts +56 -0
- package/dist/schemaMetadata.js +524 -0
- package/dist/seedRunner.d.ts +88 -0
- package/dist/seedRunner.js +627 -0
- 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 +19 -3
- package/dist/sync/executors.js +194 -165
- package/dist/sync/loadHarness.js +28 -19
- package/dist/sync/models.js +26 -24
- package/dist/sync/mutationHandler.d.ts +14 -2
- package/dist/sync/mutationHandler.js +201 -76
- package/dist/sync/registrationSideEffects.d.ts +35 -0
- package/dist/sync/registrationSideEffects.js +151 -0
- package/dist/sync/registry.d.ts +2 -52
- package/dist/sync/registry.js +42 -187
- package/dist/sync/routes.d.ts +13 -0
- package/dist/sync/routes.js +116 -58
- package/dist/sync/scripts/compactTombstones.js +0 -2
- 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 +4 -3
- package/dist/sync/syncApp.js +5 -4
- package/dist/sync/syncBatch.d.ts +5 -2
- package/dist/sync/syncBatch.js +7 -6
- package/dist/sync/syncSeqPlugin.d.ts +1 -1
- package/dist/sync/syncSeqPlugin.js +20 -16
- package/dist/sync/types.d.ts +18 -0
- package/dist/terrenoApp.d.ts +48 -5
- package/dist/terrenoApp.js +157 -72
- package/dist/tests/createTestData.d.ts +1 -3
- package/dist/tests/createTestData.js +3 -5
- package/dist/tests/models.d.ts +3 -0
- package/dist/tests/models.js +15 -2
- package/dist/tests/testHelper.d.ts +0 -5
- package/dist/tests/testHelper.js +2 -9
- package/dist/types/authToken.d.ts +33 -0
- package/dist/types/authToken.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +41 -0
- package/dist/types/mcpServiceToken.js +2 -0
- 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/headerValue.d.ts +2 -0
- package/dist/webhooks/headerValue.js +14 -0
- package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
- package/dist/webhooks/idempotency/memoryStore.js +65 -0
- package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
- package/dist/webhooks/idempotency/mongoStore.js +150 -0
- package/dist/webhooks/idempotency/webhookReceipt.d.ts +17 -0
- package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
- package/dist/webhooks/rawBody.d.ts +15 -0
- package/dist/webhooks/rawBody.js +23 -0
- package/dist/webhooks/timingSafeEqual.d.ts +4 -0
- package/dist/webhooks/timingSafeEqual.js +17 -0
- package/dist/webhooks/verifiers/hmac.d.ts +15 -0
- package/dist/webhooks/verifiers/hmac.js +49 -0
- package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
- package/dist/webhooks/verifiers/sendgrid.js +56 -0
- package/dist/webhooks/verifiers/stripe.d.ts +9 -0
- package/dist/webhooks/verifiers/stripe.js +99 -0
- package/dist/webhooks/verifiers/twilio.d.ts +9 -0
- package/dist/webhooks/verifiers/twilio.js +112 -0
- package/dist/webhooks/webhooksApp.d.ts +33 -0
- package/dist/webhooks/webhooksApp.js +195 -0
- package/package.json +32 -27
- package/src/__snapshots__/openApi.test.ts.snap +444 -36
- package/src/__snapshots__/openApiBuilder.test.ts.snap +24 -24
- package/src/__snapshots__/schemaMetadata.test.ts.snap +196 -0
- package/src/actions.ts +20 -13
- package/src/adminModelRouter.test.ts +133 -0
- package/src/adminTypes.ts +8 -0
- package/src/api.arrayOperations.test.ts +43 -31
- package/src/api.hooks.test.ts +38 -29
- package/src/api.query.test.ts +31 -31
- package/src/api.test.ts +133 -97
- package/src/api.ts +84 -27
- 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 +108 -52
- package/src/auth.ts +98 -29
- package/src/authRecovery.test.ts +281 -0
- package/src/authRecovery.ts +279 -0
- package/src/authTokens.test.ts +94 -0
- package/src/authTokens.ts +118 -0
- package/src/authVerification.test.ts +293 -0
- package/src/betterAuth.ts +31 -0
- package/src/betterAuthApp.test.ts +1 -0
- package/src/betterAuthApp.ts +27 -9
- package/src/betterAuthSetup.test.ts +595 -38
- package/src/betterAuthSetup.ts +261 -5
- package/src/collectionRegistry.test.ts +164 -0
- package/src/collectionRegistry.ts +135 -0
- package/src/configurationApp.ts +13 -7
- package/src/docLoader.test.ts +45 -1
- package/src/docLoader.ts +37 -6
- package/src/express.d.ts +3 -0
- package/src/expressServer.test.ts +180 -68
- package/src/expressServer.ts +75 -19
- package/src/githubAuth.test.ts +60 -55
- package/src/index.ts +127 -0
- package/src/mcp/auth.test.ts +47 -0
- package/src/mcp/auth.ts +32 -11
- package/src/mcp/handlers.test.ts +275 -0
- package/src/mcp/handlers.ts +45 -172
- package/src/mcp/integration.test.ts +59 -9
- package/src/mcp/query.ts +5 -7
- package/src/mcp/registry.ts +29 -20
- package/src/mcp/schemaGenerator.test.ts +8 -0
- package/src/mcp/schemaGenerator.ts +49 -131
- package/src/mcp/server.ts +2 -0
- package/src/mcp/serviceTokens.test.ts +330 -0
- package/src/mcp/serviceTokens.ts +307 -0
- package/src/mcp/toolGenerator.test.ts +82 -1
- package/src/mcp/types.ts +2 -6
- 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/mcpServiceToken.test.ts +129 -0
- package/src/models/mcpServiceToken.ts +158 -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 +80 -65
- package/src/openApi.ts +2 -1
- package/src/openApiBuilder.test.ts +95 -7
- package/src/openApiBuilder.ts +60 -12
- package/src/openApiCompat.ts +1 -1
- package/src/openApiValidator.test.ts +270 -56
- package/src/openApiValidator.ts +219 -36
- 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/plugins.test.ts +14 -0
- package/src/plugins.ts +34 -9
- package/src/populate.test.ts +34 -0
- package/src/populate.ts +40 -29
- package/src/rateLimit/applyTrustProxy.ts +17 -0
- package/src/rateLimit/createStore.ts +25 -0
- package/src/rateLimit/memoryStore.ts +40 -0
- package/src/rateLimit/middleware.ts +79 -0
- package/src/rateLimit/mongoStore.test.ts +80 -0
- package/src/rateLimit/mongoStore.ts +77 -0
- package/src/rateLimit/policies.ts +130 -0
- package/src/rateLimit/rateLimit.test.ts +328 -0
- package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
- package/src/rateLimit/redisStore.test.ts +114 -0
- package/src/rateLimit/redisStore.ts +86 -0
- package/src/rateLimit/types.ts +64 -0
- package/src/rbac/access.ts +16 -4
- package/src/rbac/assertAllowed.test.ts +325 -0
- package/src/rbac/assertAllowed.ts +157 -0
- package/src/rbac/backfillAdmins.test.ts +124 -0
- package/src/rbac/fieldViews.test.ts +89 -0
- package/src/rbac/membershipOrgAdminSource.ts +59 -0
- package/src/rbac/modelRouterAccess.test.ts +126 -0
- package/src/rbac/modelRouterAccess.ts +8 -2
- package/src/rbac/permissionUtils.test.ts +26 -5
- package/src/rbac/permissionUtils.ts +3 -2
- package/src/rbac/realtimeAccess.test.ts +109 -1
- package/src/rbac/resolve.test.ts +34 -2
- package/src/rbac/resolve.ts +31 -11
- package/src/rbac/roleManager.test.ts +169 -0
- package/src/rbac/roleModel.test.ts +34 -1
- package/src/rbac/roleModel.ts +17 -1
- package/src/rbac/routes.test.ts +233 -0
- package/src/rbac/routes.ts +16 -6
- 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.test.ts +60 -0
- package/src/realtime/deprecation.ts +33 -0
- package/src/realtime/realtime.test.ts +365 -189
- package/src/realtime/realtimeApp.ts +11 -11
- package/src/realtime/realtimeAppSetup.test.ts +32 -5
- package/src/realtime/registry.ts +48 -42
- package/src/realtime/sessionRevalidation.test.ts +57 -44
- package/src/realtime/socketAuth.test.ts +75 -23
- package/src/realtime/socketAuth.ts +17 -6
- package/src/realtime/socketUser.ts +5 -3
- package/src/realtime/types.ts +14 -4
- package/src/schemaMetadata.test.ts +419 -0
- package/src/schemaMetadata.ts +593 -0
- package/src/scrubAdminFields.test.ts +105 -0
- package/src/seedRunner.test.ts +591 -0
- package/src/seedRunner.ts +464 -0
- 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/docMatchesMutationData.test.ts +16 -0
- package/src/sync/ensureSyncIndexes.test.ts +54 -15
- package/src/sync/executors.test.ts +40 -0
- package/src/sync/executors.ts +57 -18
- package/src/sync/integration.test.ts +15 -7
- package/src/sync/loadHarness.ts +28 -19
- package/src/sync/models.ts +32 -18
- package/src/sync/mutationHandler.test.ts +293 -17
- package/src/sync/mutationHandler.ts +180 -36
- package/src/sync/registrationSideEffects.test.ts +126 -0
- package/src/sync/registrationSideEffects.ts +131 -0
- package/src/sync/registry.ts +49 -171
- package/src/sync/routes.ts +55 -10
- package/src/sync/scripts/compactTombstones.ts +0 -2
- package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
- package/src/sync/socketHandlers.ts +154 -58
- package/src/sync/streams.ts +6 -0
- package/src/sync/sync.test.ts +28 -25
- package/src/sync/syncApp.ts +5 -4
- package/src/sync/syncBatch.ts +10 -4
- package/src/sync/syncFrontier.test.ts +17 -15
- package/src/sync/syncPhaseC.test.ts +54 -43
- package/src/sync/syncRoutes.test.ts +347 -38
- package/src/sync/syncSeqPlugin.ts +66 -44
- package/src/sync/syncSocket.test.ts +341 -81
- package/src/sync/types.ts +20 -0
- package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
- package/src/terrenoApp.migrations.test.ts +114 -0
- package/src/terrenoApp.test.ts +41 -0
- package/src/terrenoApp.ts +181 -46
- package/src/tests/createTestData.ts +2 -2
- package/src/tests/models.ts +24 -3
- package/src/tests/testHelper.ts +1 -7
- package/src/types/authToken.ts +41 -0
- package/src/types/mcpServiceToken.ts +48 -0
- 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/headerValue.test.ts +22 -0
- package/src/webhooks/headerValue.ts +12 -0
- package/src/webhooks/idempotency/memoryStore.ts +34 -0
- package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
- package/src/webhooks/idempotency/mongoStore.ts +83 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +67 -0
- package/src/webhooks/rawBody.test.ts +107 -0
- package/src/webhooks/rawBody.ts +24 -0
- package/src/webhooks/timingSafeEqual.ts +16 -0
- package/src/webhooks/verifiers/hmac.test.ts +110 -0
- package/src/webhooks/verifiers/hmac.ts +54 -0
- package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
- package/src/webhooks/verifiers/sendgrid.ts +59 -0
- package/src/webhooks/verifiers/stripe.ts +67 -0
- package/src/webhooks/verifiers/twilio.ts +69 -0
- package/src/webhooks/webhooksApp.test.ts +221 -0
- package/src/webhooks/webhooksApp.ts +144 -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
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
import {type Application, Router} from "express";
|
|
3
|
+
import type mongoose from "mongoose";
|
|
4
|
+
|
|
5
|
+
import {asyncHandler, type OpenApiMiddleware} from "../api";
|
|
6
|
+
import {authenticateMiddleware, type User, type UserModel} from "../auth";
|
|
7
|
+
import {APIError, ConflictError, ForbiddenError, NotFoundError} from "../errors";
|
|
8
|
+
import {logger} from "../logger";
|
|
9
|
+
import {createOpenApiBuilder, type OpenApiSchemaProperty} from "../openApiBuilder";
|
|
10
|
+
import {findOneOrNoneFor} from "../plugins";
|
|
11
|
+
import type {AnyTerrenoAccess} from "../rbac/types";
|
|
12
|
+
import type {TerrenoPlugin} from "../terrenoPlugin";
|
|
13
|
+
import type {MembershipDocument} from "../types/membership";
|
|
14
|
+
import type {OrganizationDocument} from "../types/organization";
|
|
15
|
+
import {
|
|
16
|
+
assertOrganizationSlugAvailable,
|
|
17
|
+
Membership,
|
|
18
|
+
Organization,
|
|
19
|
+
organizationSlugFromName,
|
|
20
|
+
} from "./organizationModel";
|
|
21
|
+
import {registerOrganizationSettings} from "./organizationSettings";
|
|
22
|
+
import {assertOrganizationEnabled, isPlatformOrgActor, runWithOrgContext} from "./orgContext";
|
|
23
|
+
|
|
24
|
+
const escapeRegularExpression = (value: string): string => {
|
|
25
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const findUserForAttach = async (
|
|
29
|
+
userModel: UserModel,
|
|
30
|
+
args: {email: string; userId: string}
|
|
31
|
+
): Promise<User | null> => {
|
|
32
|
+
if (args.email) {
|
|
33
|
+
return findOneOrNoneFor(userModel, {
|
|
34
|
+
email: {$options: "i", $regex: `^${escapeRegularExpression(args.email)}$`},
|
|
35
|
+
} as never);
|
|
36
|
+
}
|
|
37
|
+
if (args.userId) {
|
|
38
|
+
return findOneOrNoneFor(userModel, {_id: args.userId} as never);
|
|
39
|
+
}
|
|
40
|
+
throw new APIError({status: 400, title: "email or userId is required"});
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export interface OrgAuditEvent {
|
|
44
|
+
actorId?: string;
|
|
45
|
+
organizationId?: string;
|
|
46
|
+
organizationLabel?: string;
|
|
47
|
+
verb:
|
|
48
|
+
| "created"
|
|
49
|
+
| "updated"
|
|
50
|
+
| "disabled"
|
|
51
|
+
| "deleted"
|
|
52
|
+
| "memberAttached"
|
|
53
|
+
| "memberUpdated"
|
|
54
|
+
| "memberRemoved";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface OrgsAppOptions {
|
|
58
|
+
access: AnyTerrenoAccess;
|
|
59
|
+
basePath?: string;
|
|
60
|
+
onOrgAudit?: (event: OrgAuditEvent, req: express.Request) => void | Promise<void>;
|
|
61
|
+
/** Nested schema for `Organization.settings`. Same as `registerOrganizationSettings`. */
|
|
62
|
+
settingsSchema?: mongoose.Schema;
|
|
63
|
+
userModel: UserModel;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const pathParam = (value: string | string[] | undefined, title: string): string => {
|
|
67
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
68
|
+
throw new APIError({status: 400, title});
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const userIdOf = (user: User): string => {
|
|
74
|
+
if (user._id) {
|
|
75
|
+
return String(user._id);
|
|
76
|
+
}
|
|
77
|
+
return user.id;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const requireUser = (req: express.Request): User => {
|
|
81
|
+
const user = req.user as User | undefined;
|
|
82
|
+
if (!user?.id) {
|
|
83
|
+
throw new APIError({status: 401, title: "Unauthorized"});
|
|
84
|
+
}
|
|
85
|
+
return user;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const emitOrgAudit = async (args: {
|
|
89
|
+
event: OrgAuditEvent;
|
|
90
|
+
onOrgAudit?: OrgsAppOptions["onOrgAudit"];
|
|
91
|
+
req: express.Request;
|
|
92
|
+
}): Promise<void> => {
|
|
93
|
+
if (!args.onOrgAudit) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
await args.onOrgAudit(args.event, args.req);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
100
|
+
logger.error(`onOrgAudit failed after ${args.event.verb}: ${detail}`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const loadOrganization = async (id: string): Promise<OrganizationDocument> => {
|
|
105
|
+
const organization = await Organization.findOneOrNone({_id: id});
|
|
106
|
+
if (!organization) {
|
|
107
|
+
throw new NotFoundError("Organization not found");
|
|
108
|
+
}
|
|
109
|
+
return organization;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const loadActiveMembership = async (
|
|
113
|
+
user: User,
|
|
114
|
+
organizationId: OrganizationDocument["_id"]
|
|
115
|
+
): Promise<MembershipDocument | undefined> => {
|
|
116
|
+
const membership = await Membership.findOneOrNone({
|
|
117
|
+
organizationId,
|
|
118
|
+
status: "active",
|
|
119
|
+
userId: userIdOf(user),
|
|
120
|
+
});
|
|
121
|
+
return membership ?? undefined;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const countActiveOrgAdmins = async (
|
|
125
|
+
organizationId: OrganizationDocument["_id"]
|
|
126
|
+
): Promise<number> => {
|
|
127
|
+
return Membership.countDocuments({
|
|
128
|
+
organizationId,
|
|
129
|
+
roleName: "org-admin",
|
|
130
|
+
status: "active",
|
|
131
|
+
});
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const assertNotLastOrgAdmin = async (
|
|
135
|
+
membership: MembershipDocument,
|
|
136
|
+
nextRoleName?: string,
|
|
137
|
+
nextStatus?: string
|
|
138
|
+
): Promise<void> => {
|
|
139
|
+
const remainsOrgAdmin =
|
|
140
|
+
(nextRoleName ?? membership.roleName) === "org-admin" &&
|
|
141
|
+
(nextStatus ?? membership.status) === "active";
|
|
142
|
+
if (remainsOrgAdmin) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (membership.roleName !== "org-admin" || membership.status !== "active") {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const activeAdmins = await countActiveOrgAdmins(membership.organizationId);
|
|
149
|
+
if (activeAdmins <= 1) {
|
|
150
|
+
throw new APIError({status: 400, title: "Cannot remove the last org-admin"});
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const assertCan = async (args: {
|
|
155
|
+
access: AnyTerrenoAccess;
|
|
156
|
+
organization?: OrganizationDocument;
|
|
157
|
+
permissions: {organization: string[]};
|
|
158
|
+
user: User;
|
|
159
|
+
}): Promise<void> => {
|
|
160
|
+
const result = await args.access.can({
|
|
161
|
+
doc: args.organization,
|
|
162
|
+
permissions: args.permissions,
|
|
163
|
+
user: args.user,
|
|
164
|
+
});
|
|
165
|
+
if (result.allowed) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
throw new ForbiddenError(result.reason ?? "Access denied");
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export class OrgsApp implements TerrenoPlugin {
|
|
172
|
+
private readonly access: AnyTerrenoAccess;
|
|
173
|
+
private readonly basePath: string;
|
|
174
|
+
private readonly onOrgAudit?: OrgsAppOptions["onOrgAudit"];
|
|
175
|
+
private readonly userModel: UserModel;
|
|
176
|
+
|
|
177
|
+
constructor(options: OrgsAppOptions) {
|
|
178
|
+
this.access = options.access;
|
|
179
|
+
this.basePath = options.basePath ?? "/orgs";
|
|
180
|
+
this.onOrgAudit = options.onOrgAudit;
|
|
181
|
+
this.userModel = options.userModel;
|
|
182
|
+
if (options.settingsSchema) {
|
|
183
|
+
registerOrganizationSettings(options.settingsSchema);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
register(app: Application, openApi?: unknown): void {
|
|
188
|
+
const router = Router();
|
|
189
|
+
const openApiMiddleware = openApi as OpenApiMiddleware | undefined;
|
|
190
|
+
const docs = (
|
|
191
|
+
summary: string,
|
|
192
|
+
requestBody?: Record<string, OpenApiSchemaProperty>
|
|
193
|
+
): ReturnType<ReturnType<typeof createOpenApiBuilder>["build"]> => {
|
|
194
|
+
const builder = createOpenApiBuilder({openApi: openApiMiddleware})
|
|
195
|
+
.withTags(["organizations"])
|
|
196
|
+
.withSummary(summary);
|
|
197
|
+
if (requestBody) {
|
|
198
|
+
builder.withRequestBody(requestBody);
|
|
199
|
+
}
|
|
200
|
+
return builder.build();
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
router.post(
|
|
204
|
+
"/",
|
|
205
|
+
authenticateMiddleware(),
|
|
206
|
+
this.access.middleware({organization: ["create"]}),
|
|
207
|
+
docs("Create an organization", {
|
|
208
|
+
name: {description: "Organization name", required: true, type: "string"},
|
|
209
|
+
settings: {description: "App-defined organization settings", type: "object"},
|
|
210
|
+
}),
|
|
211
|
+
asyncHandler(async (req, res) => {
|
|
212
|
+
const user = requireUser(req);
|
|
213
|
+
const name = typeof req.body?.name === "string" ? req.body.name.trim() : "";
|
|
214
|
+
if (!name) {
|
|
215
|
+
throw new APIError({status: 400, title: "name is required"});
|
|
216
|
+
}
|
|
217
|
+
await assertOrganizationSlugAvailable(organizationSlugFromName(name));
|
|
218
|
+
const organization = await Organization.create({
|
|
219
|
+
name,
|
|
220
|
+
ownerId: userIdOf(user),
|
|
221
|
+
settings: req.body?.settings,
|
|
222
|
+
});
|
|
223
|
+
await emitOrgAudit({
|
|
224
|
+
event: {
|
|
225
|
+
actorId: user.id,
|
|
226
|
+
organizationId: String(organization._id),
|
|
227
|
+
organizationLabel: organization.name,
|
|
228
|
+
verb: "created",
|
|
229
|
+
},
|
|
230
|
+
onOrgAudit: this.onOrgAudit,
|
|
231
|
+
req,
|
|
232
|
+
});
|
|
233
|
+
return res.status(201).json({data: organization});
|
|
234
|
+
})
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
router.get(
|
|
238
|
+
"/",
|
|
239
|
+
authenticateMiddleware(),
|
|
240
|
+
this.access.middleware({organization: ["list"]}),
|
|
241
|
+
docs("List all organizations"),
|
|
242
|
+
asyncHandler(async (_req, res) => {
|
|
243
|
+
const organizations = await Organization.find({}).sort({name: 1});
|
|
244
|
+
return res.json({data: organizations});
|
|
245
|
+
})
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
router.get(
|
|
249
|
+
"/mine",
|
|
250
|
+
authenticateMiddleware(),
|
|
251
|
+
docs("List organizations the caller may switch into"),
|
|
252
|
+
asyncHandler(async (req, res) => {
|
|
253
|
+
const user = requireUser(req);
|
|
254
|
+
if (isPlatformOrgActor(user)) {
|
|
255
|
+
const organizations = await Organization.find({disabled: {$ne: true}}).sort({name: 1});
|
|
256
|
+
return res.json({data: organizations});
|
|
257
|
+
}
|
|
258
|
+
const memberships = await Membership.find({
|
|
259
|
+
roleName: "org-admin",
|
|
260
|
+
status: "active",
|
|
261
|
+
userId: userIdOf(user),
|
|
262
|
+
});
|
|
263
|
+
if (memberships.length === 0) {
|
|
264
|
+
throw new ForbiddenError("Access denied");
|
|
265
|
+
}
|
|
266
|
+
const organizations = await Organization.find({
|
|
267
|
+
_id: {$in: memberships.map((membership) => membership.organizationId)},
|
|
268
|
+
disabled: {$ne: true},
|
|
269
|
+
}).sort({name: 1});
|
|
270
|
+
return res.json({data: organizations});
|
|
271
|
+
})
|
|
272
|
+
);
|
|
273
|
+
|
|
274
|
+
router.get(
|
|
275
|
+
"/:id",
|
|
276
|
+
authenticateMiddleware(),
|
|
277
|
+
docs("Read an organization"),
|
|
278
|
+
asyncHandler(async (req, res) => {
|
|
279
|
+
const user = requireUser(req);
|
|
280
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
281
|
+
const membership = await loadActiveMembership(user, organization._id);
|
|
282
|
+
await runWithOrgContext({membership, organization}, () =>
|
|
283
|
+
assertCan({
|
|
284
|
+
access: this.access,
|
|
285
|
+
organization,
|
|
286
|
+
permissions: {organization: ["read"]},
|
|
287
|
+
user,
|
|
288
|
+
})
|
|
289
|
+
);
|
|
290
|
+
return res.json({data: organization});
|
|
291
|
+
})
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
router.patch(
|
|
295
|
+
"/:id",
|
|
296
|
+
authenticateMiddleware(),
|
|
297
|
+
docs("Update an organization", {
|
|
298
|
+
disabled: {description: "Disable the organization", type: "boolean"},
|
|
299
|
+
name: {description: "Organization name", type: "string"},
|
|
300
|
+
settings: {description: "App-defined organization settings", type: "object"},
|
|
301
|
+
}),
|
|
302
|
+
asyncHandler(async (req, res) => {
|
|
303
|
+
const user = requireUser(req);
|
|
304
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
305
|
+
const membership = await loadActiveMembership(user, organization._id);
|
|
306
|
+
const body = req.body ?? {};
|
|
307
|
+
const wantsDisable = "disabled" in body && Boolean(body.disabled) && !organization.disabled;
|
|
308
|
+
|
|
309
|
+
await runWithOrgContext({membership, organization}, async () => {
|
|
310
|
+
await assertCan({
|
|
311
|
+
access: this.access,
|
|
312
|
+
organization,
|
|
313
|
+
permissions: {organization: ["update"]},
|
|
314
|
+
user,
|
|
315
|
+
});
|
|
316
|
+
if (wantsDisable) {
|
|
317
|
+
await assertCan({
|
|
318
|
+
access: this.access,
|
|
319
|
+
organization,
|
|
320
|
+
permissions: {organization: ["disable"]},
|
|
321
|
+
user,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
if (typeof body.name === "string" && body.name.trim()) {
|
|
327
|
+
const trimmedName = body.name.trim();
|
|
328
|
+
const slug = organizationSlugFromName(trimmedName);
|
|
329
|
+
await assertOrganizationSlugAvailable(slug, organization._id);
|
|
330
|
+
organization.name = trimmedName;
|
|
331
|
+
organization.slug = slug;
|
|
332
|
+
}
|
|
333
|
+
if ("settings" in body) {
|
|
334
|
+
organization.settings = body.settings;
|
|
335
|
+
}
|
|
336
|
+
if ("disabled" in body) {
|
|
337
|
+
organization.disabled = Boolean(body.disabled);
|
|
338
|
+
}
|
|
339
|
+
await organization.save();
|
|
340
|
+
if (wantsDisable) {
|
|
341
|
+
await Membership.updateMany({organizationId: organization._id}, {status: "suspended"});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
await emitOrgAudit({
|
|
345
|
+
event: {
|
|
346
|
+
actorId: user.id,
|
|
347
|
+
organizationId: String(organization._id),
|
|
348
|
+
organizationLabel: organization.name,
|
|
349
|
+
verb: wantsDisable ? "disabled" : "updated",
|
|
350
|
+
},
|
|
351
|
+
onOrgAudit: this.onOrgAudit,
|
|
352
|
+
req,
|
|
353
|
+
});
|
|
354
|
+
return res.json({data: organization});
|
|
355
|
+
})
|
|
356
|
+
);
|
|
357
|
+
|
|
358
|
+
router.delete(
|
|
359
|
+
"/:id",
|
|
360
|
+
authenticateMiddleware(),
|
|
361
|
+
this.access.middleware({organization: ["delete"]}),
|
|
362
|
+
docs("Soft-delete an organization"),
|
|
363
|
+
asyncHandler(async (req, res) => {
|
|
364
|
+
const user = requireUser(req);
|
|
365
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
366
|
+
organization.deleted = true;
|
|
367
|
+
await organization.save();
|
|
368
|
+
await Membership.updateMany({organizationId: organization._id}, {status: "suspended"});
|
|
369
|
+
await emitOrgAudit({
|
|
370
|
+
event: {
|
|
371
|
+
actorId: user.id,
|
|
372
|
+
organizationId: String(organization._id),
|
|
373
|
+
organizationLabel: organization.name,
|
|
374
|
+
verb: "deleted",
|
|
375
|
+
},
|
|
376
|
+
onOrgAudit: this.onOrgAudit,
|
|
377
|
+
req,
|
|
378
|
+
});
|
|
379
|
+
return res.status(204).send();
|
|
380
|
+
})
|
|
381
|
+
);
|
|
382
|
+
|
|
383
|
+
router.get(
|
|
384
|
+
"/:id/members",
|
|
385
|
+
authenticateMiddleware(),
|
|
386
|
+
docs("List organization members"),
|
|
387
|
+
asyncHandler(async (req, res) => {
|
|
388
|
+
const user = requireUser(req);
|
|
389
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
390
|
+
const membership = await loadActiveMembership(user, organization._id);
|
|
391
|
+
await runWithOrgContext({membership, organization}, () =>
|
|
392
|
+
assertCan({
|
|
393
|
+
access: this.access,
|
|
394
|
+
organization,
|
|
395
|
+
permissions: {organization: ["manageMembers"]},
|
|
396
|
+
user,
|
|
397
|
+
})
|
|
398
|
+
);
|
|
399
|
+
const members = await Membership.find({organizationId: organization._id})
|
|
400
|
+
.sort({created: 1})
|
|
401
|
+
.populate({path: "userId", select: "email name"});
|
|
402
|
+
return res.json({data: members});
|
|
403
|
+
})
|
|
404
|
+
);
|
|
405
|
+
|
|
406
|
+
router.post(
|
|
407
|
+
"/:id/members",
|
|
408
|
+
authenticateMiddleware(),
|
|
409
|
+
docs("Attach an existing user as a member", {
|
|
410
|
+
email: {description: "Existing user email", type: "string"},
|
|
411
|
+
roleName: {
|
|
412
|
+
description: "Membership role",
|
|
413
|
+
type: "string",
|
|
414
|
+
},
|
|
415
|
+
userId: {description: "Existing user id", type: "string"},
|
|
416
|
+
}),
|
|
417
|
+
asyncHandler(async (req, res) => {
|
|
418
|
+
const user = requireUser(req);
|
|
419
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
420
|
+
assertOrganizationEnabled(organization);
|
|
421
|
+
const actorMembership = await loadActiveMembership(user, organization._id);
|
|
422
|
+
await runWithOrgContext({membership: actorMembership, organization}, () =>
|
|
423
|
+
assertCan({
|
|
424
|
+
access: this.access,
|
|
425
|
+
organization,
|
|
426
|
+
permissions: {organization: ["manageMembers"]},
|
|
427
|
+
user,
|
|
428
|
+
})
|
|
429
|
+
);
|
|
430
|
+
const email = typeof req.body?.email === "string" ? req.body.email.trim() : "";
|
|
431
|
+
const userId = typeof req.body?.userId === "string" ? req.body.userId.trim() : "";
|
|
432
|
+
const target = await findUserForAttach(this.userModel, {email, userId});
|
|
433
|
+
if (!target) {
|
|
434
|
+
throw new NotFoundError("User not found");
|
|
435
|
+
}
|
|
436
|
+
const existing = await Membership.findOneOrNone({
|
|
437
|
+
organizationId: organization._id,
|
|
438
|
+
userId: userIdOf(target),
|
|
439
|
+
});
|
|
440
|
+
if (existing) {
|
|
441
|
+
throw new ConflictError("User is already a member");
|
|
442
|
+
}
|
|
443
|
+
const roleName = req.body?.roleName === "org-admin" ? "org-admin" : "member";
|
|
444
|
+
const created = await Membership.create({
|
|
445
|
+
organizationId: organization._id,
|
|
446
|
+
roleName,
|
|
447
|
+
userId: userIdOf(target),
|
|
448
|
+
});
|
|
449
|
+
await emitOrgAudit({
|
|
450
|
+
event: {
|
|
451
|
+
actorId: user.id,
|
|
452
|
+
organizationId: String(organization._id),
|
|
453
|
+
organizationLabel: organization.name,
|
|
454
|
+
verb: "memberAttached",
|
|
455
|
+
},
|
|
456
|
+
onOrgAudit: this.onOrgAudit,
|
|
457
|
+
req,
|
|
458
|
+
});
|
|
459
|
+
return res.status(201).json({data: created});
|
|
460
|
+
})
|
|
461
|
+
);
|
|
462
|
+
|
|
463
|
+
router.patch(
|
|
464
|
+
"/:id/members/:memberId",
|
|
465
|
+
authenticateMiddleware(),
|
|
466
|
+
docs("Update a membership", {
|
|
467
|
+
roleName: {
|
|
468
|
+
description: "Membership role",
|
|
469
|
+
type: "string",
|
|
470
|
+
},
|
|
471
|
+
status: {
|
|
472
|
+
description: "Membership status",
|
|
473
|
+
type: "string",
|
|
474
|
+
},
|
|
475
|
+
}),
|
|
476
|
+
asyncHandler(async (req, res) => {
|
|
477
|
+
const user = requireUser(req);
|
|
478
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
479
|
+
assertOrganizationEnabled(organization);
|
|
480
|
+
const actorMembership = await loadActiveMembership(user, organization._id);
|
|
481
|
+
await runWithOrgContext({membership: actorMembership, organization}, () =>
|
|
482
|
+
assertCan({
|
|
483
|
+
access: this.access,
|
|
484
|
+
organization,
|
|
485
|
+
permissions: {organization: ["manageMembers"]},
|
|
486
|
+
user,
|
|
487
|
+
})
|
|
488
|
+
);
|
|
489
|
+
const member = await Membership.findOneOrNone({
|
|
490
|
+
_id: pathParam(req.params.memberId, "memberId is required"),
|
|
491
|
+
organizationId: organization._id,
|
|
492
|
+
});
|
|
493
|
+
if (!member) {
|
|
494
|
+
throw new NotFoundError("Membership not found");
|
|
495
|
+
}
|
|
496
|
+
const nextRoleName =
|
|
497
|
+
typeof req.body?.roleName === "string" ? req.body.roleName : member.roleName;
|
|
498
|
+
const nextStatus = typeof req.body?.status === "string" ? req.body.status : member.status;
|
|
499
|
+
await assertNotLastOrgAdmin(member, nextRoleName, nextStatus);
|
|
500
|
+
if (typeof req.body?.roleName === "string") {
|
|
501
|
+
member.roleName = req.body.roleName === "org-admin" ? "org-admin" : "member";
|
|
502
|
+
}
|
|
503
|
+
if (typeof req.body?.status === "string") {
|
|
504
|
+
member.status = req.body.status === "suspended" ? "suspended" : "active";
|
|
505
|
+
}
|
|
506
|
+
await member.save();
|
|
507
|
+
await emitOrgAudit({
|
|
508
|
+
event: {
|
|
509
|
+
actorId: user.id,
|
|
510
|
+
organizationId: String(organization._id),
|
|
511
|
+
organizationLabel: organization.name,
|
|
512
|
+
verb: "memberUpdated",
|
|
513
|
+
},
|
|
514
|
+
onOrgAudit: this.onOrgAudit,
|
|
515
|
+
req,
|
|
516
|
+
});
|
|
517
|
+
return res.json({data: member});
|
|
518
|
+
})
|
|
519
|
+
);
|
|
520
|
+
|
|
521
|
+
router.delete(
|
|
522
|
+
"/:id/members/:memberId",
|
|
523
|
+
authenticateMiddleware(),
|
|
524
|
+
docs("Remove a membership"),
|
|
525
|
+
asyncHandler(async (req, res) => {
|
|
526
|
+
const user = requireUser(req);
|
|
527
|
+
const organization = await loadOrganization(pathParam(req.params.id, "id is required"));
|
|
528
|
+
assertOrganizationEnabled(organization);
|
|
529
|
+
const actorMembership = await loadActiveMembership(user, organization._id);
|
|
530
|
+
await runWithOrgContext({membership: actorMembership, organization}, () =>
|
|
531
|
+
assertCan({
|
|
532
|
+
access: this.access,
|
|
533
|
+
organization,
|
|
534
|
+
permissions: {organization: ["manageMembers"]},
|
|
535
|
+
user,
|
|
536
|
+
})
|
|
537
|
+
);
|
|
538
|
+
const member = await Membership.findOneOrNone({
|
|
539
|
+
_id: pathParam(req.params.memberId, "memberId is required"),
|
|
540
|
+
organizationId: organization._id,
|
|
541
|
+
});
|
|
542
|
+
if (!member) {
|
|
543
|
+
throw new NotFoundError("Membership not found");
|
|
544
|
+
}
|
|
545
|
+
await assertNotLastOrgAdmin(member, "member", "suspended");
|
|
546
|
+
await member.deleteOne();
|
|
547
|
+
await emitOrgAudit({
|
|
548
|
+
event: {
|
|
549
|
+
actorId: user.id,
|
|
550
|
+
organizationId: String(organization._id),
|
|
551
|
+
organizationLabel: organization.name,
|
|
552
|
+
verb: "memberRemoved",
|
|
553
|
+
},
|
|
554
|
+
onOrgAudit: this.onOrgAudit,
|
|
555
|
+
req,
|
|
556
|
+
});
|
|
557
|
+
return res.status(204).send();
|
|
558
|
+
})
|
|
559
|
+
);
|
|
560
|
+
|
|
561
|
+
app.use(this.basePath, router);
|
|
562
|
+
}
|
|
563
|
+
}
|
package/src/permissions.test.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
2
2
|
import type express from "express";
|
|
3
|
+
import mongoose from "mongoose";
|
|
3
4
|
import supertest from "supertest";
|
|
4
5
|
import type TestAgent from "supertest/lib/agent";
|
|
5
6
|
|
|
@@ -10,6 +11,8 @@ import {
|
|
|
10
11
|
addAuthRoutes,
|
|
11
12
|
setupAuth,
|
|
12
13
|
} from "./auth";
|
|
14
|
+
import {Membership, Organization} from "./orgs/organizationModel";
|
|
15
|
+
import {runWithOrgContext} from "./orgs/orgContext";
|
|
13
16
|
import {
|
|
14
17
|
getUserOrganizationIds,
|
|
15
18
|
OrganizationQueryFilter,
|
|
@@ -249,59 +252,82 @@ describe("permissions module", () => {
|
|
|
249
252
|
});
|
|
250
253
|
|
|
251
254
|
describe("OrganizationQueryFilter", () => {
|
|
252
|
-
it("
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
it("returns an empty $in filter when the user has no organizations", () => {
|
|
260
|
-
const user = testUser({id: "u1"});
|
|
261
|
-
expect(OrganizationQueryFilter(user)).toEqual({organizationId: {$in: []}});
|
|
255
|
+
it("scopes to the request organization context", () => {
|
|
256
|
+
const orgId = new mongoose.Types.ObjectId();
|
|
257
|
+
const filter = runWithOrgContext({organization: {_id: orgId} as never}, () =>
|
|
258
|
+
OrganizationQueryFilter(testUser({id: "u1"}))
|
|
259
|
+
);
|
|
260
|
+
expect(filter).toEqual({organizationId: orgId});
|
|
262
261
|
});
|
|
263
262
|
|
|
264
|
-
it("
|
|
265
|
-
expect(OrganizationQueryFilter(
|
|
263
|
+
it("throws when organization context is missing", () => {
|
|
264
|
+
expect(() => OrganizationQueryFilter(testUser({id: "u1"}))).toThrow(
|
|
265
|
+
"Organization context required"
|
|
266
|
+
);
|
|
267
|
+
expect(() => OrganizationQueryFilter(undefined)).toThrow("Organization context required");
|
|
266
268
|
});
|
|
267
269
|
});
|
|
268
270
|
|
|
269
271
|
describe("Permissions.IsOrganizationMember", () => {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
272
|
+
beforeEach(async () => {
|
|
273
|
+
await Membership.deleteMany({});
|
|
274
|
+
await Organization.deleteMany({});
|
|
273
275
|
});
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
false
|
|
276
|
+
it("returns true when no object is provided", async () => {
|
|
277
|
+
expect(await Permissions.IsOrganizationMember("list", testUser({id: "u1"}), undefined)).toBe(
|
|
278
|
+
true
|
|
278
279
|
);
|
|
279
280
|
});
|
|
280
281
|
|
|
281
|
-
it("returns
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
);
|
|
282
|
+
it("returns false when there is no user", async () => {
|
|
283
|
+
expect(
|
|
284
|
+
await Permissions.IsOrganizationMember("read", undefined, {organizationId: "org-1"})
|
|
285
|
+
).toBe(false);
|
|
286
286
|
});
|
|
287
287
|
|
|
288
|
-
it("returns
|
|
289
|
-
const user = testUser({
|
|
290
|
-
|
|
291
|
-
true
|
|
292
|
-
|
|
288
|
+
it("returns false for user.admin without platform org roles", async () => {
|
|
289
|
+
const user = testUser({
|
|
290
|
+
_id: new mongoose.Types.ObjectId(),
|
|
291
|
+
admin: true,
|
|
292
|
+
id: new mongoose.Types.ObjectId().toString(),
|
|
293
|
+
});
|
|
294
|
+
expect(
|
|
295
|
+
await Permissions.IsOrganizationMember("update", user, {
|
|
296
|
+
organizationId: new mongoose.Types.ObjectId(),
|
|
297
|
+
})
|
|
298
|
+
).toBe(false);
|
|
293
299
|
});
|
|
294
300
|
|
|
295
|
-
it("returns
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
301
|
+
it("returns true when the caller has an active membership in the active org context", async () => {
|
|
302
|
+
const org = await Organization.create({
|
|
303
|
+
name: "Perm Org",
|
|
304
|
+
ownerId: new mongoose.Types.ObjectId(),
|
|
305
|
+
});
|
|
306
|
+
const userId = new mongoose.Types.ObjectId();
|
|
307
|
+
await Membership.create({
|
|
308
|
+
organizationId: org._id,
|
|
309
|
+
roleName: "member",
|
|
310
|
+
userId,
|
|
311
|
+
});
|
|
312
|
+
const user = testUser({_id: userId, id: userId.toString()});
|
|
313
|
+
const allowed = await runWithOrgContext({organization: org}, () =>
|
|
314
|
+
Permissions.IsOrganizationMember("update", user, {organizationId: org._id})
|
|
299
315
|
);
|
|
316
|
+
expect(await allowed).toBe(true);
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it("returns false when the user does not belong to the document's organization", async () => {
|
|
320
|
+
const user = testUser({id: new mongoose.Types.ObjectId().toString()});
|
|
321
|
+
expect(
|
|
322
|
+
await Permissions.IsOrganizationMember("update", user, {
|
|
323
|
+
organizationId: new mongoose.Types.ObjectId(),
|
|
324
|
+
})
|
|
325
|
+
).toBe(false);
|
|
300
326
|
});
|
|
301
327
|
|
|
302
|
-
it("returns false when the document has no organizationId", () => {
|
|
303
|
-
const user = testUser({id: "u1"
|
|
304
|
-
expect(Permissions.IsOrganizationMember("read", user, {})).toBe(false);
|
|
328
|
+
it("returns false when the document has no organizationId", async () => {
|
|
329
|
+
const user = testUser({id: "u1"});
|
|
330
|
+
expect(await Permissions.IsOrganizationMember("read", user, {})).toBe(false);
|
|
305
331
|
});
|
|
306
332
|
});
|
|
307
333
|
|