@terreno/api 57.20.0 → 58.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
@@ -8,11 +8,19 @@ const node_crypto_1 = require("node:crypto");
8
8
  const luxon_1 = require("luxon");
9
9
  const mongoose_1 = __importDefault(require("mongoose"));
10
10
  const plugins_1 = require("../plugins");
11
+ const syncSeqPlugin_1 = require("../sync/syncSeqPlugin");
11
12
  exports.MCP_SERVICE_TOKEN_PREFIX = "mcp_";
12
13
  const MCP_SERVICE_TOKEN_RANDOM_BYTES = 32;
13
14
  const MCP_SERVICE_TOKEN_DISPLAY_LENGTH = 8;
14
15
  const hashToken = (token) => (0, node_crypto_1.createHash)("sha256").update(token).digest("hex");
15
16
  const mcpServiceTokenSchema = new mongoose_1.default.Schema({
17
+ _id: {
18
+ // Synced collections use String ids. New rows get a UUID; rows created before
19
+ // Terreno 58 keep their ObjectId hex after the mcp-service-token-string-ids migration.
20
+ default: () => (0, node_crypto_1.randomUUID)(),
21
+ description: "The MCP service token id (String so the synced collection can address it)",
22
+ type: String,
23
+ },
16
24
  expiresAt: {
17
25
  description: "When this MCP service token expires; unset when it does not expire",
18
26
  type: Date,
@@ -57,8 +65,23 @@ const mcpServiceTokenSchema = new mongoose_1.default.Schema({
57
65
  mcpServiceTokenSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
58
66
  mcpServiceTokenSchema.index({ revokedAt: 1, userId: 1 });
59
67
  mcpServiceTokenSchema.plugin(plugins_1.createdUpdatedPlugin);
68
+ mcpServiceTokenSchema.plugin(plugins_1.isDeletedPlugin);
60
69
  mcpServiceTokenSchema.plugin(plugins_1.findOneOrNone);
61
70
  mcpServiceTokenSchema.plugin(plugins_1.findExactlyOne);
71
+ // Deleting a token means revoking it: the row stays visible to its owner (and the audit
72
+ // trail) with `revokedAt` set. A soft delete (admin DELETE through modelRouter sets
73
+ // `deleted: true`) is turned into a revoke so it never tombstones the owner's synced row.
74
+ mcpServiceTokenSchema.pre("save", function () {
75
+ if (!this.isModified("deleted") || this.deleted !== true) {
76
+ return;
77
+ }
78
+ this.deleted = false;
79
+ if (!this.revokedAt) {
80
+ this.revokedAt = luxon_1.DateTime.now().toJSDate();
81
+ }
82
+ });
83
+ // Stamps a per-stream _syncSeq on every write; required by the /mcp/service-tokens sync config.
84
+ mcpServiceTokenSchema.plugin(syncSeqPlugin_1.syncPlugin);
62
85
  const revokeInsteadOfDelete = async (doc) => {
63
86
  if (!doc) {
64
87
  return null;
@@ -76,6 +99,9 @@ mcpServiceTokenSchema.methods = {
76
99
  return revoked ?? this;
77
100
  },
78
101
  };
102
+ // Query deleteOne revokes instead of removing the row. Registered after syncPlugin so that,
103
+ // once the collection is synced, syncPlugin's hard-delete guard rejects the call before any
104
+ // write happens.
79
105
  mcpServiceTokenSchema.pre("deleteOne", { document: false, query: true }, async function () {
80
106
  const existing = await (0, plugins_1.findOneOrNoneFor)(this.model, this.getFilter());
81
107
  await revokeInsteadOfDelete(existing);
@@ -103,9 +129,13 @@ mcpServiceTokenSchema.statics = {
103
129
  });
104
130
  return { mcpServiceToken, token };
105
131
  },
132
+ async revokeAllForUser(userId) {
133
+ const result = await this.updateMany({ revokedAt: { $exists: false }, userId: new mongoose_1.default.Types.ObjectId(String(userId)) }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
134
+ return result.modifiedCount;
135
+ },
106
136
  async revokeForUser(user, tokenId) {
107
137
  return this.findOneAndUpdate({
108
- _id: tokenId,
138
+ _id: String(tokenId),
109
139
  revokedAt: { $exists: false },
110
140
  userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
111
141
  }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } }, { returnDocument: "after" });
@@ -116,11 +146,17 @@ mcpServiceTokenSchema.statics = {
116
146
  */
117
147
  async revokeOutdatedForUser(user) {
118
148
  const currentEpoch = user.tokenEpoch ?? 0;
119
- await this.updateMany({
149
+ const userId = new mongoose_1.default.Types.ObjectId(String(user._id));
150
+ const outdated = await this.find({
120
151
  revokedAt: { $exists: false },
121
152
  tokenEpoch: { $nin: currentEpoch === 0 ? [0, null] : [currentEpoch] },
122
- userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
123
- }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
153
+ userId,
154
+ });
155
+ const revokedAt = luxon_1.DateTime.now().toJSDate();
156
+ for (const token of outdated) {
157
+ token.revokedAt = revokedAt;
158
+ await token.save();
159
+ }
124
160
  },
125
161
  async verify(token) {
126
162
  const now = luxon_1.DateTime.now().toJSDate();
@@ -0,0 +1,2 @@
1
+ import type { McpToolSettingModel } from "../types/mcpAdmin";
2
+ export declare const McpToolSetting: McpToolSettingModel;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpToolSetting = void 0;
7
+ const luxon_1 = require("luxon");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const logger_1 = require("../logger");
10
+ const plugins_1 = require("../plugins");
11
+ /**
12
+ * Registry of MCP tools with an admin on/off switch. Rows are written when the server mounts
13
+ * with `mcpToolSettings` on. A tool with no row, or with `enabled: true`, is served.
14
+ */
15
+ const mcpToolSettingSchema = new mongoose_1.default.Schema({
16
+ description: {
17
+ description: "Tool description as sent to MCP clients",
18
+ type: String,
19
+ },
20
+ enabled: {
21
+ default: true,
22
+ description: "When false, the tool is hidden from tools/list and tools/call rejects it",
23
+ type: Boolean,
24
+ },
25
+ lastRegisteredAt: {
26
+ description: "Last server start that registered this tool",
27
+ type: Date,
28
+ },
29
+ name: {
30
+ description: "MCP tool name",
31
+ required: true,
32
+ type: String,
33
+ unique: true,
34
+ },
35
+ registered: {
36
+ default: true,
37
+ description: "False when the running server no longer registers this tool",
38
+ type: Boolean,
39
+ },
40
+ source: {
41
+ description: "model (generated from a modelRouter) or custom (registerMCPTool)",
42
+ enum: ["model", "custom"],
43
+ required: true,
44
+ type: String,
45
+ },
46
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
47
+ /** How long one process reuses the disabled-tool set before reading it again. */
48
+ const DISABLED_NAMES_TTL_MS = 5000;
49
+ // Per-process cache so /mcp does not query Mongo on every request. Writes through this model
50
+ // clear it at once; other processes pick up a change within DISABLED_NAMES_TTL_MS.
51
+ const disabledNamesCache = { expiresAt: 0 };
52
+ const clearDisabledNamesCache = () => {
53
+ disabledNamesCache.expiresAt = 0;
54
+ disabledNamesCache.names = undefined;
55
+ };
56
+ for (const hook of [
57
+ "save",
58
+ "updateOne",
59
+ "updateMany",
60
+ "findOneAndUpdate",
61
+ "deleteOne",
62
+ "deleteMany",
63
+ "findOneAndDelete",
64
+ ]) {
65
+ mcpToolSettingSchema.post(hook, clearDisabledNamesCache);
66
+ }
67
+ mcpToolSettingSchema.post("bulkWrite", clearDisabledNamesCache);
68
+ mcpToolSettingSchema.plugin(plugins_1.createdUpdatedPlugin);
69
+ mcpToolSettingSchema.plugin(plugins_1.findOneOrNone);
70
+ mcpToolSettingSchema.plugin(plugins_1.findExactlyOne);
71
+ mcpToolSettingSchema.statics = {
72
+ ...mcpToolSettingSchema.statics,
73
+ async disabledNames() {
74
+ const now = luxon_1.DateTime.now().toMillis();
75
+ if (disabledNamesCache.names && now < disabledNamesCache.expiresAt) {
76
+ return disabledNamesCache.names;
77
+ }
78
+ try {
79
+ const rows = await this.find({ enabled: false }).select({ name: 1 }).lean();
80
+ const names = new Set(rows.map((row) => row.name));
81
+ disabledNamesCache.names = names;
82
+ disabledNamesCache.expiresAt = now + DISABLED_NAMES_TTL_MS;
83
+ return names;
84
+ }
85
+ catch (error) {
86
+ // Keep enforcing the last known switches rather than re-enabling every tool. With no
87
+ // known state, fail the request (closed) instead of serving tools an admin turned off.
88
+ if (disabledNamesCache.names) {
89
+ logger_1.logger.warn(`[mcp] Tool settings read failed; using last known: ${String(error)}`);
90
+ return disabledNamesCache.names;
91
+ }
92
+ throw error;
93
+ }
94
+ },
95
+ async syncRegistered(tools) {
96
+ const now = luxon_1.DateTime.now().toJSDate();
97
+ if (tools.length > 0) {
98
+ // `enabled` is only set on insert so a restart never undoes an admin's switch.
99
+ await this.bulkWrite(tools.map((tool) => ({
100
+ updateOne: {
101
+ filter: { name: tool.name },
102
+ update: {
103
+ $set: {
104
+ description: tool.description,
105
+ lastRegisteredAt: now,
106
+ registered: true,
107
+ source: tool.source,
108
+ },
109
+ $setOnInsert: { enabled: true },
110
+ },
111
+ upsert: true,
112
+ },
113
+ })));
114
+ }
115
+ await this.updateMany({ name: { $nin: tools.map((tool) => tool.name) }, registered: { $ne: false } }, { $set: { registered: false } });
116
+ },
117
+ };
118
+ exports.McpToolSetting = mongoose_1.default.models.TerrenoMcpToolSetting ??
119
+ mongoose_1.default.model("TerrenoMcpToolSetting", mcpToolSettingSchema, "mcptoolsettings");
@@ -10,6 +10,8 @@ export interface VersionConfigDocument extends mongoose.Document {
10
10
  updateUrl?: string;
11
11
  /** How often clients should poll for version updates, in minutes. Defaults to 1440 (24 hours). */
12
12
  pollingIntervalMinutes: number;
13
+ /** Singleton sentinel backing the unique index; not selected by default. */
14
+ _singleton?: "config";
13
15
  created?: Date;
14
16
  updated?: Date;
15
17
  }
@@ -80,6 +80,8 @@ export interface OpenApiSchemaProperty {
80
80
  items?: OpenApiSchemaProperty;
81
81
  /** Minimum array length when type is "array". */
82
82
  minItems?: number;
83
+ /** OpenAPI 3.0 flag: the value may also be `null`. */
84
+ nullable?: boolean;
83
85
  /** Nested properties when type is "object" */
84
86
  properties?: Record<string, OpenApiSchemaProperty>;
85
87
  /** Schema for additional properties or boolean to allow/disallow them */
@@ -355,6 +357,7 @@ export declare class OpenApiMiddlewareBuilder {
355
357
  * @param options - Optional configuration for the response
356
358
  * @param options.description - Description of the response (default: "Success")
357
359
  * @param options.mediaType - Media type for the response (default: "application/json")
360
+ * @param options.required - Top-level property names that are always present (e.g. `["data"]`)
358
361
  * @returns The builder instance for chaining
359
362
  *
360
363
  * @example
@@ -373,6 +376,7 @@ export declare class OpenApiMiddlewareBuilder {
373
376
  } | string, options?: {
374
377
  description?: string;
375
378
  mediaType?: string;
379
+ required?: string[];
376
380
  }): this;
377
381
  /**
378
382
  * Adds an array response definition to the OpenAPI operation.
@@ -227,6 +227,7 @@ class OpenApiMiddlewareBuilder {
227
227
  * @param options - Optional configuration for the response
228
228
  * @param options.description - Description of the response (default: "Success")
229
229
  * @param options.mediaType - Media type for the response (default: "application/json")
230
+ * @param options.required - Top-level property names that are always present (e.g. `["data"]`)
230
231
  * @returns The builder instance for chaining
231
232
  *
232
233
  * @example
@@ -252,6 +253,7 @@ class OpenApiMiddlewareBuilder {
252
253
  [options?.mediaType ?? "application/json"]: {
253
254
  schema: {
254
255
  properties: schema,
256
+ ...(options?.required?.length ? { required: options.required } : {}),
255
257
  type: "object",
256
258
  },
257
259
  },
@@ -1,4 +1,5 @@
1
1
  import mongoose from "mongoose";
2
+ import { type FindExactlyOnePlugin, type FindOneOrNonePlugin } from "../plugins";
2
3
  import type { PermissionSet } from "./statements";
3
4
  export interface RbacAuditDocument {
4
5
  _id: mongoose.Types.ObjectId;
@@ -14,7 +15,7 @@ export interface RbacAuditDocument {
14
15
  created: Date;
15
16
  updated: Date;
16
17
  }
17
- export type RbacAuditModel = mongoose.Model<RbacAuditDocument>;
18
+ export type RbacAuditModel = mongoose.Model<RbacAuditDocument> & FindExactlyOnePlugin<RbacAuditDocument> & FindOneOrNonePlugin<RbacAuditDocument>;
18
19
  export declare const createRbacAuditModel: (connection: mongoose.Connection) => RbacAuditModel;
19
20
  export interface RbacAuditWrite {
20
21
  action: string;
@@ -1,4 +1,3 @@
1
- import type { RESTMethod } from "../api";
2
1
  import type { User } from "../auth";
3
2
  import { type PermissionMethod } from "../permissions";
4
3
  import type { AnyTerrenoAccess, ModelRouterAccessOptions } from "./types";
@@ -8,11 +7,13 @@ interface RealtimeAccessEntry {
8
7
  accessControl?: AnyTerrenoAccess;
9
8
  permissions?: {
10
9
  read?: PermissionMethod<unknown>[];
11
- list?: PermissionMethod<unknown>[];
12
10
  };
13
11
  };
14
12
  }
15
- export declare const canSubscribeRealtime: (entry: RealtimeAccessEntry, method: "list" | "read", user?: User) => Promise<boolean>;
13
+ /**
14
+ * Socket-side read check for one document, used before emitting `sync:delta` to each
15
+ * socket in a sync stream room. Uses RBAC (`access` + `accessControl`, including
16
+ * `access.scope.check`) when configured, else the router's `permissions.read`.
17
+ */
16
18
  export declare const canReadDocumentRealtime: (entry: RealtimeAccessEntry, user?: User, doc?: Record<string, unknown>) => Promise<boolean>;
17
- export declare const maskRealtimeDocument: (entry: RealtimeAccessEntry, user: User | undefined, doc: unknown, _method: RESTMethod) => Promise<unknown>;
18
19
  export {};
@@ -1,31 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.maskRealtimeDocument = exports.canReadDocumentRealtime = exports.canSubscribeRealtime = void 0;
3
+ exports.canReadDocumentRealtime = void 0;
4
4
  const permissions_1 = require("../permissions");
5
- const fieldViews_1 = require("./fieldViews");
6
- const DEFAULT_METHOD_ACTIONS = {
7
- list: "list",
8
- read: "read",
9
- };
10
- const resolveActionForMethod = (method, access, statements) => {
11
- const override = access.actions?.[method];
12
- if (override === null) {
13
- return null;
14
- }
15
- if (override) {
16
- return override;
17
- }
18
- const resourceActions = statements[access.resource] ?? [];
19
- if (method === "list" && resourceActions.includes("list")) {
20
- return "list";
21
- }
22
- if (method === "list") {
23
- return "read";
24
- }
25
- return DEFAULT_METHOD_ACTIONS[method];
26
- };
27
- // REST and snapshot permissions append access.also[method] to the RBAC role and scope checks
28
- // (buildAccessPermissions), so realtime decisions must apply them too.
5
+ /**
6
+ * REST `access.also[method]` still applies to socket document reads. An empty list allows
7
+ * the read; any listed permission must pass.
8
+ */
29
9
  const checkAlsoPermissions = async (access, method, user, doc) => {
30
10
  const also = access.also?.[method] ?? [];
31
11
  if (also.length === 0) {
@@ -33,35 +13,24 @@ const checkAlsoPermissions = async (access, method, user, doc) => {
33
13
  }
34
14
  return (0, permissions_1.checkPermissions)(method, also, user, doc);
35
15
  };
36
- const canSubscribeRealtime = async (entry, method, user) => {
37
- const access = entry.options.access;
38
- const accessControl = entry.options.accessControl;
39
- if (access && accessControl) {
40
- const statements = accessControl.statements;
41
- const action = resolveActionForMethod(method, access, statements);
42
- if (!action) {
43
- return false;
44
- }
45
- const result = await accessControl.can({
46
- context: { transport: "socket" },
47
- permissions: { [access.resource]: [action] },
48
- user,
49
- });
50
- if (!result.allowed) {
51
- return false;
52
- }
53
- return checkAlsoPermissions(access, method, user);
16
+ /** The RBAC action for socket document reads: the router's `read` override, else `read`. */
17
+ const resolveReadAction = (access) => {
18
+ const override = access.actions?.read;
19
+ if (override === null) {
20
+ return null;
54
21
  }
55
- const permissions = entry.options.permissions?.[method] ?? [];
56
- return (0, permissions_1.checkPermissions)(method, permissions, user);
22
+ return override ?? "read";
57
23
  };
58
- exports.canSubscribeRealtime = canSubscribeRealtime;
24
+ /**
25
+ * Socket-side read check for one document, used before emitting `sync:delta` to each
26
+ * socket in a sync stream room. Uses RBAC (`access` + `accessControl`, including
27
+ * `access.scope.check`) when configured, else the router's `permissions.read`.
28
+ */
59
29
  const canReadDocumentRealtime = async (entry, user, doc) => {
60
30
  const access = entry.options.access;
61
31
  const accessControl = entry.options.accessControl;
62
32
  if (access && accessControl) {
63
- const statements = accessControl.statements;
64
- const action = resolveActionForMethod("read", access, statements);
33
+ const action = resolveReadAction(access);
65
34
  if (!action) {
66
35
  return false;
67
36
  }
@@ -103,19 +72,3 @@ const canReadDocumentRealtime = async (entry, user, doc) => {
103
72
  return (0, permissions_1.checkPermissions)("read", entry.options.permissions?.read ?? [], user, doc);
104
73
  };
105
74
  exports.canReadDocumentRealtime = canReadDocumentRealtime;
106
- const maskRealtimeDocument = async (entry, user, doc, _method) => {
107
- const access = entry.options.access;
108
- const accessControl = entry.options.accessControl;
109
- if (!access || !accessControl) {
110
- return doc;
111
- }
112
- const phase = "read";
113
- const mask = await accessControl.fieldMask({
114
- doc,
115
- phase,
116
- resource: access.resource,
117
- user,
118
- });
119
- return (0, fieldViews_1.applyReadMask)(doc, mask);
120
- };
121
- exports.maskRealtimeDocument = maskRealtimeDocument;
@@ -3,8 +3,7 @@ import type { Server } from "socket.io";
3
3
  import type { User } from "../auth";
4
4
  import type { PermissionMethod } from "../permissions";
5
5
  import { type SyncRegistryEntry } from "../sync/registry";
6
- import { type RealtimeRegistryEntry } from "./registry";
7
- import type { ChangeStreamConfig, RealtimeEvent } from "./types";
6
+ import type { ChangeStreamConfig } from "./types";
8
7
  /**
9
8
  * The subset of ChangeStreamDocument variants this watcher actually processes.
10
9
  * The pipeline filters for ["insert", "update", "replace", "delete"], so we never
@@ -31,20 +30,15 @@ export declare const DEFAULT_IGNORED_COLLECTIONS: string[];
31
30
  /**
32
31
  * Map MongoDB change stream operation types to our method names.
33
32
  *
34
- * Soft deletes (an `update` that sets `deleted: true`) are reclassified as
35
- * `"delete"` only when the model has `"delete"` enabled in its realtime
36
- * methods. Otherwise they fall back to `"update"` so models that subscribe
37
- * to updates (but not deletes) still see the change — without this fallback,
38
- * a model configured with `methods: ["create", "update"]` would silently
39
- * drop soft-delete events.
33
+ * Soft deletes (an `update` that sets `deleted: true`) are reclassified as `"delete"`.
40
34
  *
41
35
  * Exported for testing.
42
36
  */
43
37
  /** @internal */
44
- export declare const mapOperationType: (operationType: string, change: ChangeStreamDocument, enabledMethods?: ReadonlyArray<"create" | "update" | "delete">) => "create" | "update" | "delete" | null;
38
+ export declare const mapOperationType: (operationType: string, change: ChangeStreamDocument) => "create" | "update" | "delete" | null;
45
39
  /**
46
- * The minimal registry-entry shape the authorized-room emitters need. Both
47
- * `RealtimeRegistryEntry` and `SyncRegistryEntry` satisfy it structurally.
40
+ * The minimal registry-entry shape the authorized-room emitter needs.
41
+ * `SyncRegistryEntry` satisfies it structurally.
48
42
  */
49
43
  export interface AuthorizedEmitEntry {
50
44
  collectionTag?: string;
@@ -56,43 +50,18 @@ export interface AuthorizedEmitEntry {
56
50
  };
57
51
  routePath?: string;
58
52
  }
59
- /**
60
- * Determine which Socket.io rooms to emit to based on the room strategy.
61
- * Exported for testing.
62
- */
63
- /** @internal */
64
- export declare const resolveRooms: (entry: RealtimeRegistryEntry, doc: Record<string, unknown>, method: string) => string[];
65
53
  /**
66
54
  * Ensure serialized documents include `id` to match REST API responses.
67
55
  * Change stream fullDocument payloads are raw BSON objects with `_id` only.
68
56
  */
69
57
  /** @internal */
70
58
  export declare const ensureApiId: (data: unknown) => unknown;
71
- /**
72
- * Serialize a document for emission.
73
- *
74
- * Precedence:
75
- * 1. `realtimeResponseHandler` if provided (full control over what's emitted).
76
- * 2. modelRouter `responseHandler` if provided — invoked with a synthetic request
77
- * so the same stripping logic used for REST responses (e.g. removing `hash`/`salt`)
78
- * applies to realtime events. This prevents accidental leaks when an app only
79
- * configures sanitization in the REST `responseHandler`.
80
- * 3. `toJSON()` fallback.
81
- *
82
- * If a user-supplied handler throws, we re-throw so the caller's outer try/catch
83
- * records the failure and the event is dropped. Falling back to `toJSON()` here
84
- * would risk leaking unsanitized fields (e.g. `hash`/`salt`) that the handler
85
- * was supposed to strip.
86
- */
87
- /** @internal */
88
- export declare const serializeDoc: (entry: RealtimeRegistryEntry, doc: Record<string, unknown>, method: "create" | "update" | "delete", user?: User) => Promise<unknown>;
89
59
  /**
90
60
  * Generalized authorized-room emitter: iterates the sockets in `room`, runs the per-socket
91
61
  * read-permission check against `fullDocument`, builds the payload per socket (so
92
62
  * responseHandlers can tailor output to the receiving user), and emits `eventName`.
93
63
  *
94
- * `emitToAuthorizedRoom` (legacy "sync" events) and the sync layer's `sync:delta`
95
- * emission both delegate here.
64
+ * The sync layer's `sync:delta` emission delegates here.
96
65
  */
97
66
  export declare const emitPayloadToAuthorizedRoom: ({ io, room, eventName, entry, fullDocument, buildPayload, logDebug, }: {
98
67
  io: Server;
@@ -107,32 +76,11 @@ export declare const emitPayloadToAuthorizedRoom: ({ io, room, eventName, entry,
107
76
  buildPayload: (user: User | undefined) => Promise<unknown> | unknown;
108
77
  logDebug: (msg: string) => void;
109
78
  }) => Promise<void>;
110
- /** @internal */
111
- export declare const emitToAuthorizedRoom: (io: Server, room: string, event: RealtimeEvent, entry: RealtimeRegistryEntry, fullDocument: Record<string, unknown> | undefined, logDebug: (msg: string) => void) => Promise<void>;
112
- /**
113
- * Emit a sync event to document-specific and query rooms.
114
- *
115
- * Document rooms: `document:{collection}:{docId}` — clients subscribed to a single document.
116
- * Query rooms: `query:{queryId}` — clients subscribed to a query filter. The change stream
117
- * watcher evaluates whether the document matches each active query for the collection.
118
- *
119
- * For deletes, we are careful not to leak cross-user activity:
120
- * - Soft deletes (fullDocument present) are matched against each query like updates so
121
- * query subscribers only see deletes for docs that matched their filter.
122
- * - Hard deletes (fullDocument absent) on owner-strategy collections are NOT forwarded
123
- * to query rooms — subscribers will reconcile on their next fetch. Other strategies
124
- * forward the delete because the model/broadcast rooms are not user-scoped.
125
- *
126
- * Exported for testing.
127
- */
128
- /** @internal */
129
- export declare const emitToDocumentAndQueryRooms: (io: Server, collection: string, event: RealtimeEvent, fullDocument: Record<string, unknown> | undefined, logDebug: (msg: string) => void, entry?: RealtimeRegistryEntry) => Promise<void>;
130
79
  /**
131
80
  * Emit `sync:delta` events for a change on a sync-registered collection.
132
81
  *
133
82
  * Deltas fan out to the dedicated `sync:{stream}` rooms joined via `sync:subscribe`
134
- * (independent of the legacy realtime rooms), with the same per-socket read-permission
135
- * checks as legacy events. `seq` and `stream` come from the post-image: the `syncPlugin`
83
+ * with per-socket read-permission checks. `seq` and `stream` come from the post-image: the `syncPlugin`
136
84
  * stamps `_syncSeq` on every synced write and the watcher runs `updateLookup`.
137
85
  *
138
86
  * Soft deletes (an update setting `deleted: true`, reclassified by `mapOperationType`)
@@ -151,9 +99,6 @@ export declare const emitToDocumentAndQueryRooms: (io: Server, collection: strin
151
99
  * emit time, C1); the client advances its cursor to `min(delta.seq, delta.frontierSeq)`
152
100
  * so a delta observed out of commit order never advances a cursor past an uncommitted hole.
153
101
  *
154
- * A model with both `realtime` and `sync` configs emits both the legacy "sync" event and
155
- * "sync:delta" — distinct event names, no interference (documented as transitional).
156
- *
157
102
  * Exported for testing.
158
103
  */
159
104
  export declare const emitSyncDeltaForChange: ({ io, entry, change, docId, logDebug, }: {
@@ -164,7 +109,7 @@ export declare const emitSyncDeltaForChange: ({ io, entry, change, docId, logDeb
164
109
  logDebug: (msg: string) => void;
165
110
  }) => Promise<void>;
166
111
  /**
167
- * Start watching MongoDB change streams and emitting real-time events.
112
+ * Start watching MongoDB change streams and emitting `sync:delta` events.
168
113
  *
169
114
  * Task 9.16: the stream is supervised — an `error`/`close`/`end` schedules a re-open with
170
115
  * exponential backoff, resuming from the last seen token. Call