@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.
Files changed (293) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +6 -0
  3. package/dist/adminTypes.d.ts +7 -0
  4. package/dist/adminTypes.js +6 -1
  5. package/dist/api.d.ts +10 -0
  6. package/dist/api.js +99 -36
  7. package/dist/audit/auditApp.d.ts +30 -0
  8. package/dist/audit/auditApp.js +155 -0
  9. package/dist/audit/auditEventModel.d.ts +29 -0
  10. package/dist/audit/auditEventModel.js +102 -0
  11. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  12. package/dist/audit/cloudTasksEnqueue.js +162 -0
  13. package/dist/audit/diff.d.ts +10 -0
  14. package/dist/audit/diff.js +230 -0
  15. package/dist/audit/processQueue.d.ts +6 -0
  16. package/dist/audit/processQueue.js +101 -0
  17. package/dist/audit/rbacSink.d.ts +2 -0
  18. package/dist/audit/rbacSink.js +82 -0
  19. package/dist/audit/record.d.ts +56 -0
  20. package/dist/audit/record.js +373 -0
  21. package/dist/betterAuth.d.ts +6 -0
  22. package/dist/betterAuthSetup.js +1 -1
  23. package/dist/collectionRegistry.d.ts +3 -1
  24. package/dist/collectionRegistry.js +25 -0
  25. package/dist/index.d.ts +26 -1
  26. package/dist/index.js +48 -2
  27. package/dist/mcp/query.d.ts +0 -13
  28. package/dist/mcp/query.js +8 -8
  29. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  30. package/dist/migrations/fixtures/all-down/20260910120000-one.js +49 -0
  31. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  32. package/dist/migrations/fixtures/all-down/20260910120001-two.js +49 -0
  33. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  34. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +45 -0
  35. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  36. package/dist/migrations/fixtures/bad-name/not-a-migration.js +45 -0
  37. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  38. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  39. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  40. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +45 -0
  41. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  42. package/dist/migrations/fixtures/valid/20260910120001-beta.js +49 -0
  43. package/dist/migrations/generate.d.ts +17 -0
  44. package/dist/migrations/generate.js +277 -0
  45. package/dist/migrations/load.d.ts +20 -0
  46. package/dist/migrations/load.js +236 -0
  47. package/dist/migrations/lock.d.ts +13 -0
  48. package/dist/migrations/lock.js +145 -0
  49. package/dist/migrations/runner.d.ts +42 -0
  50. package/dist/migrations/runner.js +503 -0
  51. package/dist/migrations/schemaCatalog.d.ts +44 -0
  52. package/dist/migrations/schemaCatalog.js +326 -0
  53. package/dist/migrations/types.d.ts +87 -0
  54. package/dist/migrations/types.js +7 -0
  55. package/dist/models/notification.d.ts +2 -0
  56. package/dist/models/notification.js +62 -0
  57. package/dist/models/notificationPreference.d.ts +2 -0
  58. package/dist/models/notificationPreference.js +49 -0
  59. package/dist/notifications/notificationService.d.ts +40 -0
  60. package/dist/notifications/notificationService.js +323 -0
  61. package/dist/notifications/notificationsApp.d.ts +18 -0
  62. package/dist/notifications/notificationsApp.js +250 -0
  63. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  64. package/dist/notifications/notificationsBeforeSend.js +77 -0
  65. package/dist/openApi.d.ts +1 -7
  66. package/dist/openApi.js +7 -6
  67. package/dist/openApiBuilder.d.ts +14 -3
  68. package/dist/openApiValidator.d.ts +13 -1
  69. package/dist/openApiValidator.js +200 -36
  70. package/dist/orgs/orgContext.d.ts +23 -0
  71. package/dist/orgs/orgContext.js +198 -0
  72. package/dist/orgs/orgPermissions.d.ts +4 -0
  73. package/dist/orgs/orgPermissions.js +77 -0
  74. package/dist/orgs/orgPlugin.d.ts +13 -0
  75. package/dist/orgs/orgPlugin.js +84 -0
  76. package/dist/orgs/organizationModel.d.ts +13 -0
  77. package/dist/orgs/organizationModel.js +301 -0
  78. package/dist/orgs/organizationSettings.d.ts +19 -0
  79. package/dist/orgs/organizationSettings.js +120 -0
  80. package/dist/orgs/orgsApp.d.ts +28 -0
  81. package/dist/orgs/orgsApp.js +678 -0
  82. package/dist/permissions.d.ts +7 -13
  83. package/dist/permissions.js +8 -31
  84. package/dist/rateLimit/middleware.d.ts +0 -8
  85. package/dist/rateLimit/middleware.js +2 -3
  86. package/dist/rateLimit/mongoStore.d.ts +1 -0
  87. package/dist/rateLimit/mongoStore.js +1 -0
  88. package/dist/rateLimit/policies.d.ts +0 -4
  89. package/dist/rateLimit/policies.js +5 -7
  90. package/dist/rateLimit/redisStore.d.ts +1 -0
  91. package/dist/rateLimit/redisStore.js +1 -0
  92. package/dist/rbac/access.js +30 -13
  93. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  94. package/dist/rbac/membershipOrgAdminSource.js +122 -0
  95. package/dist/rbac/modelRouterAccess.d.ts +3 -0
  96. package/dist/rbac/modelRouterAccess.js +3 -0
  97. package/dist/rbac/resolve.js +60 -31
  98. package/dist/rbac/roleModel.d.ts +2 -5
  99. package/dist/rbac/roleModel.js +18 -4
  100. package/dist/rbac/statements.d.ts +10 -1
  101. package/dist/rbac/statements.js +19 -2
  102. package/dist/rbac/types.d.ts +5 -0
  103. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  104. package/dist/realtime/changeStreamWatcher.js +110 -64
  105. package/dist/realtime/deprecation.d.ts +1 -0
  106. package/dist/realtime/deprecation.js +1 -0
  107. package/dist/realtime/realtimeApp.d.ts +1 -0
  108. package/dist/realtime/realtimeApp.js +1 -0
  109. package/dist/schemaMetadata.js +16 -5
  110. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  111. package/dist/sync/adminBroadcastScope.js +194 -0
  112. package/dist/sync/adminWindowAccess.d.ts +13 -0
  113. package/dist/sync/adminWindowAccess.js +96 -0
  114. package/dist/sync/adminWindowMutation.d.ts +88 -0
  115. package/dist/sync/adminWindowMutation.js +247 -0
  116. package/dist/sync/executors.d.ts +9 -3
  117. package/dist/sync/executors.js +190 -159
  118. package/dist/sync/mutationHandler.d.ts +5 -2
  119. package/dist/sync/mutationHandler.js +191 -71
  120. package/dist/sync/registry.js +4 -0
  121. package/dist/sync/routes.d.ts +13 -0
  122. package/dist/sync/routes.js +113 -56
  123. package/dist/sync/socketHandlers.d.ts +8 -2
  124. package/dist/sync/socketHandlers.js +144 -50
  125. package/dist/sync/streams.d.ts +2 -0
  126. package/dist/sync/streams.js +7 -1
  127. package/dist/sync/syncApp.d.ts +2 -1
  128. package/dist/sync/syncApp.js +2 -1
  129. package/dist/sync/syncBatch.d.ts +5 -2
  130. package/dist/sync/syncBatch.js +4 -4
  131. package/dist/sync/types.d.ts +18 -0
  132. package/dist/terrenoApp.d.ts +29 -0
  133. package/dist/terrenoApp.js +91 -54
  134. package/dist/tests/createTestData.d.ts +1 -3
  135. package/dist/tests/createTestData.js +3 -5
  136. package/dist/tests/models.d.ts +1 -0
  137. package/dist/tests/models.js +9 -2
  138. package/dist/tests/testHelper.d.ts +0 -5
  139. package/dist/tests/testHelper.js +2 -9
  140. package/dist/types/authToken.d.ts +3 -3
  141. package/dist/types/mcpServiceToken.d.ts +2 -2
  142. package/dist/types/membership.d.ts +23 -0
  143. package/dist/types/membership.js +2 -0
  144. package/dist/types/notification.d.ts +28 -0
  145. package/dist/types/notification.js +2 -0
  146. package/dist/types/notificationPreference.d.ts +20 -0
  147. package/dist/types/notificationPreference.js +2 -0
  148. package/dist/types/organization.d.ts +36 -0
  149. package/dist/types/organization.js +2 -0
  150. package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
  151. package/dist/webhooks/idempotency/webhookReceipt.js +7 -7
  152. package/dist/webhooks/rawBody.d.ts +1 -0
  153. package/dist/webhooks/rawBody.js +1 -0
  154. package/package.json +31 -25
  155. package/src/__snapshots__/openApi.test.ts.snap +192 -54
  156. package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
  157. package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
  158. package/src/adminTypes.ts +8 -0
  159. package/src/api.test.ts +39 -2
  160. package/src/api.ts +68 -0
  161. package/src/audit/auditApp.test.ts +243 -0
  162. package/src/audit/auditApp.ts +139 -0
  163. package/src/audit/auditEventModel.ts +156 -0
  164. package/src/audit/auditRouter.test.ts +456 -0
  165. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  166. package/src/audit/cloudTasksEnqueue.ts +104 -0
  167. package/src/audit/diff.ts +163 -0
  168. package/src/audit/processQueue.ts +69 -0
  169. package/src/audit/rbacSink.test.ts +86 -0
  170. package/src/audit/rbacSink.ts +42 -0
  171. package/src/audit/record.test.ts +402 -0
  172. package/src/audit/record.ts +328 -0
  173. package/src/auth.test.ts +1 -1
  174. package/src/betterAuth.ts +7 -0
  175. package/src/betterAuthSetup.test.ts +27 -0
  176. package/src/betterAuthSetup.ts +1 -0
  177. package/src/collectionRegistry.test.ts +8 -9
  178. package/src/collectionRegistry.ts +21 -1
  179. package/src/express.d.ts +2 -0
  180. package/src/expressServer.test.ts +50 -2
  181. package/src/index.ts +69 -0
  182. package/src/mcp/handlers.test.ts +275 -0
  183. package/src/mcp/query.ts +3 -3
  184. package/src/mcp/toolGenerator.test.ts +81 -0
  185. package/src/migrations/cli.test.ts +376 -0
  186. package/src/migrations/cli.ts +283 -0
  187. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  188. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  189. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  190. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  191. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  192. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  193. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  194. package/src/migrations/generate.test.ts +333 -0
  195. package/src/migrations/generate.ts +216 -0
  196. package/src/migrations/load.test.ts +103 -0
  197. package/src/migrations/load.ts +124 -0
  198. package/src/migrations/lock.test.ts +133 -0
  199. package/src/migrations/lock.ts +118 -0
  200. package/src/migrations/runner.test.ts +504 -0
  201. package/src/migrations/runner.ts +358 -0
  202. package/src/migrations/schemaCatalog.test.ts +159 -0
  203. package/src/migrations/schemaCatalog.ts +262 -0
  204. package/src/migrations/types.ts +94 -0
  205. package/src/models/notification.ts +68 -0
  206. package/src/models/notificationPreference.ts +62 -0
  207. package/src/notifications/notificationService.ts +254 -0
  208. package/src/notifications/notificationsApp.test.ts +505 -0
  209. package/src/notifications/notificationsApp.ts +200 -0
  210. package/src/notifications/notificationsBeforeSend.ts +51 -0
  211. package/src/openApi.test.ts +0 -1
  212. package/src/openApi.ts +2 -1
  213. package/src/openApiBuilder.ts +14 -3
  214. package/src/openApiValidator.test.ts +221 -2
  215. package/src/openApiValidator.ts +218 -33
  216. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  217. package/src/orgs/orgContext.test.ts +259 -0
  218. package/src/orgs/orgContext.ts +151 -0
  219. package/src/orgs/orgPermissions.test.ts +105 -0
  220. package/src/orgs/orgPermissions.ts +40 -0
  221. package/src/orgs/orgPlugin.test.ts +130 -0
  222. package/src/orgs/orgPlugin.ts +70 -0
  223. package/src/orgs/orgRbac.test.ts +267 -0
  224. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  225. package/src/orgs/organizationModel.test.ts +205 -0
  226. package/src/orgs/organizationModel.ts +257 -0
  227. package/src/orgs/organizationSettings.test.ts +113 -0
  228. package/src/orgs/organizationSettings.ts +126 -0
  229. package/src/orgs/orgsApp.test.ts +382 -0
  230. package/src/orgs/orgsApp.ts +563 -0
  231. package/src/permissions.test.ts +62 -36
  232. package/src/permissions.ts +8 -30
  233. package/src/rateLimit/middleware.ts +1 -1
  234. package/src/rateLimit/mongoStore.ts +1 -0
  235. package/src/rateLimit/policies.ts +2 -2
  236. package/src/rateLimit/redisStore.ts +1 -0
  237. package/src/rbac/access.ts +11 -3
  238. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  239. package/src/rbac/modelRouterAccess.ts +3 -0
  240. package/src/rbac/permissionUtils.test.ts +26 -5
  241. package/src/rbac/resolve.test.ts +34 -2
  242. package/src/rbac/resolve.ts +26 -7
  243. package/src/rbac/roleModel.test.ts +34 -1
  244. package/src/rbac/roleModel.ts +17 -1
  245. package/src/rbac/statements.test.ts +19 -0
  246. package/src/rbac/statements.ts +19 -1
  247. package/src/rbac/types.ts +5 -0
  248. package/src/realtime/changeStreamWatcher.ts +73 -33
  249. package/src/realtime/deprecation.ts +1 -0
  250. package/src/realtime/realtime.test.ts +357 -185
  251. package/src/realtime/realtimeApp.ts +1 -0
  252. package/src/schemaMetadata.test.ts +14 -0
  253. package/src/schemaMetadata.ts +5 -5
  254. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  255. package/src/sync/adminBroadcastScope.test.ts +155 -0
  256. package/src/sync/adminBroadcastScope.ts +123 -0
  257. package/src/sync/adminWindowAccess.test.ts +57 -0
  258. package/src/sync/adminWindowAccess.ts +32 -0
  259. package/src/sync/adminWindowMutation.test.ts +450 -0
  260. package/src/sync/adminWindowMutation.ts +283 -0
  261. package/src/sync/executors.ts +33 -6
  262. package/src/sync/mutationHandler.test.ts +277 -1
  263. package/src/sync/mutationHandler.ts +171 -29
  264. package/src/sync/registry.ts +4 -0
  265. package/src/sync/routes.ts +52 -8
  266. package/src/sync/socketHandlers.ts +154 -58
  267. package/src/sync/streams.ts +6 -0
  268. package/src/sync/sync.test.ts +3 -2
  269. package/src/sync/syncApp.ts +2 -1
  270. package/src/sync/syncBatch.ts +7 -2
  271. package/src/sync/syncRoutes.test.ts +297 -3
  272. package/src/sync/syncSocket.test.ts +229 -0
  273. package/src/sync/types.ts +20 -0
  274. package/src/terrenoApp.migrations.test.ts +114 -0
  275. package/src/terrenoApp.test.ts +41 -0
  276. package/src/terrenoApp.ts +94 -31
  277. package/src/tests/createTestData.ts +2 -2
  278. package/src/tests/models.ts +10 -2
  279. package/src/tests/testHelper.ts +1 -7
  280. package/src/types/authToken.ts +2 -4
  281. package/src/types/mcpServiceToken.ts +1 -7
  282. package/src/types/membership.ts +48 -0
  283. package/src/types/notification.ts +34 -0
  284. package/src/types/notificationPreference.ts +28 -0
  285. package/src/types/organization.ts +49 -0
  286. package/src/webhooks/idempotency/webhookReceipt.ts +4 -7
  287. package/src/webhooks/rawBody.test.ts +33 -0
  288. package/src/webhooks/rawBody.ts +1 -0
  289. package/tsconfig.json +1 -1
  290. package/tsconfig.typedoc.json +2 -1
  291. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  292. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  293. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
