@terreno/api 57.21.0 → 58.0.0-beta.2

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 (121) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -1
  3. package/dist/api.d.ts +0 -13
  4. package/dist/api.js +0 -9
  5. package/dist/auth.d.ts +3 -2
  6. package/dist/auth.js +95 -5
  7. package/dist/authRecovery.d.ts +2 -1
  8. package/dist/authRecovery.js +35 -17
  9. package/dist/collectionRegistry.d.ts +3 -4
  10. package/dist/collectionRegistry.js +0 -1
  11. package/dist/consentApp.d.ts +1 -1
  12. package/dist/consentApp.js +58 -2
  13. package/dist/index.d.ts +4 -5
  14. package/dist/index.js +8 -20
  15. package/dist/mcp/adminTracking.js +1 -1
  16. package/dist/mcp/serviceTokens.d.ts +21 -1
  17. package/dist/mcp/serviceTokens.js +159 -183
  18. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  19. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  20. package/dist/models/mcpRequestLog.js +1 -1
  21. package/dist/models/mcpServiceToken.js +36 -4
  22. package/dist/openApiBuilder.d.ts +4 -0
  23. package/dist/openApiBuilder.js +2 -0
  24. package/dist/rbac/realtimeAccess.d.ts +5 -4
  25. package/dist/rbac/realtimeAccess.js +17 -64
  26. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  27. package/dist/realtime/changeStreamWatcher.js +32 -391
  28. package/dist/realtime/realtimeApp.d.ts +14 -27
  29. package/dist/realtime/realtimeApp.js +14 -220
  30. package/dist/realtime/types.d.ts +0 -64
  31. package/dist/sync/entityIds.d.ts +14 -0
  32. package/dist/sync/entityIds.js +17 -0
  33. package/dist/sync/executors.js +14 -2
  34. package/dist/sync/models.d.ts +1 -0
  35. package/dist/sync/models.js +4 -0
  36. package/dist/sync/mutationHandler.js +51 -2
  37. package/dist/sync/routes.js +12 -17
  38. package/dist/sync/socketHandlers.d.ts +1 -1
  39. package/dist/sync/socketHandlers.js +1 -1
  40. package/dist/sync/types.d.ts +8 -0
  41. package/dist/terrenoApp.d.ts +7 -5
  42. package/dist/terrenoApp.js +18 -14
  43. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  44. package/dist/tests/openApiResponseSchema.js +56 -0
  45. package/dist/tests.d.ts +1 -0
  46. package/dist/tests.js +4 -1
  47. package/dist/types/mcpAdmin.d.ts +1 -1
  48. package/dist/types/mcpServiceToken.d.ts +7 -4
  49. package/dist/versionCheckPlugin.d.ts +1 -1
  50. package/dist/versionCheckPlugin.js +25 -2
  51. package/package.json +17 -6
  52. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  53. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  54. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  55. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  56. package/src/api.test.ts +9 -7
  57. package/src/api.ts +0 -24
  58. package/src/auth.ts +116 -5
  59. package/src/authOpenApi.test.ts +316 -0
  60. package/src/authRecovery.ts +47 -19
  61. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  62. package/src/collectionRegistry.ts +3 -5
  63. package/src/consentApp.test.ts +98 -0
  64. package/src/consentApp.ts +67 -2
  65. package/src/index.ts +6 -28
  66. package/src/mcp/actionTools.test.ts +2 -2
  67. package/src/mcp/adminTracking.ts +1 -1
  68. package/src/mcp/auth.test.ts +7 -3
  69. package/src/mcp/oauth.test.ts +12 -12
  70. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  71. package/src/mcp/serviceTokens.test.ts +112 -61
  72. package/src/mcp/serviceTokens.ts +193 -212
  73. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  74. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  75. package/src/models/mcpRequestLog.ts +1 -1
  76. package/src/models/mcpServiceToken.test.ts +52 -5
  77. package/src/models/mcpServiceToken.ts +51 -14
  78. package/src/openApiBuilder.test.ts +34 -1
  79. package/src/openApiBuilder.ts +5 -0
  80. package/src/rateLimit/rateLimit.test.ts +25 -10
  81. package/src/rbac/realtimeAccess.test.ts +20 -172
  82. package/src/rbac/realtimeAccess.ts +17 -82
  83. package/src/realtime/changeStreamWatcher.ts +43 -506
  84. package/src/realtime/realtime.test.ts +205 -2545
  85. package/src/realtime/realtimeApp.ts +16 -295
  86. package/src/realtime/types.ts +0 -72
  87. package/src/sync/entityIds.ts +18 -0
  88. package/src/sync/executors.test.ts +28 -0
  89. package/src/sync/executors.ts +23 -2
  90. package/src/sync/models.ts +6 -0
  91. package/src/sync/mutationHandler.test.ts +84 -0
  92. package/src/sync/mutationHandler.ts +57 -2
  93. package/src/sync/routes.ts +12 -17
  94. package/src/sync/socketHandlers.ts +1 -1
  95. package/src/sync/syncRoutes.test.ts +8 -4
  96. package/src/sync/syncSocket.test.ts +77 -113
  97. package/src/sync/types.ts +9 -0
  98. package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
  99. package/src/terrenoApp.ts +24 -18
  100. package/src/tests/openApiResponseSchema.ts +104 -0
  101. package/src/tests.ts +7 -0
  102. package/src/types/mcpAdmin.ts +1 -1
  103. package/src/types/mcpServiceToken.ts +7 -4
  104. package/src/versionCheckPlugin.ts +41 -2
  105. package/biome.jsonc +0 -22
  106. package/bunfig.toml +0 -10
  107. package/bunfig.unit.toml +0 -3
  108. package/dist/realtime/deprecation.d.ts +0 -13
  109. package/dist/realtime/deprecation.js +0 -31
  110. package/dist/realtime/queryStore.d.ts +0 -37
  111. package/dist/realtime/queryStore.js +0 -103
  112. package/dist/realtime/registry.d.ts +0 -15
  113. package/dist/realtime/registry.js +0 -52
  114. package/e2e/smoke.ts +0 -193
  115. package/src/realtime/deprecation.test.ts +0 -60
  116. package/src/realtime/deprecation.ts +0 -33
  117. package/src/realtime/queryStore.ts +0 -122
  118. package/src/realtime/registry.ts +0 -84
  119. package/tsconfig.json +0 -19
  120. package/tsconfig.typecheck.json +0 -14
  121. package/tsconfig.typedoc.json +0 -13
package/CHANGELOG.md CHANGED
@@ -20,6 +20,95 @@ Upgrade notes for consumer action live in [`mcp-server/src/docs/upgrades/`](mcp-
20
20
 
21
21
  Unreleased changes live in [`changelog/unreleased/`](changelog/unreleased/). Add one Markdown file per feature (see that directory's README) instead of editing this section.
22
22
 
23
+ ## [58.0.0-beta.2] - 2026-11-03
24
+
25
+ Upgrade note: [`mcp-server/src/docs/upgrades/58.0.0-beta.2.md`](mcp-server/src/docs/upgrades/58.0.0-beta.2.md).
26
+
27
+ ### Breaking
28
+
29
+ - Terreno 58 targets Expo SDK 58 (`~58.0.14`), React Native `0.88.0`, and React `19.3.0`. `@terreno/ui` peers `react-native` `0.88.0`. Native catalog moves with the SDK: `react-native-gesture-handler` `~3.3.0`, `react-native-reanimated` `4.7.1` + `react-native-worklets` `0.13.0`, `react-native-screens` `~4.30.0`, `react-native-webview` `14.0.1`, `@sentry/react-native` `~8.28.0`, `@shopify/flash-list` `2.3.2`, `@shopify/react-native-skia` `2.14.0`. Rebuild dev clients and store binaries.
30
+ - Expo Router 58: set `export const unstable_settings = {initialRouteName}` on the layout instead of passing `initialRouteName` to `<Slot>` / navigators. `SidebarNavigation` ignores the prop.
31
+ - Expo Router 58 static rendering: a custom `app/+html.tsx` must render `headNodes` and `bodyNodes` from `useServerDocumentContext()` (`expo-router/html`), or exported pages ship without their JavaScript. `example-frontend` is updated.
32
+ - React Native 0.88 generated types: type refs as `ViewInstance`, `TextInstance`, `ScrollViewInstance`, and `TextInputInstance` (`Box.scrollRef`, `TextField.inputRef`, `Text` `ref`).
33
+ - `create-terreno-app` scaffolds Expo `~58.0.14`, React Native `0.88.0`, and React `19.3.0`.
34
+ - The Terreno 58 native module baseline lands in `example-frontend` and `demo`: `@stripe/stripe-react-native` 0.81.0, `react-native-purchases` and `react-native-purchases-ui` 10.12.2, `expo-device`, `expo-crypto`, `expo-local-authentication`, `expo-system-ui`, and `expo-build-properties` (Android Kotlin 2.2.21 and `compileSdkVersion` 37 pins). Rebuild every dev client and store binary. `react-native-otp-verify` is left out because it does not support the New Architecture. The demo has a hidden **Native Modules** page that shows each module's version and whether the running binary links it. See the 58.0.0 upgrade note.
35
+ - `TerrenoApp` turns HTTP rate limiting on by default. Omitting `rateLimit` now mounts the limiter with the memory store (auth 20 / 15 min, api 600 / 15 min). Pass `rateLimit: false` to turn it off. On Cloud Run pass `rateLimit: {trustProxy: 1}` so unauthenticated traffic keys by client IP. See the 58.0.0 upgrade note.
36
+ - `@terreno/admin-frontend` no longer takes an RTK `api`. The `api` prop is removed from every admin component (`AdminProvider`, `AdminShellLayout`, `AdminHome`, `AdminModelList`, `AdminModelTable`, `AdminModelForm`, `AdminScreenRouter`, `ConfigurationScreen`, `DocumentStorageBrowser`, `ConsentHistory`, comms, jobs, org, consent, and announcement screens, and widget props), and admin hooks drop their `api` argument (`useAdminConfig(apiBase)`, `useAdminScripts(apiBase)`, `useAdminRoles(apiBase)`, `useConfigurationApi({basePath})`, `useDocumentStorageApi(basePath)`, `useConsentHistory(baseUrl)`, `useOrganizationsApi(basePath)`, `useCommsDashboardApi()`, `useJobsDashboardApi()`, and the `useAiObservability*Api()` hooks).
37
+ - `useAdminApi(api, routePath, modelName)` is removed. Use `useAdminModelApi(routePath, modelName)`, which keeps the same hook names and calls the same `/admin/{routePath}` URLs through the admin fetch client. `AdminApi`, `EndpointBuilder`, and admin `injectEndpoints` are gone; `@reduxjs/toolkit` and `react-redux` are no longer peers of admin-frontend.
38
+ - `AdminProvider` is now the required auth binding for every admin request, including ObjectId and API-only model CRUD. Cookie SPAs pass `credentials="same-origin"`; embedded apps pass `apiOrigin` and `getAuthHeaders`. Product screens that reuse admin components wrap them in `AdminProvider`. See the 58.0.0 upgrade guide.
39
+ - Removed the legacy RTK realtime path. Use `sync` on `modelRouter` with `@terreno/syncdb` for live collection updates. `RealtimeApp`, `SyncApp`, socket auth, `sync:delta`, and admin `admin:model.changed` events are unchanged. See the 58.0.0 upgrade note.
40
+ - `@terreno/api`: `modelRouter` no longer accepts `realtime` (now a TypeScript error), and the change stream no longer emits the `sync` websocket event. Removed `RealtimeConfig`, `RealtimeEvent`, `DocumentSubscription`, `QuerySubscription`, `registerRealtime`, `getRealtimeRegistry`, `findRegistryEntryByCollection`, `findRegistryEntryByRoutePath`, `updateRealtimeRegistryOptions`, `clearRealtimeRegistry`, `RealtimeRegistryEntry`, the query-subscription store (`addQuerySubscription`, `removeQuerySubscription`, `removeAllSocketQueries`, `getQuerySubscriptionsForCollection`, `computeQueryId`, `clearQueryStore`), and `MAX_MODEL_SUBSCRIPTIONS` / `MAX_DOCUMENT_SUBSCRIPTIONS` / `MAX_QUERY_SUBSCRIPTIONS`. Sockets no longer handle `subscribe:model`, `subscribe:document`, or `subscribe:query`.
41
+ - `@terreno/rtk`: removed `realtimeList`, `realtimeDocument`, `setRealtimeSocket`, `getRealtimeSocket`, `useSyncConnection`, and the `RealtimeEvent` type. The rest of `@terreno/rtk` (including `useSocketConnection` and `useRealtimeDebug`) is removed in the same release; see `remove-rtk.md`.
42
+ - Removed `@terreno/rtk` and every Redux dependency (`@reduxjs/toolkit`, `react-redux`, `redux-persist`, `@rtk-query/codegen-openapi`). `@terreno/rtk` is not published for 58. `@terreno/syncdb` is the only frontend data, request, and session layer. Follow `docs/how-to/migrate-rtk-to-syncdb.md`, which maps every removed export to its replacement, and the 58.0.0 upgrade note.
43
+ - `@terreno/syncdb` adds `@terreno/syncdb/api` (`createApiClient`, `ApiError`), request hooks in `@terreno/syncdb/react` (`ApiClientProvider`, `useApiQuery`, `useLazyApiQuery`, `useApiMutation`, `useSocketEvent`), `@terreno/syncdb/config` (`baseUrl`, `baseWebsocketsUrl`, `appHeaders`), `@terreno/syncdb/auth` (`createBetterAuthClient`, `SessionProvider`, `useSession`, `jwtAuthAdapter`, `useJwtAuth`, token-expiry helpers), `@terreno/syncdb/flags` (`useFeatureFlags`, `useTerrenoFeatureFlags` on the sync socket), `@terreno/syncdb/app` (`useUpgradeCheck`, `hasPermission`, `canOpenAdminPage`, `installDevConsoleLogger`, `useMCPTools`), and `@terreno/syncdb/buildNumber`.
44
+ - `terreno-syncdb-codegen --api-out` generates typed hooks for every non-synced OpenAPI operation (same names as the RTK codegen), replacing `@rtk-query/codegen-openapi`. `bun run sdk` writes `store/apiSdk.ts`.
45
+ - `@terreno/ui` `ConsentNavigator`, `AnnouncementNavigator`, `useConsentForms`, `useSubmitConsent`, `useAnnouncements`, and `useAcknowledgeAnnouncement` take a request `client` instead of an RTK `api`.
46
+ - `GptHistory` (`gpt/histories`) is a synced collection and keeps its ObjectId `_id` (no migration). `McpServiceToken` (`mcp/service-tokens`, read-only) is a synced collection with String ids; run `mcpServiceTokenStringIdsMigration` (`@terreno/api`) before deploying 58 frontends.
47
+ - `create-terreno-app`, the `terreno_bootstrap` prompt, and the `terreno_generate_screen` tool scaffold apps without Redux or `@terreno/rtk`. The terreno-mcp-local `get_rtk_state` tool, the MCP resource `terreno://docs/rtk`, and `terreno state --slice rtk` are removed; use `get_syncdb_state` and `terreno state`.
48
+
49
+ ### Added
50
+
51
+ - `DataTable` columns size themselves when `width` is omitted. Each auto column starts at the wider of its header and its content (sampled from at most 50 rows, measured with a canvas on web and estimated on native), clamped to 80–360px, and auto columns grow to fill the table's container. Columns that set `width` keep it. `DataTableColumn.width` is now optional.
52
+ - `@terreno/syncdb` `createSyncDb({idFormats})` mints 24-hex ObjectIds for a collection set to `"objectId"`, so a model that keeps Mongoose's default ObjectId `_id` can sync without migrating its ids. `mutate()` throws on an explicit non-hex id for such a collection. `generateObjectId` and the `SyncIdFormat` type are exported.
53
+ - Sync `validation` nacks carry an optional `reason`: `invalid_id` when an ObjectId-keyed collection gets a non-hex id (rejected before the mutation is claimed), and `id_collision` when a create names an `_id` another document holds. A collision never touches the existing document and its message never names the holder. The ledger records the reason (`SyncMutation.nackReason`) so a redelivery replays it.
54
+ - `GET /sync/entities` leaves out non-hex ids for an ObjectId-keyed model instead of answering 400, so a rejected create queued for repair cannot fail the rest of the repair batch.
55
+
56
+ ### Changed
57
+
58
+ - The repository's agent rules now generate with rulesync 17 (up from 9). The root rule `.rulesync/rules/00-root.md` now generates `AGENTS.md`, which Devin and other AGENTS.md readers load, in place of `.devin/rules/00-root.md`. Never edit `AGENTS.md` by hand: edit the root rule and run `bun run rules`. The examples that existed only in the old hand-edited `AGENTS.md` (syncdb and RTK SDK usage) moved into the root rule, so `CLAUDE.md`, the Cursor root rule, and Copilot instructions get them too. Links in the root rule now resolve from the repository root. Generated Copilot hooks use the portable `command` field. Generated Copilot subagents no longer list `agent/runSubagent` as their only tool, so they get every default tool. Generated skills carry their `license`, `disable-model-invocation`, and Devin `triggers` frontmatter.
59
+ - `@terreno/syncdb/auth` `SessionProvider`: `logout()` no longer clears the session before the server answers. The session stays in the state until `authClient.signOut()` finishes (`signOutTimeoutMs`, default 10 seconds), and then it is cleared. Meanwhile the new `isSigningOut` state (`useSession().isSigningOut`) is true; `isLoading` is left alone, so a navigator gated on it keeps its screen. Before, a login screen that opened at once could find the still-live session and sign the user straight back in. A sign-out that fails or times out checks the session first. A session that is still live, or a cookie or native session the server cannot be asked about, stays signed in, and `error` is set to `SIGN_OUT_FAILED_MESSAGE` ("Couldn't sign out. Check your connection and try again."). A web bearer client, which drops its token before the request leaves, ends signed out. The global `auth/logout` action (a refused session) now ends signed out even when the sign-out request fails. With `apisToReset` (57.17.0), `logout()` purges the cache when the session clears, not when it is dispatched: a purge at dispatch refetched every mounted screen mid-sign-out, and a refetch that could not reach the server answered 401 and signed the user out even though the sign-out failed. A failed sign-out keeps both the session and the cache. The global `auth/logout` action still purges at once (only the first of several in flight) and again when the session clears. A sign-in for another user that lands while a sign-out is in flight is kept; a sign-out that started signed out asks `getSession` first, so a restore of the session it revoked is cleared. Show `selectBetterAuthIsSigningOut` on the sign-out control and `selectBetterAuthError` after a failed sign-out.
60
+
61
+ ### Removed
62
+
63
+ - `@terreno/ui` no longer exports the `Filter` and `FilterProps` aliases deprecated in 57.7.0. Import `DropdownPanel` and `DropdownPanelProps` instead. `FilterSelectMenu`, `FilterBoolean`, `FilterAccordion`, and `FilterChangesBadge` keep their names.
64
+
65
+ ### Fixed
66
+
67
+ - `@terreno/syncdb`: logging out while `syncDb.start()` is still running no longer loses local writes or logs errors. `start()` now resolves the web encryption key from `GET /sync/key` before it loads the store, so the flush in `stop()` never needs the network after the session has ended. A `stop()` or `signOut()` call now cancels a `start()` that is running or queued ahead of it, so the transport never connects without a session. A failed key fetch is now retried on the next save instead of failing every save for the rest of the session.
68
+
69
+ ## [58.0.0-beta.1] - 2026-11-02
70
+
71
+ Upgrade note: [`mcp-server/src/docs/upgrades/58.0.0-beta.1.md`](mcp-server/src/docs/upgrades/58.0.0-beta.1.md).
72
+
73
+ ### Breaking
74
+
75
+ - Terreno 58 targets Expo SDK 58 (`~58.0.14`), React Native `0.88.0`, and React `19.3.0`. `@terreno/ui` peers `react-native` `0.88.0`. Native catalog moves with the SDK: `react-native-gesture-handler` `~3.3.0`, `react-native-reanimated` `4.7.1` + `react-native-worklets` `0.13.0`, `react-native-screens` `~4.30.0`, `react-native-webview` `14.0.1`, `@sentry/react-native` `~8.28.0`, `@shopify/flash-list` `2.3.2`, `@shopify/react-native-skia` `2.14.0`. Rebuild dev clients and store binaries.
76
+ - Expo Router 58: set `export const unstable_settings = {initialRouteName}` on the layout instead of passing `initialRouteName` to `<Slot>` / navigators. `SidebarNavigation` ignores the prop.
77
+ - Expo Router 58 static rendering: a custom `app/+html.tsx` must render `headNodes` and `bodyNodes` from `useServerDocumentContext()` (`expo-router/html`), or exported pages ship without their JavaScript. `example-frontend` is updated.
78
+ - React Native 0.88 generated types: type refs as `ViewInstance`, `TextInstance`, `ScrollViewInstance`, and `TextInputInstance` (`Box.scrollRef`, `TextField.inputRef`, `Text` `ref`).
79
+ - `create-terreno-app` scaffolds Expo `~58.0.14`, React Native `0.88.0`, and React `19.3.0`.
80
+ - The Terreno 58 native module baseline lands in `example-frontend` and `demo`: `@stripe/stripe-react-native` 0.81.0, `react-native-purchases` and `react-native-purchases-ui` 10.12.2, `expo-device`, `expo-crypto`, `expo-local-authentication`, `expo-system-ui`, and `expo-build-properties` (Android Kotlin 2.2.21 and `compileSdkVersion` 37 pins). Rebuild every dev client and store binary. `react-native-otp-verify` is left out because it does not support the New Architecture. The demo has a hidden **Native Modules** page that shows each module's version and whether the running binary links it. See the 58.0.0 upgrade note.
81
+ - `TerrenoApp` turns HTTP rate limiting on by default. Omitting `rateLimit` now mounts the limiter with the memory store (auth 20 / 15 min, api 600 / 15 min). Pass `rateLimit: false` to turn it off. On Cloud Run pass `rateLimit: {trustProxy: 1}` so unauthenticated traffic keys by client IP. See the 58.0.0 upgrade note.
82
+ - `@terreno/admin-frontend` no longer takes an RTK `api`. The `api` prop is removed from every admin component (`AdminProvider`, `AdminShellLayout`, `AdminHome`, `AdminModelList`, `AdminModelTable`, `AdminModelForm`, `AdminScreenRouter`, `ConfigurationScreen`, `DocumentStorageBrowser`, `ConsentHistory`, comms, jobs, org, consent, and announcement screens, and widget props), and admin hooks drop their `api` argument (`useAdminConfig(apiBase)`, `useAdminScripts(apiBase)`, `useAdminRoles(apiBase)`, `useConfigurationApi({basePath})`, `useDocumentStorageApi(basePath)`, `useConsentHistory(baseUrl)`, `useOrganizationsApi(basePath)`, `useCommsDashboardApi()`, `useJobsDashboardApi()`, and the `useAiObservability*Api()` hooks).
83
+ - `useAdminApi(api, routePath, modelName)` is removed. Use `useAdminModelApi(routePath, modelName)`, which keeps the same hook names and calls the same `/admin/{routePath}` URLs through the admin fetch client. `AdminApi`, `EndpointBuilder`, and admin `injectEndpoints` are gone; `@reduxjs/toolkit` and `react-redux` are no longer peers of admin-frontend.
84
+ - `AdminProvider` is now the required auth binding for every admin request, including ObjectId and API-only model CRUD. Cookie SPAs pass `credentials="same-origin"`; embedded apps pass `apiOrigin` and `getAuthHeaders`. Product screens that reuse admin components wrap them in `AdminProvider`. See the 58.0.0 upgrade guide.
85
+ - Removed the legacy RTK realtime path. Use `sync` on `modelRouter` with `@terreno/syncdb` for live collection updates. `RealtimeApp`, `SyncApp`, socket auth, `sync:delta`, and admin `admin:model.changed` events are unchanged. See the 58.0.0 upgrade note.
86
+ - `@terreno/api`: `modelRouter` no longer accepts `realtime` (now a TypeScript error), and the change stream no longer emits the `sync` websocket event. Removed `RealtimeConfig`, `RealtimeEvent`, `DocumentSubscription`, `QuerySubscription`, `registerRealtime`, `getRealtimeRegistry`, `findRegistryEntryByCollection`, `findRegistryEntryByRoutePath`, `updateRealtimeRegistryOptions`, `clearRealtimeRegistry`, `RealtimeRegistryEntry`, the query-subscription store (`addQuerySubscription`, `removeQuerySubscription`, `removeAllSocketQueries`, `getQuerySubscriptionsForCollection`, `computeQueryId`, `clearQueryStore`), and `MAX_MODEL_SUBSCRIPTIONS` / `MAX_DOCUMENT_SUBSCRIPTIONS` / `MAX_QUERY_SUBSCRIPTIONS`. Sockets no longer handle `subscribe:model`, `subscribe:document`, or `subscribe:query`.
87
+ - `@terreno/rtk`: removed `realtimeList`, `realtimeDocument`, `setRealtimeSocket`, `getRealtimeSocket`, `useSyncConnection`, and the `RealtimeEvent` type. The rest of `@terreno/rtk` (including `useSocketConnection` and `useRealtimeDebug`) is removed in the same release; see `remove-rtk.md`.
88
+ - Removed `@terreno/rtk` and every Redux dependency (`@reduxjs/toolkit`, `react-redux`, `redux-persist`, `@rtk-query/codegen-openapi`). `@terreno/rtk` is not published for 58. `@terreno/syncdb` is the only frontend data, request, and session layer. Follow `docs/how-to/migrate-rtk-to-syncdb.md`, which maps every removed export to its replacement, and the 58.0.0 upgrade note.
89
+ - `@terreno/syncdb` adds `@terreno/syncdb/api` (`createApiClient`, `ApiError`), request hooks in `@terreno/syncdb/react` (`ApiClientProvider`, `useApiQuery`, `useLazyApiQuery`, `useApiMutation`, `useSocketEvent`), `@terreno/syncdb/config` (`baseUrl`, `baseWebsocketsUrl`, `appHeaders`), `@terreno/syncdb/auth` (`createBetterAuthClient`, `SessionProvider`, `useSession`, `jwtAuthAdapter`, `useJwtAuth`, token-expiry helpers), `@terreno/syncdb/flags` (`useFeatureFlags`, `useTerrenoFeatureFlags` on the sync socket), `@terreno/syncdb/app` (`useUpgradeCheck`, `hasPermission`, `canOpenAdminPage`, `installDevConsoleLogger`, `useMCPTools`), and `@terreno/syncdb/buildNumber`.
90
+ - `terreno-syncdb-codegen --api-out` generates typed hooks for every non-synced OpenAPI operation (same names as the RTK codegen), replacing `@rtk-query/codegen-openapi`. `bun run sdk` writes `store/apiSdk.ts`.
91
+ - `@terreno/ui` `ConsentNavigator`, `AnnouncementNavigator`, `useConsentForms`, `useSubmitConsent`, `useAnnouncements`, and `useAcknowledgeAnnouncement` take a request `client` instead of an RTK `api`.
92
+ - `GptHistory` (`gpt/histories`) and `McpServiceToken` (`mcp/service-tokens`, read-only) are synced collections with String ids. Run the `gptHistoryStringIdsMigration` (`@terreno/ai`) and `mcpServiceTokenStringIdsMigration` (`@terreno/api`) before deploying 58 frontends.
93
+ - `create-terreno-app`, the `terreno_bootstrap` prompt, and the `terreno_generate_screen` tool scaffold apps without Redux or `@terreno/rtk`. The terreno-mcp-local `get_rtk_state` tool, the MCP resource `terreno://docs/rtk`, and `terreno state --slice rtk` are removed; use `get_syncdb_state` and `terreno state`.
94
+
95
+ ### Added
96
+
97
+ - `DataTable` columns size themselves when `width` is omitted. Each auto column starts at the wider of its header and its content (sampled from at most 50 rows, measured with a canvas on web and estimated on native), clamped to 80–360px, and auto columns grow to fill the table's container. Columns that set `width` keep it. `DataTableColumn.width` is now optional.
98
+
99
+ ### Changed
100
+
101
+ - The repository's agent rules now generate with rulesync 17 (up from 9). The root rule `.rulesync/rules/00-root.md` now generates `AGENTS.md`, which Devin and other AGENTS.md readers load, in place of `.devin/rules/00-root.md`. Never edit `AGENTS.md` by hand: edit the root rule and run `bun run rules`. The examples that existed only in the old hand-edited `AGENTS.md` (syncdb and RTK SDK usage) moved into the root rule, so `CLAUDE.md`, the Cursor root rule, and Copilot instructions get them too. Links in the root rule now resolve from the repository root. Generated Copilot hooks use the portable `command` field. Generated Copilot subagents no longer list `agent/runSubagent` as their only tool, so they get every default tool. Generated skills carry their `license`, `disable-model-invocation`, and Devin `triggers` frontmatter.
102
+ - `@terreno/syncdb/auth` `SessionProvider`: `logout()` no longer clears the session before the server answers. The session stays in the state until `authClient.signOut()` finishes (`signOutTimeoutMs`, default 10 seconds), and then it is cleared. Meanwhile the new `isSigningOut` state (`useSession().isSigningOut`) is true; `isLoading` is left alone, so a navigator gated on it keeps its screen. Before, a login screen that opened at once could find the still-live session and sign the user straight back in. A sign-out that fails or times out checks the session first. A session that is still live, or a cookie or native session the server cannot be asked about, stays signed in, and `error` is set to `SIGN_OUT_FAILED_MESSAGE` ("Couldn't sign out. Check your connection and try again."). A web bearer client, which drops its token before the request leaves, ends signed out. The global `auth/logout` action (a refused session) now ends signed out even when the sign-out request fails. With `apisToReset` (57.17.0), `logout()` purges the cache when the session clears, not when it is dispatched: a purge at dispatch refetched every mounted screen mid-sign-out, and a refetch that could not reach the server answered 401 and signed the user out even though the sign-out failed. A failed sign-out keeps both the session and the cache. The global `auth/logout` action still purges at once (only the first of several in flight) and again when the session clears. A sign-in for another user that lands while a sign-out is in flight is kept; a sign-out that started signed out asks `getSession` first, so a restore of the session it revoked is cleared. Show `selectBetterAuthIsSigningOut` on the sign-out control and `selectBetterAuthError` after a failed sign-out.
103
+
104
+ ### Removed
105
+
106
+ - `@terreno/ui` no longer exports the `Filter` and `FilterProps` aliases deprecated in 57.7.0. Import `DropdownPanel` and `DropdownPanelProps` instead. `FilterSelectMenu`, `FilterBoolean`, `FilterAccordion`, and `FilterChangesBadge` keep their names.
107
+
108
+ ### Fixed
109
+
110
+ - `@terreno/syncdb`: logging out while `syncDb.start()` is still running no longer loses local writes or logs errors. `start()` now resolves the web encryption key from `GET /sync/key` before it loads the store, so the flush in `stop()` never needs the network after the session has ended. A `stop()` or `signOut()` call now cancels a `start()` that is running or queued ahead of it, so the transport never connects without a session. A failed key fetch is now retried on the next save instead of failing every save for the rest of the session.
111
+
23
112
  ## [57.21.0] - 2026-11-01
24
113
 
25
114
  Upgrade note: [`mcp-server/src/docs/upgrades/57.21.0.md`](mcp-server/src/docs/upgrades/57.21.0.md).
package/README.md CHANGED
@@ -7,7 +7,7 @@ Most REST APIs wind up being a lot of boilerplate, so this tries to cut that dow
7
7
  into a full blown framework of its own. This library is inspired by the
8
8
  [Django-REST-Framework](https://www.django-rest-framework.org).
9
9
 
10
- These APIs integrate with @terreno/rtk to create consistent types on the frontend
10
+ These APIs integrate with @terreno/syncdb to create consistent types on the frontend
11
11
  and backend, and automatically generated React hooks to fetch, query, and modify
12
12
  model instances.
13
13
 
package/dist/api.d.ts CHANGED
@@ -10,7 +10,6 @@ import { type ModelRouterValidationOptions } from "./openApiValidator";
10
10
  import { type RESTPermissions } from "./permissions";
11
11
  import type { PopulatePath } from "./populate";
12
12
  import type { AnyTerrenoAccess, ModelRouterAccessOptions } from "./rbac/types";
13
- import type { RealtimeConfig } from "./realtime/types";
14
13
  import type { SyncConfig } from "./sync/types";
15
14
  import { type TerrenoTransformer } from "./transformers";
16
15
  type ModelLike<T> = Model<T, any, any, any, any, any>;
@@ -290,18 +289,6 @@ export interface ModelRouterOptions<T> {
290
289
  * ```
291
290
  */
292
291
  mcp?: MCPConfig;
293
- /**
294
- * Enable real-time sync for this model via WebSocket events.
295
- * When configured, CRUD operations will emit events to connected clients
296
- * through the RealtimeApp plugin's change stream watcher.
297
- *
298
- * Requires the RealtimeApp plugin to be registered with TerrenoApp.
299
- *
300
- * @deprecated Removed in Terreno 58. Use `sync` with
301
- * `@terreno/syncdb` instead. `RealtimeApp` remains required for sync sockets.
302
- * See docs/how-to/migrate-rtk-to-syncdb.md.
303
- */
304
- realtime?: RealtimeConfig;
305
292
  /**
306
293
  * Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
307
294
  * into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
package/dist/api.js CHANGED
@@ -61,7 +61,6 @@ const openApiValidator_1 = require("./openApiValidator");
61
61
  const permissions_1 = require("./permissions");
62
62
  const modelRouterAccess_1 = require("./rbac/modelRouterAccess");
63
63
  const userWriteGuards_1 = require("./rbac/userWriteGuards");
64
- const deprecation_1 = require("./realtime/deprecation");
65
64
  const sortFields_1 = require("./sortFields");
66
65
  const executors_1 = require("./sync/executors");
67
66
  const transformers_1 = require("./transformers");
@@ -311,9 +310,6 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
311
310
  }
312
311
  const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
313
312
  if (path !== undefined) {
314
- if (options.realtime) {
315
- (0, deprecation_1.warnRealtimeDeprecated)(model.modelName, path);
316
- }
317
313
  (0, collectionRegistry_1.registerCollection)({ model, options, routePath: path });
318
314
  }
319
315
  const router = shouldDeferBuild ? express_1.default.Router() : _buildModelRouter(model, options, path);
@@ -335,11 +331,6 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
335
331
  router,
336
332
  };
337
333
  }
338
- if (options.realtime) {
339
- (0, deprecation_1.warnRealtimeDeprecated)(model.modelName);
340
- logger_1.logger.warn(`modelRouter for ${model.modelName} has realtime config but was called without a path. ` +
341
- "Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)");
342
- }
343
334
  if (options.sync) {
344
335
  logger_1.logger.warn(`modelRouter for ${model.modelName} has sync config but was called without a path. ` +
345
336
  "Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)");
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import express from "express";
2
2
  import type { Model, ObjectId, Query } from "mongoose";
3
3
  import passport from "passport";
4
+ import type { OpenApiMiddleware } from "./api";
4
5
  import type { AuthOptions } from "./expressServer";
5
6
  export interface User {
6
7
  _id: ObjectId | string;
@@ -131,5 +132,5 @@ export declare const generateTokens: (user: unknown, authOptions?: AuthOptions,
131
132
  */
132
133
  export declare const isUserDisabled: (user: unknown) => boolean;
133
134
  export declare const setupAuth: (app: express.Application, userModel: UserModel) => void;
134
- export declare const addAuthRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions) => void;
135
- export declare const addMeRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions, accessControl?: import("./rbac/types").AnyTerrenoAccess) => void;
135
+ export declare const addAuthRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions, openApi?: OpenApiMiddleware) => void;
136
+ export declare const addMeRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions, accessControl?: import("./rbac/types").AnyTerrenoAccess, openApi?: OpenApiMiddleware) => void;
package/dist/auth.js CHANGED
@@ -17,6 +17,8 @@ const authRecovery_1 = require("./authRecovery");
17
17
  const authTokens_1 = require("./authTokens");
18
18
  const errors_1 = require("./errors");
19
19
  const logger_1 = require("./logger");
20
+ const openApiBuilder_1 = require("./openApiBuilder");
21
+ const populate_1 = require("./populate");
20
22
  const policies_1 = require("./rateLimit/policies");
21
23
  const userWriteGuards_1 = require("./rbac/userWriteGuards");
22
24
  const requestContext_1 = require("./requestContext");
@@ -532,7 +534,7 @@ const setupAuth = (app, userModel) => {
532
534
  app.use(express_1.default.urlencoded({ extended: false }));
533
535
  };
534
536
  exports.setupAuth = setupAuth;
535
- const addAuthRoutes = (app, userModel, authOptions) => {
537
+ const addAuthRoutes = (app, userModel, authOptions, openApi) => {
536
538
  const router = express_1.default.Router();
537
539
  router.post("/login", async (req, res, next) => {
538
540
  passport_1.default.authenticate("local", { session: false }, async (err, user, info) => {
@@ -654,12 +656,100 @@ const addAuthRoutes = (app, userModel, authOptions) => {
654
656
  }
655
657
  app.set("etag", false);
656
658
  app.use("/auth", router);
657
- (0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions);
659
+ (0, authRecovery_1.addAuthRecoveryRoutes)(app, userModel, authOptions, openApi);
658
660
  };
659
661
  exports.addAuthRoutes = addAuthRoutes;
660
- const addMeRoutes = (app, userModel, authOptions, accessControl) => {
662
+ /** Fields `PATCH /auth/me` cannot meaningfully set: identity and server-managed timestamps. */
663
+ const ME_PATCH_EXCLUDED_FIELDS = ["_id", "id", "__v", "created", "updated", "deleted"];
664
+ /**
665
+ * OpenAPI properties of the app's user model as `/auth/me` returns them. Paths with
666
+ * `select: false` (passport-local-mongoose `hash` and `salt`) are never loaded by `findById`,
667
+ * so they are left out of the documented shape.
668
+ */
669
+ const getMeUserOpenApiSpec = (userModel) => {
670
+ const { properties, required } = (0, populate_1.getOpenApiSpecForModel)(userModel);
671
+ const visible = {};
672
+ for (const [key, value] of Object.entries(properties)) {
673
+ const schemaPath = userModel.schema.path(key);
674
+ if (schemaPath?.options?.select === false) {
675
+ continue;
676
+ }
677
+ visible[key] = value;
678
+ }
679
+ return { properties: visible, required: required.filter((field) => field in visible) };
680
+ };
681
+ const buildMeOpenApi = ({ accessControl, openApi, userModel, }) => {
682
+ const noop = (_req, _res, next) => next();
683
+ if (!openApi?.path) {
684
+ return { get: noop, patch: noop };
685
+ }
686
+ const user = getMeUserOpenApiSpec(userModel);
687
+ const idProperty = {
688
+ description: "The user's id, the same value as _id",
689
+ type: "string",
690
+ };
691
+ const userRequired = Array.from(new Set([...user.required, "_id", "id"]));
692
+ const meUser = {
693
+ properties: {
694
+ ...user.properties,
695
+ id: idProperty,
696
+ ...(accessControl
697
+ ? {
698
+ permissions: {
699
+ additionalProperties: { items: { type: "string" }, type: "array" },
700
+ description: "RBAC permissions resolved for the user, keyed by resource",
701
+ type: "object",
702
+ },
703
+ roles: {
704
+ description: "RBAC role names assigned to the user",
705
+ items: { type: "string" },
706
+ type: "array",
707
+ },
708
+ }
709
+ : {}),
710
+ },
711
+ required: accessControl ? [...userRequired, "permissions", "roles"] : userRequired,
712
+ type: "object",
713
+ };
714
+ const patchedUser = {
715
+ properties: { ...user.properties, id: idProperty },
716
+ required: userRequired,
717
+ type: "object",
718
+ };
719
+ const patchBody = {};
720
+ for (const [key, value] of Object.entries(user.properties)) {
721
+ if (ME_PATCH_EXCLUDED_FIELDS.includes(key) ||
722
+ exports.PRIVILEGED_USER_FIELDS.includes(key)) {
723
+ continue;
724
+ }
725
+ patchBody[key] = value;
726
+ }
727
+ patchBody[CURRENT_PASSWORD_FIELD] = {
728
+ description: "The current password; required to change the email. It is never stored.",
729
+ type: "string",
730
+ };
731
+ // Documentation only: request validation stays off so the handlers behave as before.
732
+ return {
733
+ get: (0, openApiBuilder_1.createOpenApiBuilder)({ openApi })
734
+ .withTags(["auth"])
735
+ .withSummary("Get the current user")
736
+ .withResponse(200, { data: meUser }, { required: ["data"] })
737
+ .withValidation({ enabled: false })
738
+ .build(),
739
+ patch: (0, openApiBuilder_1.createOpenApiBuilder)({ openApi })
740
+ .withTags(["auth"])
741
+ .withSummary("Update the current user")
742
+ .withDescription("Partial update of the current user. Privileged fields (admin, roles, organizationIds, emailVerified, tokenEpoch) are ignored.")
743
+ .withRequestBody(patchBody)
744
+ .withResponse(200, { data: patchedUser }, { required: ["data"] })
745
+ .withValidation({ enabled: false })
746
+ .build(),
747
+ };
748
+ };
749
+ const addMeRoutes = (app, userModel, authOptions, accessControl, openApi) => {
661
750
  const router = express_1.default.Router();
662
- router.get("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
751
+ const meOpenApi = buildMeOpenApi({ accessControl, openApi, userModel });
752
+ router.get("/me", (0, exports.authenticateMiddleware)(), meOpenApi.get, async (req, res) => {
663
753
  if (!req.user?.id) {
664
754
  logger_1.logger.debug("Not user found for /me");
665
755
  return res.sendStatus(401);
@@ -680,7 +770,7 @@ const addMeRoutes = (app, userModel, authOptions, accessControl) => {
680
770
  }
681
771
  return res.json({ data: dataObject });
682
772
  });
683
- router.patch("/me", (0, exports.authenticateMiddleware)(), async (req, res) => {
773
+ router.patch("/me", (0, exports.authenticateMiddleware)(), meOpenApi.patch, async (req, res) => {
684
774
  if (!req.user?.id) {
685
775
  return res.sendStatus(401);
686
776
  }
@@ -1,4 +1,5 @@
1
1
  import express from "express";
2
+ import { type OpenApiMiddleware } from "./api";
2
3
  import { type User, type UserModel } from "./auth";
3
4
  import type { AuthOptions } from "./expressServer";
4
5
  export declare const sendVerificationEmail: (user: User, authOptions?: AuthOptions) => Promise<void>;
@@ -33,4 +34,4 @@ export interface ChangeUserPasswordOptions {
33
34
  * `setPasswordForUser` alone revokes nothing.
34
35
  */
35
36
  export declare const changeUserPassword: (user: User, password: string, options?: ChangeUserPasswordOptions) => Promise<void>;
36
- export declare const addAuthRecoveryRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions) => void;
37
+ export declare const addAuthRecoveryRoutes: (app: express.Application, userModel: UserModel, authOptions?: AuthOptions, openApi?: OpenApiMiddleware) => void;
@@ -166,6 +166,13 @@ const hasLegacyPassword = async (userModel, user) => {
166
166
  const incrementTokenEpoch = (user) => {
167
167
  user.tokenEpoch = (user.tokenEpoch ?? 0) + 1;
168
168
  };
169
+ const okResponse = {
170
+ data: {
171
+ properties: { ok: { type: "boolean" } },
172
+ required: ["ok"],
173
+ type: "object",
174
+ },
175
+ };
169
176
  // The auth options passed to addAuthRoutes, kept on the app so changeUserPassword can reach the
170
177
  // Better Auth credential sync that TerrenoApp wires after the routes are added.
171
178
  const AUTH_OPTIONS_LOCAL_KEY = "terrenoAuthOptions";
@@ -188,7 +195,8 @@ const changeUserPassword = async (user, password, options = {}) => {
188
195
  }
189
196
  };
190
197
  exports.changeUserPassword = changeUserPassword;
191
- const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
198
+ const addAuthRecoveryRoutes = (app, userModel, authOptions, openApi) => {
199
+ const openApiOptions = openApi ? { openApi } : {};
192
200
  if (authOptions) {
193
201
  app.locals[AUTH_OPTIONS_LOCAL_KEY] = authOptions;
194
202
  }
@@ -271,25 +279,33 @@ const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
271
279
  data: { refreshToken: tokens.refreshToken, token: tokens.token, userId: user._id },
272
280
  });
273
281
  });
274
- const forgotOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)({})
282
+ const forgotOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
275
283
  .withTags(["auth"])
276
284
  .withSummary("Request a password reset email")
277
- .withRequestBody({ email: { type: "string" } })
278
- .withResponse(202, { ok: { type: "boolean" } })
285
+ .withDescription("Always returns 202, whether or not an account exists for the email, so accounts cannot be probed.")
286
+ .withRequestBody({ email: { description: "The account's email address", type: "string" } })
287
+ .withResponse(202, okResponse, { description: "Accepted", required: ["data"] })
279
288
  .build();
280
- const resetOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)({})
289
+ const resetOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
281
290
  .withTags(["auth"])
282
291
  .withSummary("Reset password with a one-time token")
292
+ .withDescription("Send `token` and either `password` or `newPassword`. Returns fresh tokens for the user.")
283
293
  .withRequestBody({
284
- newPassword: { type: "string" },
285
- password: { type: "string" },
286
- token: { type: "string" },
294
+ newPassword: { description: "Alias for password", type: "string" },
295
+ password: { description: "The new password", type: "string" },
296
+ token: { description: "One-time reset token from the emailed link", type: "string" },
287
297
  })
288
298
  .withResponse(200, {
289
- refreshToken: { type: "string" },
290
- token: { type: "string" },
291
- userId: { type: "string" },
292
- })
299
+ data: {
300
+ properties: {
301
+ refreshToken: { type: "string" },
302
+ token: { type: "string" },
303
+ userId: { type: "string" },
304
+ },
305
+ required: ["refreshToken", "token", "userId"],
306
+ type: "object",
307
+ },
308
+ }, { required: ["data"] })
293
309
  .build();
294
310
  const sendVerification = (0, api_1.asyncHandler)(async (req, res) => {
295
311
  const user = req.user;
@@ -316,16 +332,18 @@ const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
316
332
  await user.save();
317
333
  return res.json({ data: { ok: true } });
318
334
  });
319
- const sendVerificationOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)({})
335
+ const sendVerificationOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
320
336
  .withTags(["auth"])
321
337
  .withSummary("Send or resend an email verification link")
322
- .withResponse(202, { ok: { type: "boolean" } })
338
+ .withResponse(202, okResponse, { description: "Accepted", required: ["data"] })
323
339
  .build();
324
- const verifyEmailOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)({})
340
+ const verifyEmailOpenApi = (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
325
341
  .withTags(["auth"])
326
342
  .withSummary("Verify email with a one-time token")
327
- .withRequestBody({ token: { type: "string" } })
328
- .withResponse(200, { ok: { type: "boolean" } })
343
+ .withRequestBody({
344
+ token: { description: "One-time verification token from the emailed link", type: "string" },
345
+ })
346
+ .withResponse(200, okResponse, { required: ["data"] })
329
347
  .build();
330
348
  const router = express_1.default.Router();
331
349
  if (authOptions?.passwordReset !== false) {
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * Process-global catalog of modelRouter collections, keyed by routePath
3
- * (e.g. `/todos`). MCP, realtime, and Sync read this Map instead of each
3
+ * (e.g. `/todos`). MCP and Sync read this Map instead of each
4
4
  * keeping their own list. `modelRouter` is the writer; surface `register*`
5
5
  * / `update*` / `clear*` helpers are wrappers around this module.
6
6
  *
7
7
  * TerrenoApp later injects `accessControl` into options. That patch goes
8
- * through replaceCollectionOptions so all three surfaces see one options
8
+ * through replaceCollectionOptions so every surface sees one options
9
9
  * object. Surface flags stay sticky (OR) so a later replace cannot drop
10
- * mcp/realtime/sync once enabled. First-time sync enable still runs schema
10
+ * mcp/sync once enabled. First-time sync enable still runs schema
11
11
  * and index guards in registrationSideEffects — not here — so catalog
12
12
  * writes stay a Map update.
13
13
  */
@@ -15,7 +15,6 @@ import type { Model } from "mongoose";
15
15
  import type { ModelRouterOptions } from "./api";
16
16
  interface CollectionSurfaces {
17
17
  mcp: boolean;
18
- realtime: boolean;
19
18
  sync: boolean;
20
19
  }
21
20
  export interface CollectionRecord {
@@ -18,7 +18,6 @@ const collectionRegistry = new Map();
18
18
  /** OR new option flags onto existing ones so a patch cannot disable a surface. */
19
19
  const deriveSurfaces = (options, existing) => ({
20
20
  mcp: Boolean(options.mcp) || (existing?.mcp ?? false),
21
- realtime: Boolean(options.realtime) || (existing?.realtime ?? false),
22
21
  sync: Boolean(options.sync) || (existing?.sync ?? false),
23
22
  });
24
23
  /** Insert or merge a collection. First sync enable runs schema/index guards. */
@@ -8,7 +8,7 @@
8
8
  import { type Application } from "express";
9
9
  import type { AdminContribution } from "./adminTypes";
10
10
  import { type ResolveConsentForms } from "./consentStatus";
11
- import type { PopulatePath } from "./populate";
11
+ import { type PopulatePath } from "./populate";
12
12
  import type { AnyTerrenoAccess } from "./rbac/types";
13
13
  import type { TerrenoPlugin } from "./terrenoPlugin";
14
14
  /** Shared populate config for consent response list/read endpoints. */
@@ -18,7 +18,9 @@ const errors_1 = require("./errors");
18
18
  const logger_1 = require("./logger");
19
19
  const consentForm_1 = require("./models/consentForm");
20
20
  const consentResponse_1 = require("./models/consentResponse");
21
+ const openApiBuilder_1 = require("./openApiBuilder");
21
22
  const permissions_1 = require("./permissions");
23
+ const populate_1 = require("./populate");
22
24
  const utils_1 = require("./utils");
23
25
  const zodOpenApi_1 = require("./zodOpenApi");
24
26
  /** Shared populate config for consent response list/read endpoints. */
@@ -36,6 +38,59 @@ exports.consentResponsePopulatePaths = [
36
38
  path: "provisionalSignedBy",
37
39
  },
38
40
  ];
41
+ /** A consent document as `toJSON` serializes it: model fields plus the `id` virtual. */
42
+ const consentDocumentOpenApiSchema = (model) => {
43
+ const { properties, required } = (0, populate_1.getOpenApiSpecForModel)(model);
44
+ return {
45
+ properties: {
46
+ ...properties,
47
+ id: { description: "The document id, the same value as _id", type: "string" },
48
+ },
49
+ required: Array.from(new Set([...required, "_id", "id"])),
50
+ type: "object",
51
+ };
52
+ };
53
+ /** Documentation only: request validation stays off so the handlers behave as before. */
54
+ const buildConsentOpenApi = (openApi) => {
55
+ const noop = (_req, _res, next) => next();
56
+ if (!openApi?.path) {
57
+ return { pending: noop, respond: noop };
58
+ }
59
+ const consentForm = consentDocumentOpenApiSchema(consentForm_1.ConsentForm);
60
+ const consentResponse = consentDocumentOpenApiSchema(consentResponse_1.ConsentResponse);
61
+ return {
62
+ pending: (0, openApiBuilder_1.createOpenApiBuilder)({ openApi })
63
+ .withTags(["consents"])
64
+ .withSummary("List active consent forms the current user still has to answer")
65
+ .withResponse(200, { data: { items: consentForm, type: "array" } }, { required: ["data"] })
66
+ .withValidation({ enabled: false })
67
+ .build(),
68
+ respond: (0, openApiBuilder_1.createOpenApiBuilder)({ openApi })
69
+ .withTags(["consents"])
70
+ .withSummary("Submit the current user's response to a consent form")
71
+ .withRequestBody({
72
+ agreed: { description: "Whether the user agreed", required: true, type: "boolean" },
73
+ checkboxValues: {
74
+ additionalProperties: { type: "boolean" },
75
+ description: "Checkbox index (as a string) to whether it was checked",
76
+ type: "object",
77
+ },
78
+ consentFormId: {
79
+ description: "The consent form being answered",
80
+ required: true,
81
+ type: "string",
82
+ },
83
+ locale: { description: "Locale the form was shown in", required: true, type: "string" },
84
+ signature: {
85
+ description: "Signature image data, required when the form captures a signature",
86
+ type: "string",
87
+ },
88
+ })
89
+ .withResponse(200, { data: consentResponse }, { required: ["data"] })
90
+ .withValidation({ enabled: false })
91
+ .build(),
92
+ };
93
+ };
39
94
  const PROVISIONAL_NOTE_MAX_LENGTH = 2000;
40
95
  const provisionalSignBody = zodOpenApi_1.z
41
96
  .object({
@@ -262,6 +317,7 @@ class ConsentApp {
262
317
  }
263
318
  register(app, openApi) {
264
319
  const { accessControl, auditTrail, resolveConsentForms, aiConfig } = this.options;
320
+ const consentOpenApi = buildConsentOpenApi(openApi);
265
321
  if (!accessControl) {
266
322
  logger_1.logger.warn("ConsentApp registered without accessControl; only admins may sign consent on behalf of other users");
267
323
  }
@@ -539,7 +595,7 @@ class ConsentApp {
539
595
  // User-facing consent endpoints
540
596
  const router = (0, express_1.Router)();
541
597
  // GET /consents/pending - fetch pending consent forms for the current user
542
- router.get("/pending", (0, auth_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(async (req, res) => {
598
+ router.get("/pending", (0, auth_1.authenticateMiddleware)(), consentOpenApi.pending, (0, api_1.asyncHandler)(async (req, res) => {
543
599
  const user = req.user;
544
600
  if (!user) {
545
601
  throw new errors_1.APIError({ status: 401, title: "Authentication required" });
@@ -607,7 +663,7 @@ class ConsentApp {
607
663
  return res.json({ data: pendingData });
608
664
  }));
609
665
  // POST /consents/respond - submit a consent response
610
- router.post("/respond", (0, auth_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(async (req, res) => {
666
+ router.post("/respond", (0, auth_1.authenticateMiddleware)(), consentOpenApi.respond, (0, api_1.asyncHandler)(async (req, res) => {
611
667
  const user = req.user;
612
668
  if (!user) {
613
669
  throw new errors_1.APIError({ status: 401, title: "Authentication required" });
package/dist/index.d.ts CHANGED
@@ -44,10 +44,11 @@ export type { MCPCustomTool } from "./mcp/registry";
44
44
  export { clearMCPRegistry, getMCPRegistry, registerMCPModel, registerMCPTool, updateMCPRegistryOptions, } from "./mcp/registry";
45
45
  export { generateInputSchema, generateToolDescription } from "./mcp/schemaGenerator";
46
46
  export { type MCPServerOptions, mountMCPServer } from "./mcp/server";
47
- export { addMcpServiceTokenRoutes, MAX_ACTIVE_MCP_SERVICE_TOKENS, type McpServiceTokenRoutesOptions, type McpServiceTokensAppOption, resolveMcpServiceTokensOption, } from "./mcp/serviceTokens";
47
+ export { addMcpServiceTokenRoutes, createMcpServiceTokenRouter, MAX_ACTIVE_MCP_SERVICE_TOKENS, MCP_SERVICE_TOKENS_ROUTE_PATH, MCP_SERVICE_TOKENS_SYNC_COLLECTION, type McpServiceTokenRoutesOptions, type McpServiceTokensAppOption, resolveMcpServiceTokensOption, toPublicMcpServiceToken, } from "./mcp/serviceTokens";
48
48
  export { generateAllTools, generateToolsForEntry, getAllMCPTools, type MCPToolDefinition, } from "./mcp/toolGenerator";
49
49
  export type { MCPConfig, MCPMethod, MCPRegistryEntry, MCPRequest, MCPToolArgs, MCPToolResult, } from "./mcp/types";
50
50
  export * from "./middleware";
51
+ export * from "./migrations/builtin/mcpServiceTokenStringIds";
51
52
  export * from "./migrations/generate";
52
53
  export * from "./migrations/load";
53
54
  export * from "./migrations/lock";
@@ -106,13 +107,11 @@ export * from "./rbac/userPlugin";
106
107
  export { assertCanWriteTargetUser, assertCanWriteUserIdentity, isRbacUserModelName, isWriteKeyForField, USER_IDENTITY_FIELDS, USER_UPDATE_IDENTITY_ACTION, } from "./rbac/userWriteGuards";
107
108
  export { type AuthorizedEmitEntry, emitPayloadToAuthorizedRoom, emitSyncDeltaForChange, startChangeStreamWatcher, stopChangeStreamWatcher, } from "./realtime/changeStreamWatcher";
108
109
  export { matchesQuery } from "./realtime/queryMatcher";
109
- export { addQuerySubscription, clearQueryStore, computeQueryId, getQuerySubscriptionsForCollection, removeAllSocketQueries, removeQuerySubscription, } from "./realtime/queryStore";
110
- export { installRealtimeSocketHandlers, MAX_DOCUMENT_SUBSCRIPTIONS, MAX_MODEL_SUBSCRIPTIONS, MAX_QUERY_SUBSCRIPTIONS, RealtimeApp, type RealtimeSocketLike, } from "./realtime/realtimeApp";
111
- export { clearRealtimeRegistry, findRegistryEntryByCollection, findRegistryEntryByRoutePath, getRealtimeRegistry, type RealtimeRegistryEntry, registerRealtime, updateRealtimeRegistryOptions, } from "./realtime/registry";
110
+ export { installRealtimeSocketHandlers, RealtimeApp, type RealtimeSocketLike, } from "./realtime/realtimeApp";
112
111
  export { DEFAULT_SESSION_REVALIDATION_INTERVAL_MS, loadFullUserForSocket, type RevalidatableSocket, type RevalidationOutcome, reresolveSyncRoomsForSocket, revalidateSocketSession, runSessionRevalidationSweep, type SessionRevalidationHandle, type SessionRevalidationOptions, startSessionRevalidationSweep, } from "./realtime/sessionRevalidation";
113
112
  export { type AuthenticatableSocket, type BetterAuthSocketOptions, createBetterAuthValidator, createLegacyJwtValidator, createSocketAuthMiddleware, type SocketAuthValidator, } from "./realtime/socketAuth";
114
113
  export { type DecodedRealtimeToken, getSocketUser, type SocketDataBag, type SocketWithDecodedToken, } from "./realtime/socketUser";
115
- export type { ChangeStreamConfig, DocumentSubscription, QuerySubscription, RealtimeAppOptions, RealtimeConfig, RealtimeEvent, } from "./realtime/types";
114
+ export type { ChangeStreamConfig, RealtimeAppOptions } from "./realtime/types";
116
115
  export * from "./requestContext";
117
116
  export { type DescribeModelForRouterOptions, type DescribeModelOptions, describeModel, describeModelForRouter, type FieldDescription, type FieldKind, fieldDescriptionToAdminMeta, fieldDescriptionToOpenApiProperty, fieldDescriptionToZodType, type ModelDescription, modelDescriptionToAdminFields, modelDescriptionToOpenApiSpec, nestDottedFieldDescriptions, SYSTEM_FIELD_PATHS, } from "./schemaMetadata";
118
117
  export * from "./scriptRunner";