@@ -83,29 +83,40 @@ schema.statics = {
83
83
  - Apply the standard plugins (`createdUpdatedPlugin`, `isDeletedPlugin`, `findOneOrNone`, `findExactlyOne`) on every new model. Most existing models go through `addDefaultPlugins`.
84
84
  - `checkModelsStrict()` runs at non-prod startup (`server.ts`) and validates schema consistency — keep it passing.
85
85
 
86
+ ## Migration files
87
+
88
+ Schema and data changes that must run once per environment belong in
89
+ `migrations/<YYYYMMDDHHmmss>-<slug>.ts` with required `up` and optional `down`.
90
+ Generate a draft with `terreno-migrate generate --dir ./migrations --models ./src/models.ts`,
91
+ then `terreno-migrate up --dir ./migrations --dry` before wet apply.
92
+ See [Run MongoDB migrations](../../../../docs/how-to/run-mongodb-migrations.md).
93
+
94
+ Admin **Scripts** (`ScriptRunner` + `BackgroundTask`) stay for one-off operator
95
+ tools. Do not use Scripts as the primary path for versioned schema backfills.
96
+
86
97
  ## Schema Change Risk Matrix
87
98
 
88
99
  | Change Type | Risk Level | Required Mitigation |
89
100
  |-------------|-----------|---------------------|
90
101
  | Add optional field | Low | Safe to ship directly (still requires `description`) |
91
- | Add required field | High | Must provide a default value, OR write a backfill migration script first |
102
+ | Add required field | High | Must provide a default value, OR write a versioned migration (`terreno-migrate generate` / `up`) with a backfill before wet apply |
92
103
  | Remove field | Medium | Soft-remove first (mark optional, stop writing); hard-remove in next PR after deploys settle |
93
- | Rename field | High | Three-step: add new → backfill → remove old (separate PRs) |
94
- | Change field type | Critical | Treat as rename: new field + migration + remove old |
95
- | Add index | Medium | Safe in code, but build can slow writes on large collections — coordinate with ops |
104
+ | Rename field | High | Three-step: add new → backfill migration → remove old (separate PRs) |
105
+ | Change field type | Critical | Treat as rename: new field + versioned migration + remove old |
106
+ | Add index | Medium | Prefer `terreno-migrate generate` for the index; build can slow writes on large collections — coordinate with ops |
96
107
  | Remove index | Low | Safe to ship directly |
97
- | Add unique index | High | Dedup migration must run first; otherwise the index build fails on existing duplicates |
108
+ | Add unique index | High | Dedup in a versioned migration first; otherwise the index build fails on existing duplicates |
98
109
 
99
- ## Migration Scripts
110
+ ## One-off admin scripts
100
111
 
101
- Migration / backfill scripts live in `example-backend/src/scripts/` (e.g. `syncConsents.ts`, `seedConsents.ts`). They use the `ScriptRunner` type and `BackgroundTask` model from `@terreno/api` (`api/src/scriptRunner.ts`):
112
+ Ad-hoc operator tools (counts, reseeds, support fixes) still live as admin
113
+ Scripts using `ScriptRunner` and `BackgroundTask`:
102
114
 
103
115
  ```typescript
104
116
  import type {ScriptContext, ScriptResult, ScriptRunner} from "@terreno/api";
105
117
 
106
118
  export const run: ScriptRunner = async (wetRun, ctx) => {
107
119
  const results: string[] = [];
108
- // ... do work ...
109
120
  if (wetRun) {
110
121
  // commit changes
111
122
  }
@@ -113,7 +124,9 @@ export const run: ScriptRunner = async (wetRun, ctx) => {
113
124
  };
114
125
  ```
115
126
 
116
- Always run with `wetRun = false` first to verify the dry-run output. Use `ctx.checkCancellation()`, `ctx.addLog()`, and `ctx.updateProgress()` for long-running tasks.
127
+ Always run with `wetRun = false` first. Use `ctx.checkCancellation()`,
128
+ `ctx.addLog()`, and `ctx.updateProgress()` for long-running tasks. Do not put
129
+ repeatable schema backfills here — use `migrations/` and `terreno-migrate`.
117
130
 
118
131
  ## Cross-Package Ripple
119
132
 
@@ -131,7 +144,7 @@ A schema change in one place often ripples:
131
144
  - [ ] For a new model: all five types (`Document`, `Methods`, `Statics`, `Model`, `Schema`) created
132
145
  - [ ] Statics/methods assigned directly on schema (`schema.statics = {...}`, `schema.methods = {...}`) — not `.static()` / `.method()`
133
146
  - [ ] Other model type files checked — any model that populates this one updated if its shape changed
134
- - [ ] Migration script written (and dry-run verified with `wetRun = false`) for any backfill
147
+ - [ ] Versioned migration written (`migrations/` + `terreno-migrate`) and dry-run verified for any backfill; unique-index dedup runs before the index is added
135
148
  - [ ] `modelRouter` config updated (`queryFields`, `populatePaths`, `responseHandler`) if needed
136
149
  - [ ] `AdminApp` `listFields` updated if the model is in the admin panel
137
150
  - [ ] `bun run sdk` run from `example-frontend/` if the API response shape changed
package/README.md CHANGED
@@ -227,6 +227,12 @@ To enable Sentry, create a "src/sentryInstrumment.ts" file in your project.
227
227
 
228
228
  > **Note:** Bun automatically loads `.env` files before your code runs, so there's no need for `dotenv`. Just place a `.env` file in your project root and `process.env` will have your variables available immediately. See [Bun .env docs](https://bun.sh/docs/runtime/env).
229
229
 
230
+ Install both SDK packages in the consuming backend:
231
+
232
+ ```bash
233
+ bun add @sentry/bun @sentry/profiling-node
234
+ ```
235
+
230
236
  ```
231
237
  import * as Sentry from "@sentry/bun";
232
238
  import {nodeProfilingIntegration} from "@sentry/profiling-node";
@@ -7,6 +7,11 @@ import type { ScriptArgDef, ScriptRunner } from "./scriptRunner";
7
7
  /** Server-side cap on bulk action id lists (v2 bulk-patch). */
8
8
  export declare const MAX_BULK_PATCH_IDS = 1000;
9
9
  export type AdminFilterKind = "boolean" | "choice" | "dateRange" | "ref" | "text";
10
+ /**
11
+ * Wire-format sentinel for optional choice filters meaning "field is null or unset".
12
+ * Must match `DATA_TABLE_CHOICE_EMPTY_VALUE` in `@terreno/ui`.
13
+ */
14
+ export declare const ADMIN_LIST_CHOICE_EMPTY_VALUE = "__empty__";
10
15
  export interface AdminFilterBoolean {
11
16
  field: string;
12
17
  kind: "boolean";
@@ -17,6 +22,8 @@ export interface AdminFilterChoice {
17
22
  label: string;
18
23
  value: string;
19
24
  }[];
25
+ /** When true, the filter UI offers an Empty option and the parser accepts {@link ADMIN_LIST_CHOICE_EMPTY_VALUE}. */
26
+ allowEmpty?: boolean;
20
27
  field: string;
21
28
  kind: "choice";
22
29
  label?: string;
@@ -1,5 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_BULK_PATCH_IDS = void 0;
3
+ exports.ADMIN_LIST_CHOICE_EMPTY_VALUE = exports.MAX_BULK_PATCH_IDS = void 0;
4
4
  /** Server-side cap on bulk action id lists (v2 bulk-patch). */
5
5
  exports.MAX_BULK_PATCH_IDS = 1000;
6
+ /**
7
+ * Wire-format sentinel for optional choice filters meaning "field is null or unset".
8
+ * Must match `DATA_TABLE_CHOICE_EMPTY_VALUE` in `@terreno/ui`.
9
+ */
10
+ exports.ADMIN_LIST_CHOICE_EMPTY_VALUE = "__empty__";
package/dist/api.d.ts CHANGED
@@ -3,6 +3,7 @@ import mongoose, { type Document, type Model } from "mongoose";
3
3
  import { type CollectionActionConfig, type InstanceActionConfig } from "./actions";
4
4
  import { type ModelRouterBuildContext } from "./adminModelRouter";
5
5
  import type { AdminConfig } from "./adminTypes";
6
+ import { type ModelRouterAuditConfig } from "./audit/record";
6
7
  import { type User } from "./auth";
7
8
  import type { MCPConfig } from "./mcp/types";
8
9
  import { type ModelRouterValidationOptions } from "./openApiValidator";
@@ -203,6 +204,13 @@ export interface ModelRouterOptions<T> {
203
204
  * @param value - The document that was deleted, after the soft update of deleted: true (type: T).
204
205
  */
205
206
  postDelete?: (request: express.Request, value: T) => void | Promise<void>;
207
+ /**
208
+ * When true or `{redact}`, persist an `AuditEvent` after successful HTTP
209
+ * create/update/delete. Requires `AuditApp`. Extra `redact` names merge with
210
+ * the default secret segments (`password`, `hash`, `salt`, `token`, `secret`,
211
+ * `refreshToken`).
212
+ */
213
+ audit?: ModelRouterAuditConfig;
206
214
  /** Hook that runs after the object is fetched but before it is serialized.
207
215
  * Returns a promise so that asynchronous actions can be included in the function.
208
216
  * Throw an APIError to return a 400 with an error message.
@@ -290,6 +298,8 @@ export interface ModelRouterOptions<T> {
290
298
  /**
291
299
  * Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
292
300
  * into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
301
+ * Set `sync.adminBroadcast: true` to also emit `sync:delta` to `{collection}|admin`
302
+ * (default false; stored on the collection catalog at registration).
293
303
  *
294
304
  * Requires the schema to use `isDeletedPlugin` (soft delete tombstones) and
295
305
  * `syncPlugin` (per-stream `_syncSeq` stamping) — validated at registration.
package/dist/api.js CHANGED
@@ -133,6 +133,7 @@ var luxon_1 = require("luxon");
133
133
  var mongoose_1 = __importDefault(require("mongoose"));
134
134
  var actions_1 = require("./actions");
135
135
  var adminModelRouter_1 = require("./adminModelRouter");
136
+ var record_1 = require("./audit/record");
136
137
  var auth_1 = require("./auth");
137
138
  var collectionRegistry_1 = require("./collectionRegistry");
138
139
  var errors_1 = require("./errors");
@@ -373,6 +374,9 @@ var getBodyValidationMiddleware = function (model, options, operation) {
373
374
  validationOptions.excludeFields = excludeFields;
374
375
  }
375
376
  }
377
+ if (operation === "update") {
378
+ validationOptions.partial = true;
379
+ }
376
380
  return (0, openApiValidator_1.validateModelRequestBody)(model, validationOptions);
377
381
  };
378
382
  // Get query validation middleware if validation is enabled
@@ -487,6 +491,15 @@ var _buildModelRouter = function (model, options, routePath) {
487
491
  })];
488
492
  case 1:
489
493
  doc = (_a.sent()).doc;
494
+ void (0, record_1.maybeRecordModelRouterAudit)({
495
+ after: doc,
496
+ audit: options.audit,
497
+ modelName: model.modelName,
498
+ operation: "create",
499
+ recordId: String(doc._id),
500
+ req: req,
501
+ verb: "created",
502
+ });
490
503
  _a.label = 2;
491
504
  case 2:
492
505
  _a.trys.push([2, 4, , 5]);
@@ -510,23 +523,23 @@ var _buildModelRouter = function (model, options, routePath) {
510
523
  (0, openApi_1.listOpenApiMiddleware)(model, options, routePath),
511
524
  queryValidation,
512
525
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
513
- var query, _a, _b, queryParam, _c, _d, queryParam, queryFilter, error_2, limit, builtQuery, total, populatedQuery, data, error_3, serialized, error_4, more, msg;
514
- var e_6, _e, e_7, _f;
515
- var _g, _h, _j, _k, _l, _m;
516
- return __generator(this, function (_o) {
517
- switch (_o.label) {
526
+ var query, _a, _b, queryParam, _c, _d, queryParam, queryFilter, error_2, _e, _f, _g, key, value, limit, builtQuery, total, populatedQuery, data, error_3, serialized, error_4, more, msg;
527
+ var e_6, _h, e_7, _j, e_8, _k;
528
+ var _l, _m, _o, _p, _q, _r;
529
+ return __generator(this, function (_s) {
530
+ switch (_s.label) {
518
531
  case 0:
519
532
  query = {};
520
533
  try {
521
- for (_a = __values(Object.keys((_g = options.defaultQueryParams) !== null && _g !== void 0 ? _g : [])), _b = _a.next(); !_b.done; _b = _a.next()) {
534
+ for (_a = __values(Object.keys((_l = options.defaultQueryParams) !== null && _l !== void 0 ? _l : [])), _b = _a.next(); !_b.done; _b = _a.next()) {
522
535
  queryParam = _b.value;
523
- query[queryParam] = (_h = options.defaultQueryParams) === null || _h === void 0 ? void 0 : _h[queryParam];
536
+ query[queryParam] = (_m = options.defaultQueryParams) === null || _m === void 0 ? void 0 : _m[queryParam];
524
537
  }
525
538
  }
526
539
  catch (e_6_1) { e_6 = { error: e_6_1 }; }
527
540
  finally {
528
541
  try {
529
- if (_b && !_b.done && (_e = _a.return)) _e.call(_a);
542
+ if (_b && !_b.done && (_h = _a.return)) _h.call(_a);
530
543
  }
531
544
  finally { if (e_6) throw e_6.error; }
532
545
  }
@@ -552,29 +565,29 @@ var _buildModelRouter = function (model, options, routePath) {
552
565
  catch (e_7_1) { e_7 = { error: e_7_1 }; }
553
566
  finally {
554
567
  try {
555
- if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
568
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
556
569
  }
557
570
  finally { if (e_7) throw e_7.error; }
558
571
  }
559
572
  query = mergeDateRangeQueryParams(model, query);
560
573
  // Special operators. NOTE: these request Mongo Atlas.
561
574
  if (req.query.$search) {
562
- (_j = mongoose_1.default.connection.db) === null || _j === void 0 ? void 0 : _j.collection(model.collection.collectionName);
575
+ (_o = mongoose_1.default.connection.db) === null || _o === void 0 ? void 0 : _o.collection(model.collection.collectionName);
563
576
  }
564
577
  if (req.query.$autocomplete) {
565
- (_k = mongoose_1.default.connection.db) === null || _k === void 0 ? void 0 : _k.collection(model.collection.collectionName);
578
+ (_p = mongoose_1.default.connection.db) === null || _p === void 0 ? void 0 : _p.collection(model.collection.collectionName);
566
579
  }
567
580
  if (!options.queryFilter) return [3 /*break*/, 5];
568
581
  queryFilter = void 0;
569
- _o.label = 1;
582
+ _s.label = 1;
570
583
  case 1:
571
- _o.trys.push([1, 3, , 4]);
584
+ _s.trys.push([1, 3, , 4]);
572
585
  return [4 /*yield*/, options.queryFilter(req.user, query)];
573
586
  case 2:
574
- queryFilter = _o.sent();
587
+ queryFilter = _s.sent();
575
588
  return [3 /*break*/, 4];
576
589
  case 3:
577
- error_2 = _o.sent();
590
+ error_2 = _s.sent();
578
591
  throw (0, errors_1.passthroughOrWrap)(error_2, {
579
592
  code: "query-filter-error",
580
593
  status: 400,
@@ -587,11 +600,26 @@ var _buildModelRouter = function (model, options, routePath) {
587
600
  return [2 /*return*/, res.json({ data: [] })];
588
601
  }
589
602
  query = __assign(__assign({}, query), queryFilter);
590
- _o.label = 5;
603
+ try {
604
+ for (_e = __values(Object.entries(queryFilter)), _f = _e.next(); !_f.done; _f = _e.next()) {
605
+ _g = __read(_f.value, 2), key = _g[0], value = _g[1];
606
+ if (value === undefined) {
607
+ delete query[key];
608
+ }
609
+ }
610
+ }
611
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
612
+ finally {
613
+ try {
614
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
615
+ }
616
+ finally { if (e_8) throw e_8.error; }
617
+ }
618
+ _s.label = 5;
591
619
  case 5:
592
- limit = (_l = options.defaultLimit) !== null && _l !== void 0 ? _l : 100;
620
+ limit = (_q = options.defaultLimit) !== null && _q !== void 0 ? _q : 100;
593
621
  if (Number(req.query.limit)) {
594
- limit = Math.min(Number(req.query.limit), (_m = options.maxLimit) !== null && _m !== void 0 ? _m : 500);
622
+ limit = Math.min(Number(req.query.limit), (_r = options.maxLimit) !== null && _r !== void 0 ? _r : 500);
595
623
  }
596
624
  if (query.period) {
597
625
  // need to remove 'period' since it isn't part of any schemas but parsed and applied in
@@ -601,7 +629,7 @@ var _buildModelRouter = function (model, options, routePath) {
601
629
  builtQuery = model.find(query).limit(limit + 1);
602
630
  return [4 /*yield*/, model.countDocuments(query)];
603
631
  case 6:
604
- total = _o.sent();
632
+ total = _s.sent();
605
633
  if (req.query.page) {
606
634
  if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
607
635
  throw new errors_1.BadRequestError({
@@ -621,27 +649,27 @@ var _buildModelRouter = function (model, options, routePath) {
621
649
  builtQuery = builtQuery.sort(options.sort);
622
650
  }
623
651
  populatedQuery = (0, exports.addPopulateToQuery)(builtQuery, options.populatePaths);
624
- _o.label = 7;
652
+ _s.label = 7;
625
653
  case 7:
626
- _o.trys.push([7, 9, , 10]);
654
+ _s.trys.push([7, 9, , 10]);
627
655
  return [4 /*yield*/, populatedQuery.exec()];
628
656
  case 8:
629
- data = (_o.sent());
657
+ data = (_s.sent());
630
658
  return [3 /*break*/, 10];
631
659
  case 9:
632
- error_3 = _o.sent();
660
+ error_3 = _s.sent();
633
661
  throw (0, errors_1.passthroughOrWrap)(error_3, {
634
662
  code: "list-error",
635
663
  title: "List error",
636
664
  });
637
665
  case 10:
638
- _o.trys.push([10, 12, , 13]);
666
+ _s.trys.push([10, 12, , 13]);
639
667
  return [4 /*yield*/, responseHandler(data, "list", req, options)];
640
668
  case 11:
641
- serialized = _o.sent();
669
+ serialized = _s.sent();
642
670
  return [3 /*break*/, 13];
643
671
  case 12:
644
- error_4 = _o.sent();
672
+ error_4 = _s.sent();
645
673
  throw (0, errors_1.passthroughOrWrap)(error_4, {
646
674
  code: "response-handler-error",
647
675
  title: "responseHandler error",
@@ -727,7 +755,7 @@ var _buildModelRouter = function (model, options, routePath) {
727
755
  (0, permissions_1.permissionMiddleware)(model, options),
728
756
  updateValidation,
729
757
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
730
- var existingDoc, bodyUpdatedAt, preciseUnmodifiedSince, httpUnmodifiedSince, timestampValue, httpTimestampValue, concurrencyCheck, usingPreciseHeader, usingHttpHeader, clientTimestamp, doc, error_6, serialized, serialized, error_7;
758
+ var existingDoc, bodyUpdatedAt, preciseUnmodifiedSince, httpUnmodifiedSince, timestampValue, httpTimestampValue, concurrencyCheck, usingPreciseHeader, usingHttpHeader, clientTimestamp, doc, previous, error_6, serialized, serialized, error_7;
731
759
  return __generator(this, function (_a) {
732
760
  switch (_a.label) {
733
761
  case 0:
@@ -762,6 +790,7 @@ var _buildModelRouter = function (model, options, routePath) {
762
790
  type: "timestamp",
763
791
  };
764
792
  }
793
+ previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
765
794
  _a.label = 1;
766
795
  case 1:
767
796
  _a.trys.push([1, 3, , 6]);
@@ -791,18 +820,30 @@ var _buildModelRouter = function (model, options, routePath) {
791
820
  })];
792
821
  case 5: throw error_6;
793
822
  case 6:
794
- _a.trys.push([6, 8, , 9]);
795
- return [4 /*yield*/, responseHandler(doc, "update", req, options)];
823
+ void (0, record_1.maybeRecordModelRouterAudit)({
824
+ after: doc,
825
+ audit: options.audit,
826
+ before: previous,
827
+ modelName: model.modelName,
828
+ operation: "update",
829
+ recordId: String(doc._id),
830
+ req: req,
831
+ verb: "updated",
832
+ });
833
+ _a.label = 7;
796
834
  case 7:
835
+ _a.trys.push([7, 9, , 10]);
836
+ return [4 /*yield*/, responseHandler(doc, "update", req, options)];
837
+ case 8:
797
838
  serialized = _a.sent();
798
839
  return [2 /*return*/, res.json({ data: serialized })];
799
- case 8:
840
+ case 9:
800
841
  error_7 = _a.sent();
801
842
  throw (0, errors_1.passthroughOrWrap)(error_7, {
802
843
  code: "response-handler-error",
803
844
  title: "responseHandler error",
804
845
  });
805
- case 9: return [2 /*return*/];
846
+ case 10: return [2 /*return*/];
806
847
  }
807
848
  });
808
849
  }); }));
@@ -811,11 +852,12 @@ var _buildModelRouter = function (model, options, routePath) {
811
852
  (0, openApi_1.deleteOpenApiMiddleware)(model, options),
812
853
  (0, permissions_1.permissionMiddleware)(model, options),
813
854
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
814
- var existingDoc;
855
+ var existingDoc, previous;
815
856
  return __generator(this, function (_a) {
816
857
  switch (_a.label) {
817
858
  case 0:
818
859
  existingDoc = req.obj;
860
+ previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
819
861
  return [4 /*yield*/, (0, executors_1.executeDelete)({
820
862
  existingDoc: existingDoc,
821
863
  id: req.params.id,
@@ -826,12 +868,21 @@ var _buildModelRouter = function (model, options, routePath) {
826
868
  })];
827
869
  case 1:
828
870
  _a.sent();
871
+ void (0, record_1.maybeRecordModelRouterAudit)({
872
+ audit: options.audit,
873
+ before: previous,
874
+ modelName: model.modelName,
875
+ operation: "delete",
876
+ recordId: String(existingDoc._id),
877
+ req: req,
878
+ verb: "deleted",
879
+ });
829
880
  return [2 /*return*/, res.status(204).json({})];
830
881
  }
831
882
  });
832
883
  }); }));
833
884
  var arrayOperation = function (req, res, operation) { return __awaiter(void 0, void 0, void 0, function () {
834
- var doc, prevDoc, field, itemId, array, index, body, error_8, error_9, error_10;
885
+ var doc, prevDoc, field, itemId, array, index, body, error_8, error_9, error_10, arrayAuditOperation;
835
886
  var _a;
836
887
  var _b, _c;
837
888
  return __generator(this, function (_d) {
@@ -1012,9 +1063,21 @@ var _buildModelRouter = function (model, options, routePath) {
1012
1063
  status: 400,
1013
1064
  title: "PATCH Post Update error",
1014
1065
  });
1015
- case 17: return [2 /*return*/, res.json({
1016
- data: (0, transformers_1.serialize)(req, options, doc),
1017
- })];
1066
+ case 17:
1067
+ arrayAuditOperation = operation === "POST" ? "arrayPush" : operation === "PATCH" ? "arrayUpdate" : "arrayRemove";
1068
+ void (0, record_1.maybeRecordModelRouterAudit)({
1069
+ after: doc,
1070
+ audit: options.audit,
1071
+ before: prevDoc,
1072
+ modelName: model.modelName,
1073
+ operation: arrayAuditOperation,
1074
+ recordId: String(doc._id),
1075
+ req: req,
1076
+ verb: "updated",
1077
+ });
1078
+ return [2 /*return*/, res.json({
1079
+ data: (0, transformers_1.serialize)(req, options, doc),
1080
+ })];
1018
1081
  }
1019
1082
  });
1020
1083
  }); };
@@ -0,0 +1,30 @@
1
+ import type express from "express";
2
+ import type { AdminContribution } from "../adminTypes";
3
+ import type { TerrenoPlugin } from "../terrenoPlugin";
4
+ import { type AuditEnqueue } from "./record";
5
+ export interface AuditAppOptions {
6
+ /**
7
+ * When set, persist is delegated (Cloud Tasks). Mongo is not written on the
8
+ * request process. Diffs still run inline so before/after is captured now.
9
+ */
10
+ enqueue?: AuditEnqueue;
11
+ /** Shared secret for POST on `processQueuePath`. Required when that path is set. */
12
+ processQueueSecret?: string;
13
+ /**
14
+ * Worker URL path Cloud Tasks should POST to. Defaults to `/internal/audit-events`
15
+ * when enqueue comes from env (`GCP_TASKS_AUDIT_QUEUE` + `AUDIT_TASKS_URL`).
16
+ */
17
+ processQueuePath?: string;
18
+ /** Mongo TTL in days. Omit or 0 = forever (no TTL index). */
19
+ retentionDays?: number;
20
+ }
21
+ export declare class AuditApp implements TerrenoPlugin {
22
+ private readonly options;
23
+ private readonly enqueue;
24
+ constructor(options?: AuditAppOptions);
25
+ getRetentionDays: () => number | undefined;
26
+ adminContribution(): AdminContribution;
27
+ register(app: express.Application): void;
28
+ private mountProcessQueue;
29
+ private resolveProcessQueuePath;
30
+ }
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.AuditApp = void 0;
43
+ var mongoose_1 = __importDefault(require("mongoose"));
44
+ var api_1 = require("../api");
45
+ var logger_1 = require("../logger");
46
+ var permissions_1 = require("../permissions");
47
+ var auditEventModel_1 = require("./auditEventModel");
48
+ var cloudTasksEnqueue_1 = require("./cloudTasksEnqueue");
49
+ var processQueue_1 = require("./processQueue");
50
+ var record_1 = require("./record");
51
+ var DEFAULT_PROCESS_QUEUE_PATH = "/internal/audit-events";
52
+ var AuditApp = /** @class */ (function () {
53
+ function AuditApp(options) {
54
+ if (options === void 0) { options = {}; }
55
+ var _this = this;
56
+ var _a;
57
+ this.getRetentionDays = function () {
58
+ return _this.options.retentionDays;
59
+ };
60
+ this.mountProcessQueue = function (app) {
61
+ var _a;
62
+ var path = _this.resolveProcessQueuePath();
63
+ if (!path) {
64
+ return;
65
+ }
66
+ var secret = (_a = _this.options.processQueueSecret) !== null && _a !== void 0 ? _a : process.env.AUDIT_TASKS_SECRET;
67
+ if (!secret) {
68
+ logger_1.logger.error("AuditApp processQueuePath requires processQueueSecret or AUDIT_TASKS_SECRET");
69
+ return;
70
+ }
71
+ app.post(path, (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
72
+ return __generator(this, function (_a) {
73
+ return [2 /*return*/, (0, processQueue_1.handleEnqueuedAuditWrite)({ req: req, res: res, secret: secret })];
74
+ });
75
+ }); }));
76
+ };
77
+ this.resolveProcessQueuePath = function () {
78
+ if (_this.options.processQueuePath) {
79
+ return _this.options.processQueuePath;
80
+ }
81
+ if (_this.options.enqueue === undefined && _this.enqueue) {
82
+ return DEFAULT_PROCESS_QUEUE_PATH;
83
+ }
84
+ return undefined;
85
+ };
86
+ this.options = options;
87
+ this.enqueue = (_a = options.enqueue) !== null && _a !== void 0 ? _a : (0, cloudTasksEnqueue_1.auditEnqueueFromEnv)();
88
+ }
89
+ AuditApp.prototype.adminContribution = function () {
90
+ var model = (0, auditEventModel_1.createAuditEventModel)(mongoose_1.default.connection, {
91
+ retentionDays: this.options.retentionDays,
92
+ });
93
+ return {
94
+ models: [
95
+ {
96
+ admin: {
97
+ adminPermissions: {
98
+ create: [],
99
+ delete: [],
100
+ update: [],
101
+ },
102
+ defaultSort: "-created",
103
+ displayName: "Audit Log",
104
+ listFields: ["created", "verb", "modelName", "recordLabel", "actorId"],
105
+ readonlyFields: [
106
+ "actorId",
107
+ "after",
108
+ "before",
109
+ "created",
110
+ "modelName",
111
+ "operation",
112
+ "organizationId",
113
+ "recordId",
114
+ "recordLabel",
115
+ "source",
116
+ "updated",
117
+ "verb",
118
+ ],
119
+ recordTitleField: "recordLabel",
120
+ },
121
+ model: model,
122
+ permissions: {
123
+ create: [],
124
+ delete: [],
125
+ list: [permissions_1.Permissions.IsAdmin],
126
+ read: [permissions_1.Permissions.IsAdmin],
127
+ update: [],
128
+ },
129
+ routePath: "/audit-events",
130
+ },
131
+ ],
132
+ };
133
+ };
134
+ AuditApp.prototype.register = function (app) {
135
+ var model = (0, auditEventModel_1.createAuditEventModel)(mongoose_1.default.connection, {
136
+ retentionDays: this.options.retentionDays,
137
+ });
138
+ (0, record_1.installAuditRecorder)(model, { enqueue: this.enqueue });
139
+ var router = (0, api_1.modelRouter)(model, {
140
+ permissions: {
141
+ create: [],
142
+ delete: [],
143
+ list: [permissions_1.Permissions.IsAdmin],
144
+ read: [permissions_1.Permissions.IsAdmin],
145
+ update: [],
146
+ },
147
+ queryFields: ["actorId", "modelName", "organizationId", "recordId", "source", "verb"],
148
+ sort: "-created",
149
+ });
150
+ app.use("/audit-events", router);
151
+ this.mountProcessQueue(app);
152
+ };
153
+ return AuditApp;
154
+ }());
155
+ exports.AuditApp = AuditApp;
@@ -0,0 +1,29 @@
1
+ import mongoose from "mongoose";
2
+ import { type FindExactlyOnePlugin, type FindOneOrNonePlugin } from "../plugins";
3
+ export type AuditEventVerb = "created" | "deleted" | "updated";
4
+ export type AuditEventSource = "admin" | "modelRouter" | "rbac";
5
+ export type AuditEventOperation = "arrayPush" | "arrayRemove" | "arrayUpdate" | "create" | "delete" | "update";
6
+ type AuditEventMethods = Record<string, never>;
7
+ interface AuditEventStatics extends FindExactlyOnePlugin<AuditEventDocument>, FindOneOrNonePlugin<AuditEventDocument> {
8
+ }
9
+ export interface AuditEventModel extends mongoose.Model<AuditEventDocument, object, AuditEventMethods>, AuditEventStatics {
10
+ }
11
+ export interface AuditEventDocument extends mongoose.Document {
12
+ _id: mongoose.Types.ObjectId;
13
+ actorId?: mongoose.Types.ObjectId;
14
+ after?: Record<string, unknown>;
15
+ before?: Record<string, unknown>;
16
+ created: Date;
17
+ modelName: string;
18
+ operation: AuditEventOperation;
19
+ organizationId?: string;
20
+ recordId?: string;
21
+ recordLabel?: string;
22
+ source: AuditEventSource;
23
+ updated: Date;
24
+ verb: AuditEventVerb;
25
+ }
26
+ export declare const createAuditEventModel: (connection: mongoose.Connection, options?: {
27
+ retentionDays?: number;
28
+ }) => AuditEventModel;
29
+ export {};