@sfxcode/mongocamp-server-core 2.4.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.mts +247 -121
  2. package/dist/index.mjs +866 -235
  3. package/package.json +8 -2
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { MongoError, MongoServerError, MongoBulkWriteError, MongoNetworkError, M
3
3
  import { Cron } from 'croner';
4
4
  import { randomBytes, timingSafeEqual, createHash, scrypt, randomUUID, createHmac } from 'node:crypto';
5
5
  import { createHooks } from 'hookable';
6
- import { createRouter, addRoute, findRoute } from 'rou3';
6
+ import { findRoute, createRouter, addRoute } from 'rou3';
7
7
  import { Readable } from 'node:stream';
8
8
  import { pipeline } from 'node:stream/promises';
9
9
  import busboy from 'busboy';
@@ -148,6 +148,12 @@ const ErrorCodes = {
148
148
  changeStreamsUnsupported: 5011,
149
149
  unauthorizedUser: 4011,
150
150
  unauthorizedUserForOtherUser: 4012,
151
+ /** 413 (2.6.0): the body is greater than `BODY_MAX_BYTES`. */
152
+ bodyTooLarge: 4131,
153
+ /** 413 (2.6.0): the uploaded file is greater than `GRIDFS_UPLOAD_MAX_BYTES`. */
154
+ uploadTooLarge: 4132,
155
+ /** 413 (2.6.0): the import is greater than `IMPORT_MAX_BYTES`. */
156
+ importTooLarge: 4133,
151
157
  forbiddenStage: 4031,
152
158
  forbiddenCollectionInStage: 4032,
153
159
  jobAlreadyAdded: 4121,
@@ -424,6 +430,11 @@ class MongocampError extends Error {
424
430
  this.current = current;
425
431
  this.name = "MongocampError";
426
432
  }
433
+ /**
434
+ * 2.6.0: the stored document of a version conflict with the values of the driver (without secrets), so the answer can use the Extended
435
+ * JSON mode of the request (`currentIn`); `current` is relaxed.
436
+ */
437
+ storedDocument;
427
438
  get description() {
428
439
  const description = { code: this.code, msg: this.message, additionalInfo: this.additionalInfo };
429
440
  if (this.issues !== void 0) {
@@ -442,8 +453,12 @@ class MongocampError extends Error {
442
453
  return new MongocampError(message, 400, code, "", issues);
443
454
  }
444
455
  /** 409 for a write based on an outdated version, with the stored document (as Extended JSON) for the client to show or merge. */
445
- static versionConflict(current) {
446
- return new MongocampError("the document was changed in the meantime: read it again (current) and repeat the change", 409, ErrorCodes.versionConflict, "", void 0, current);
456
+ static versionConflict(current, storedDocument) {
457
+ const error = new MongocampError("the document was changed in the meantime: read it again (current) and repeat the change", 409, ErrorCodes.versionConflict, "", void 0, current);
458
+ if (storedDocument !== void 0) {
459
+ error.storedDocument = storedDocument;
460
+ }
461
+ return error;
447
462
  }
448
463
  /** 403 and not 401: a client such as the UI clears its session on 401, but the session is fine, only this request is refused. */
449
464
  static forbidden(message, code = -1) {
@@ -479,10 +494,15 @@ const defaultLogger = (error, status) => {
479
494
  console.error("[mongocamp]", error);
480
495
  }
481
496
  };
482
- function toErrorResponse(error, log = defaultLogger) {
497
+ const InternalErrorMessage = "internal server error, the log of the server has the details (x-request-id)";
498
+ function toErrorResponse(error, log = defaultLogger, options = {}) {
483
499
  const cause = error instanceof HTTPError && error.cause instanceof Error ? error.cause : error;
484
500
  if (cause instanceof MongocampError) {
485
- return errorResponse(cause.status, cause.description);
501
+ const description = cause.description;
502
+ if (cause.storedDocument !== void 0 && options.currentIn !== void 0) {
503
+ description.current = options.currentIn(cause.storedDocument);
504
+ }
505
+ return errorResponse(cause.status, description);
486
506
  }
487
507
  const databaseError = findDatabaseError(cause);
488
508
  if (databaseError) {
@@ -494,7 +514,7 @@ function toErrorResponse(error, log = defaultLogger) {
494
514
  return errorResponse(cause.status, { code: -1, msg: cause.message, additionalInfo: "" });
495
515
  }
496
516
  log(cause, 500);
497
- const message = cause instanceof Error ? cause.message : "Unknown Error";
517
+ const message = !options.exposeInternal ? InternalErrorMessage : cause instanceof Error ? cause.message : "Unknown Error";
498
518
  return errorResponse(500, { code: -1, msg: message, additionalInfo: "" });
499
519
  }
500
520
 
@@ -689,6 +709,7 @@ class JobScheduler {
689
709
  lastScheduledFireTime: entry.lastRun?.toISOString() ?? null,
690
710
  nextScheduledFireTime: next?.toISOString() ?? null,
691
711
  scheduleInformation
712
+ // the spec declares these fields optional, the API answers `null` (as the Scala server did): the generated type has no `null`
692
713
  };
693
714
  }
694
715
  list() {
@@ -878,6 +899,8 @@ const ConfigKeys = {
878
899
  ServerInterface: "SERVER_INTERFACE",
879
900
  ServerPort: "SERVER_PORT",
880
901
  AggregationStagesDenied: "AGGREGATION_STAGES_DENIED",
902
+ // new in 2.5.0: operators that run JavaScript on the database server are refused in the filters, projections and updates of clients
903
+ FilterOperatorsDenied: "FILTER_OPERATORS_DENIED",
881
904
  AuthHandler: "AUTH_HANDLER",
882
905
  AuthSecret: "AUTH_SECRET",
883
906
  AuthApiKeyLength: "AUTH_APIKEYLENGTH",
@@ -887,6 +910,17 @@ const ConfigKeys = {
887
910
  AuthGrantDeniedStatus: "AUTH_GRANT_DENIED_STATUS",
888
911
  ImportMaxBytes: "IMPORT_MAX_BYTES",
889
912
  WatchMaxStreams: "WATCH_MAX_STREAMS",
913
+ // new in 2.5.0: limits of a request (0: no limit); the body limit and the queue of a live update are on by default
914
+ BodyMaxBytes: "BODY_MAX_BYTES",
915
+ PagingMaxRows: "PAGING_MAX_ROWS",
916
+ ExportMaxDocuments: "EXPORT_MAX_DOCUMENTS",
917
+ GridfsUploadMaxBytes: "GRIDFS_UPLOAD_MAX_BYTES",
918
+ WatchQueueMax: "WATCH_QUEUE_MAX",
919
+ // new in 2.5.0: what the answers of the server show (the `server` header, the messages of unexpected errors) and csv formula escaping
920
+ ServerHeaderEnabled: "SERVER_HEADER_ENABLED",
921
+ ErrorsExposeInternal: "ERRORS_EXPOSE_INTERNAL",
922
+ UsersReadHideApiKey: "USERS_READ_HIDE_API_KEY",
923
+ ExportCsvEscapeFormulas: "EXPORT_CSV_ESCAPE_FORMULAS",
890
924
  // new in 2.0.0: the time zone of dates without offset in Lucene filters
891
925
  FilterTimeZone: "FILTER_TIME_ZONE",
892
926
  // new in 2.0.0: drop what the Scala server left in the database at the start (`system/scala-leftovers.ts`)
@@ -948,6 +982,7 @@ const configDefinitions = [
948
982
  define(K.ServerInterface, "String", "0.0.0.0", restart),
949
983
  define(K.ServerPort, "Long", 8080, restart),
950
984
  define(K.AggregationStagesDenied, "List[String]", ["$function", "$accumulator", "$where", "$out", "$merge", "$currentOp", "$listSessions", "$collStats", "$indexStats"]),
985
+ define(K.FilterOperatorsDenied, "List[String]", ["$where", "$function", "$accumulator"]),
951
986
  define(K.AuthHandler, "String", "mongo", restart),
952
987
  // the Scala server registers a random secret (not the `secret_key` of reference.conf); it is persisted, so it survives restarts
953
988
  define(K.AuthSecret, "String", () => randomAlphanumeric$1(32)),
@@ -960,6 +995,16 @@ const configDefinitions = [
960
995
  define(K.ImportMaxBytes, "Long", 1073741824),
961
996
  // 2.3.0: live updates, change streams open at the same time in one instance (each holds a cursor of the database)
962
997
  define(K.WatchMaxStreams, "Long", 100),
998
+ define(K.BodyMaxBytes, "Long", 67108864),
999
+ define(K.PagingMaxRows, "Long", 0),
1000
+ define(K.ExportMaxDocuments, "Long", 0),
1001
+ define(K.GridfsUploadMaxBytes, "Long", 0),
1002
+ define(K.WatchQueueMax, "Long", 1e3),
1003
+ define(K.ServerHeaderEnabled, "Boolean", true),
1004
+ define(K.ErrorsExposeInternal, "Boolean", false),
1005
+ // 2.6.0: the document routes leave out apiKey of the users collection too (default true in 3.0)
1006
+ define(K.UsersReadHideApiKey, "Boolean", false),
1007
+ define(K.ExportCsvEscapeFormulas, "Boolean", false),
963
1008
  define(K.FilterTimeZone, "String", "UTC"),
964
1009
  define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
965
1010
  define(K.JobsEnabled, "Boolean", true, nonPersistent),
@@ -969,7 +1014,7 @@ const configDefinitions = [
969
1014
  define(K.FileHandler, "String", "gridfs", restart),
970
1015
  define(K.FileCacheAge, "String", "7776000"),
971
1016
  define(K.CorsHeadersAllowed, "List[String]", ["Authorization", "Content-Type", "X-Requested-With", "X-AUTH-APIKEY"]),
972
- define(K.CorsHeadersExposed, "List[String]", ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages", "x-pagination-next", "x-request-id"]),
1017
+ define(K.CorsHeadersExposed, "List[String]", ["Content-Type", "x-pagination-rows-per-page", "x-pagination-current-page", "x-pagination-count-rows", "x-pagination-count-pages", "x-pagination-next", "x-request-id", "x-export-max-documents"]),
973
1018
  define(K.CorsOriginsAllowed, "List[String]", ["http://localhost:8080"]),
974
1019
  define(K.DocsSwagger, "Boolean", false, restart),
975
1020
  define(K.DocsOpenApi, "Boolean", true, restart),
@@ -1012,6 +1057,9 @@ function longQuery(params, name) {
1012
1057
  }
1013
1058
  return value;
1014
1059
  }
1060
+ function limitPaging(paging, maxRows) {
1061
+ return maxRows > 0 && (paging.rowsPerPage ?? 0) > maxRows ? { ...paging, rowsPerPage: maxRows } : paging;
1062
+ }
1015
1063
  function readPaging(params) {
1016
1064
  const paging = { rowsPerPage: longQuery(params, "rowsPerPage"), page: longQuery(params, "page") };
1017
1065
  if (params.has("after")) {
@@ -1101,6 +1149,9 @@ async function hashPassword(password) {
1101
1149
  function equalBytes(a, b) {
1102
1150
  return a.length === b.length && timingSafeEqual(a, b);
1103
1151
  }
1152
+ function sameSecret(a, b) {
1153
+ return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
1154
+ }
1104
1155
  async function verifyPassword(password, stored) {
1105
1156
  const hash = parsePasswordHash(stored);
1106
1157
  if (hash.algorithm === "sha256") {
@@ -1324,7 +1375,13 @@ class StaticAuthHolder {
1324
1375
  async upgradePassword() {
1325
1376
  }
1326
1377
  async findUserByApiKeyOption(apiKey) {
1327
- return this.users.find((user) => user.apiKey === apiKey);
1378
+ let found;
1379
+ for (const user of this.users) {
1380
+ if (typeof user.apiKey === "string" && user.apiKey !== "" && sameSecret(user.apiKey, apiKey) && found === void 0) {
1381
+ found = user;
1382
+ }
1383
+ }
1384
+ return found;
1328
1385
  }
1329
1386
  async findRoles(names) {
1330
1387
  return names.flatMap((name) => this.roles.filter((role) => role.name.toLowerCase() === name.toLowerCase()).slice(0, 1));
@@ -1542,7 +1599,6 @@ const BasicAuthCacheMillis = 6e4;
1542
1599
  const BasicAuthCacheEntries = 1e3;
1543
1600
  class AuthService {
1544
1601
  constructor(database, config, version) {
1545
- this.database = database;
1546
1602
  this.config = config;
1547
1603
  this.version = version;
1548
1604
  this.holder = createAuthHolder(database, config);
@@ -1969,6 +2025,7 @@ class ConfigPersistence {
1969
2025
  };
1970
2026
  await this.collection.updateOne({ key: definition.key }, { $setOnInsert: document }, { upsert: true });
1971
2027
  }
2028
+ await this.upgradeLegacyDefaults();
1972
2029
  await this.refresh(true);
1973
2030
  if (refreshMillis !== false) {
1974
2031
  this.timer = setInterval(() => {
@@ -1977,6 +2034,14 @@ class ConfigPersistence {
1977
2034
  this.timer.unref?.();
1978
2035
  }
1979
2036
  }
2037
+ /**
2038
+ * 2.6.0: a database created before 2.2.0 stored the old default 401 of `AUTH_GRANT_DENIED_STATUS` at its first start, and kept answering
2039
+ * 401 for a missing grant. A stored 401 that no update set (no `changedAt`, written since 2.6.0) becomes the default 403 once; an
2040
+ * administrator who wants 401 patches it again (then it is marked and stays).
2041
+ */
2042
+ async upgradeLegacyDefaults() {
2043
+ await this.collection.updateOne({ key: "AUTH_GRANT_DENIED_STATUS", value: 401, changedAt: { $exists: false } }, { $set: { value: 403 } });
2044
+ }
1980
2045
  /** Reads the stored values; at startup also the keys that need a restart, later only the ones that are active at once. */
1981
2046
  async refresh(startup) {
1982
2047
  const documents = await this.collection.find({}).toArray();
@@ -2036,7 +2101,7 @@ class ConfigPersistence {
2036
2101
  }
2037
2102
  const internal = valueForUpdate(definition, value);
2038
2103
  const stored = toStored(definition.type, internal);
2039
- const before = await this.collection.findOneAndUpdate({ key }, { $set: { value: stored } });
2104
+ const before = await this.collection.findOneAndUpdate({ key }, { $set: { value: stored, changedAt: /* @__PURE__ */ new Date() } });
2040
2105
  if (!before) {
2041
2106
  return false;
2042
2107
  }
@@ -2046,6 +2111,24 @@ class ConfigPersistence {
2046
2111
  }
2047
2112
  return true;
2048
2113
  }
2114
+ /**
2115
+ * 2.6.0: the default again (`DELETE /system/configurations/{key}`), at once in this instance for a key that needs no restart. The
2116
+ * reasons it is not possible are answered by the route (unknown, not persistent, set by the environment, a generated default).
2117
+ */
2118
+ async reset(key) {
2119
+ const definition = this.config.definition(key);
2120
+ if (!definition?.persistent || this.config.overrideOf(key) === "env" || typeof definition.defaultValue === "function") {
2121
+ return false;
2122
+ }
2123
+ const internal = definition.defaultValue;
2124
+ const stored = toStored(definition.type, internal);
2125
+ const before = await this.collection.findOneAndUpdate({ key }, { $set: { value: stored, comment: "" }, $unset: { changedAt: "" } }, { upsert: true });
2126
+ this.events?.publish("config:update", { key, newValue: SecretKeys.has(key) ? SecretMask : stored, oldValue: SecretKeys.has(key) ? SecretMask : before?.value ?? null, callingMethod: "resetConfig" });
2127
+ if (!definition.needsRestartForActivation) {
2128
+ this.config.applyPersisted(key, internal);
2129
+ }
2130
+ return true;
2131
+ }
2049
2132
  close() {
2050
2133
  if (this.timer) {
2051
2134
  clearInterval(this.timer);
@@ -2089,6 +2172,10 @@ class MongocampDatabase {
2089
2172
  internalCollectionName(name) {
2090
2173
  return `${this.config.string(ConfigKeys.AuthPrefix)}${name}`;
2091
2174
  }
2175
+ /** `USERS_READ_HIDE_API_KEY` (2.6.0): the document routes leave out `apiKey` of the users collection too. */
2176
+ get hidesUserApiKeys() {
2177
+ return this.config.boolean(ConfigKeys.UsersReadHideApiKey);
2178
+ }
2092
2179
  async close() {
2093
2180
  if (this.ownsClient) {
2094
2181
  await this.client.close();
@@ -2263,8 +2350,9 @@ class WriteInterceptors {
2263
2350
  }
2264
2351
  }
2265
2352
 
2353
+ const { rawJSON } = JSON;
2266
2354
  function rawNumber(text) {
2267
- return JSON.rawJSON(text);
2355
+ return rawJSON(text);
2268
2356
  }
2269
2357
  const maxLong = 9223372036854775807n;
2270
2358
  const minLong = -9223372036854775808n;
@@ -2346,10 +2434,10 @@ function parseJsonBody(text) {
2346
2434
  function stringifyJson(value) {
2347
2435
  return JSON.stringify(value, (_key, entry) => {
2348
2436
  if (typeof entry === "bigint") {
2349
- return JSON.rawJSON(entry.toString());
2437
+ return rawNumber(entry.toString());
2350
2438
  }
2351
2439
  if (entry instanceof Long) {
2352
- return JSON.rawJSON(entry.toString());
2440
+ return rawNumber(entry.toString());
2353
2441
  }
2354
2442
  return entry;
2355
2443
  });
@@ -2995,6 +3083,7 @@ function resolveIndexes(declarations, behaviours) {
2995
3083
  }
2996
3084
  if (indexOptions.unique === true && behaviours.softDelete !== void 0 && indexOptions.partialFilterExpression === void 0) {
2997
3085
  indexOptions.partialFilterExpression = { [behaviours.softDelete.field]: null };
3086
+ return { ...resolved(key, indexOptions, options.name, "declaration"), softDeleteFilter: true };
2998
3087
  }
2999
3088
  return resolved(key, indexOptions, options.name, "declaration");
3000
3089
  });
@@ -3169,7 +3258,16 @@ function resolveRefs(refs, behaviours, jsonSchema) {
3169
3258
  if (throughArray) {
3170
3259
  throw new Error(`refs: ${field} goes through an array, only the last part of a reference may be an array`);
3171
3260
  }
3172
- return { field, collection, ...node !== void 0 ? { many: isArrayNode(node) } : {} };
3261
+ const declaredMany = typeof declaration === "object" && declaration !== null ? declaration.many : void 0;
3262
+ if (declaredMany !== void 0 && typeof declaredMany !== "boolean") {
3263
+ throw new Error(`refs: many of ${field} must be a boolean`);
3264
+ }
3265
+ const schemaMany = node !== void 0 ? isArrayNode(node) : void 0;
3266
+ if (declaredMany !== void 0 && schemaMany !== void 0 && declaredMany !== schemaMany) {
3267
+ throw new Error(`refs: ${field} is declared with many: ${declaredMany}, but the schema says ${schemaMany ? "an array" : "no array"}`);
3268
+ }
3269
+ const many = schemaMany ?? declaredMany;
3270
+ return { field, collection, ...many !== void 0 ? { many } : {} };
3173
3271
  });
3174
3272
  }
3175
3273
 
@@ -3972,11 +4070,15 @@ function idToString(id) {
3972
4070
  }
3973
4071
 
3974
4072
  const SecretUserFields = ["password"];
4073
+ const SecretUserFieldsWithApiKey = ["password", "apiKey"];
3975
4074
  function secretFieldsOf(database, collection) {
3976
4075
  const name = parseCollectionName(collection);
3977
4076
  const defaultDatabase = database.db().databaseName;
3978
4077
  const inDefault = name.database === void 0 || name.database === defaultDatabase;
3979
- return inDefault && name.name === database.internalCollectionName("users") ? SecretUserFields : [];
4078
+ if (!inDefault || name.name !== database.internalCollectionName("users")) {
4079
+ return [];
4080
+ }
4081
+ return database.hidesUserApiKeys ? SecretUserFieldsWithApiKey : SecretUserFields;
3980
4082
  }
3981
4083
  function withoutSecrets(document, fields) {
3982
4084
  if (fields.length === 0 || !fields.some((field) => field in document)) {
@@ -4069,7 +4171,8 @@ function registerVersioned(context, own) {
4069
4171
  const conflictCheck = (collection, filter) => async () => {
4070
4172
  const stored = await collectionOf(context.database, collection).findOne(filter);
4071
4173
  if (stored !== null) {
4072
- throw MongocampError.versionConflict(withoutSecrets(documentToJson(stored), secretFieldsOf(context.database, collection)));
4174
+ const secrets = secretFieldsOf(context.database, collection);
4175
+ throw MongocampError.versionConflict(withoutSecrets(documentToJson(stored), secrets), withoutSecrets(stored, secrets));
4073
4176
  }
4074
4177
  };
4075
4178
  const removers = [
@@ -4359,6 +4462,22 @@ class CollectionRegistry {
4359
4462
  const name = parseCollectionName(collection);
4360
4463
  return this.find(databaseOf(context.database, name).databaseName, name.name);
4361
4464
  }
4465
+ /** The fields of the declared refs of a collection (2.6.0: a Lucene term with an id matches their `ObjectId`); empty without a declaration. */
4466
+ refFields(context, collection) {
4467
+ return this.resolve(context, collection)?.refs.map((ref) => ref.field) ?? [];
4468
+ }
4469
+ /**
4470
+ * The references of the declared collections to a declaration (2.6.0, `referencedBy` of its answer), from the registry (no database
4471
+ * read). `collection` is the name as the routes take it (`database:name` when the declaration names its database).
4472
+ */
4473
+ referencesTo(context, target) {
4474
+ return this.all().flatMap((entry) => entry.refs.filter((ref) => this.resolve(context, ref.collection) === target).map((ref) => ({
4475
+ collection: entry.definition.database !== void 0 ? `${entry.definition.database}${CollectionSeparator}${entry.definition.name}` : entry.definition.name,
4476
+ database: entry.databaseName,
4477
+ field: ref.field,
4478
+ many: ref.many ?? false
4479
+ })));
4480
+ }
4362
4481
  get size() {
4363
4482
  return this.entries.size;
4364
4483
  }
@@ -4692,7 +4811,7 @@ async function readLines(collection, body, maxBytes, state, beforeBatch) {
4692
4811
  }
4693
4812
  bytes += value.byteLength;
4694
4813
  if (bytes > maxBytes) {
4695
- throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
4814
+ throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413, ErrorCodes.importTooLarge);
4696
4815
  }
4697
4816
  pending += decoder.decode(value, { stream: true });
4698
4817
  let newline = pending.indexOf("\n");
@@ -4722,6 +4841,108 @@ async function readLines(collection, body, maxBytes, state, beforeBatch) {
4722
4841
  }
4723
4842
  }
4724
4843
 
4844
+ function normalizeStage(name) {
4845
+ return name.startsWith("$") ? name : `$${name}`;
4846
+ }
4847
+ function refuseIfDenied(operator, denied) {
4848
+ if (denied.has(operator)) {
4849
+ throw MongocampError.forbidden(`the operator ${operator} is not allowed in an aggregation`, ErrorCodes.forbiddenStage);
4850
+ }
4851
+ }
4852
+ function scan(value, denied) {
4853
+ if (Array.isArray(value)) {
4854
+ value.forEach((entry) => scan(entry, denied));
4855
+ } else if (isPlainObject(value)) {
4856
+ for (const [key, entry] of Object.entries(value)) {
4857
+ refuseIfDenied(key, denied);
4858
+ scan(entry, denied);
4859
+ }
4860
+ }
4861
+ }
4862
+ function checkDeniedFilterOperators(values, deniedOperators) {
4863
+ const denied = new Set(deniedOperators.map(normalizeStage));
4864
+ if (denied.size === 0) {
4865
+ return;
4866
+ }
4867
+ const visit = (value) => {
4868
+ if (Array.isArray(value)) {
4869
+ value.forEach(visit);
4870
+ } else if (isPlainObject(value)) {
4871
+ for (const [key, entry] of Object.entries(value)) {
4872
+ if (denied.has(key)) {
4873
+ throw MongocampError.forbidden(`the operator ${key} is not allowed in a filter`, ErrorCodes.forbiddenStage);
4874
+ }
4875
+ visit(entry);
4876
+ }
4877
+ }
4878
+ };
4879
+ values.forEach(visit);
4880
+ }
4881
+ function checkDeniedOperators(pipeline, deniedOperators) {
4882
+ const denied = new Set(deniedOperators.map(normalizeStage));
4883
+ if (denied.size === 0) {
4884
+ return;
4885
+ }
4886
+ for (const stage of pipeline) {
4887
+ refuseIfDenied(normalizeStage(stage.stage), denied);
4888
+ scan(stage.value, denied);
4889
+ }
4890
+ }
4891
+ function referencedCollections(value) {
4892
+ const fromValue = (from) => {
4893
+ if (typeof from === "string") {
4894
+ return [{ name: from }];
4895
+ }
4896
+ if (isPlainObject(from)) {
4897
+ return [{ unsupported: "a reference to a collection of another database" }];
4898
+ }
4899
+ return [];
4900
+ };
4901
+ if (Array.isArray(value)) {
4902
+ return value.flatMap(referencedCollections);
4903
+ }
4904
+ if (!isPlainObject(value)) {
4905
+ return [];
4906
+ }
4907
+ return Object.entries(value).flatMap(([key, entry]) => {
4908
+ let own = [];
4909
+ if ((key === "$lookup" || key === "$graphLookup") && isPlainObject(entry)) {
4910
+ own = fromValue(entry.from);
4911
+ } else if (key === "$unionWith" && typeof entry === "string") {
4912
+ own = [{ name: entry }];
4913
+ } else if (key === "$unionWith" && isPlainObject(entry)) {
4914
+ own = fromValue(entry.coll);
4915
+ }
4916
+ return [...own, ...referencedCollections(entry)];
4917
+ });
4918
+ }
4919
+ function checkPipeline(user, collection, pipeline, deniedOperators) {
4920
+ checkDeniedOperators(pipeline, deniedOperators);
4921
+ const separator = collection.indexOf(":");
4922
+ const prefix = separator >= 0 ? collection.slice(0, separator + 1) : "";
4923
+ for (const stage of pipeline) {
4924
+ for (const reference of referencedCollections({ [normalizeStage(stage.stage)]: stage.value })) {
4925
+ if ("unsupported" in reference) {
4926
+ throw MongocampError.forbidden(`${reference.unsupported} is not supported in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
4927
+ }
4928
+ if (!user.canRead(prefix + reference.name)) {
4929
+ throw MongocampError.forbidden(`the user is not allowed to read the collection ${reference.name} in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
4930
+ }
4931
+ }
4932
+ }
4933
+ }
4934
+ const firstStageOnly = /* @__PURE__ */ new Set(["$geoNear", "$search", "$searchMeta", "$vectorSearch", "$collStats", "$indexStats", "$documents"]);
4935
+ function checkMatchBefore(pipeline) {
4936
+ const first = pipeline[0];
4937
+ if (first && firstStageOnly.has(normalizeStage(first.stage))) {
4938
+ const stage = normalizeStage(first.stage);
4939
+ throw MongocampError.badRequest(`the filter cannot be combined with a pipeline that starts with ${stage}, put the conditions in the stage itself`, ErrorCodes.filterNotSupported);
4940
+ }
4941
+ }
4942
+ function toBsonPipeline(pipeline) {
4943
+ return pipeline.map((stage) => ({ [normalizeStage(stage.stage)]: stage.value }));
4944
+ }
4945
+
4725
4946
  function cursorSort(sort) {
4726
4947
  const keys = Object.entries(sort).map(([field, direction]) => [field, Number(direction) < 0 ? -1 : 1]);
4727
4948
  return keys.some(([field]) => field === "_id") ? keys : [...keys, ["_id", 1]];
@@ -5001,6 +5222,14 @@ class DocumentService {
5001
5222
  }
5002
5223
  }
5003
5224
  /** The filter with the read scope of the caller. */
5225
+ /** The paging of a read with `rowsPerPage` at most `PAGING_MAX_ROWS` (2.5.0, 0: no limit); the page headers show the rows used. */
5226
+ limited(paging) {
5227
+ return limitPaging(paging, this.context.config.number(ConfigKeys.PagingMaxRows));
5228
+ }
5229
+ /** Refuses filters, projections and updates of the caller with an operator of `FILTER_OPERATORS_DENIED` (2.5.0). */
5230
+ checkOperators(...values) {
5231
+ checkDeniedFilterOperators(values, this.context.config.list(ConfigKeys.FilterOperatorsDenied));
5232
+ }
5004
5233
  scope(user, collection, filter, operation, options = {}) {
5005
5234
  return readScope(this.context, user, collection, filter, operation, options);
5006
5235
  }
@@ -5068,14 +5297,16 @@ class DocumentService {
5068
5297
  /** A page of documents (list, find, search), with the references of `options.expand` expanded. */
5069
5298
  async page(user, collection, request, paging, count = "exact", options = {}) {
5070
5299
  this.require(user, collection, "read", options);
5300
+ this.checkOperators(request.filter, request.projection);
5071
5301
  const refs = this.refs(collection, options.expand);
5072
5302
  const filter = await this.scope(user, collection, request.filter, options.operation ?? "list", options);
5073
- const page = await readPage(this.collection(collection), { ...request, filter }, paging, count);
5303
+ const page = await readPage(this.collection(collection), { ...request, filter }, this.limited(paging), count);
5074
5304
  return refs.length > 0 ? { ...page, documents: await this.expand(user, page.documents, refs) } : page;
5075
5305
  }
5076
5306
  /** The number of documents of a filter. */
5077
5307
  async count(user, collection, filter, options = {}) {
5078
5308
  this.require(user, collection, "read", options);
5309
+ this.checkOperators(filter);
5079
5310
  return this.collection(collection).countDocuments(await this.scope(user, collection, filter, "count", options));
5080
5311
  }
5081
5312
  /** One document by the id of the path (any type of id), `null` when it is missing or not in the scope of the caller. */
@@ -5088,6 +5319,7 @@ class DocumentService {
5088
5319
  /** The filter of an export with the scope, and the scope alone (for the column sample of a csv export). */
5089
5320
  async exportFilter(user, collection, filter, options = {}) {
5090
5321
  this.require(user, collection, "read", options);
5322
+ this.checkOperators(filter);
5091
5323
  return readScopeParts(this.context, user, collection, filter, "export", options);
5092
5324
  }
5093
5325
  /** The distinct values of a field, as aggregation results `{ _id, field }`. */
@@ -5096,7 +5328,7 @@ class DocumentService {
5096
5328
  const scoped = await this.scope(user, collection, {}, "distinct", options);
5097
5329
  const path = `$${field}`;
5098
5330
  const pipeline = [...Object.keys(scoped).length > 0 ? [{ $match: scoped }] : [], { $group: { _id: path, field: { $first: path } } }];
5099
- return paginatedAggregation(this.collection(collection), pipeline, true, paging, count);
5331
+ return paginatedAggregation(this.collection(collection), pipeline, true, this.limited(paging), count);
5100
5332
  }
5101
5333
  /**
5102
5334
  * An aggregation: `prefix` (the client's filter, the unset of secrets) and the stages of the client, after the scope of the caller as
@@ -5106,7 +5338,7 @@ class DocumentService {
5106
5338
  this.require(user, collection, "read", options);
5107
5339
  const scoped = await this.scope(user, collection, {}, "aggregate", options);
5108
5340
  const pipeline = [...Object.keys(scoped).length > 0 ? [{ $match: scoped }] : [], ...prefix, ...stages];
5109
- return paginatedAggregation(this.collection(collection), pipeline, allowDiskUse, paging, count);
5341
+ return paginatedAggregation(this.collection(collection), pipeline, allowDiskUse, this.limited(paging), count);
5110
5342
  }
5111
5343
  // ----- writes -----
5112
5344
  /**
@@ -5224,6 +5456,7 @@ class DocumentService {
5224
5456
  /** Changes the document of the path id with an operator update (`$set`, ...). */
5225
5457
  async update(user, collection, id, operators) {
5226
5458
  this.require(user, collection, "write");
5459
+ this.checkOperators(operators);
5227
5460
  const { filter, update, onNoMatch } = await this.intercept("document:beforeUpdate", user, collection, { filter: await this.scope(user, collection, pathIdFilter(id), "write"), update: operators, many: false });
5228
5461
  const old = await this.oldValues("document:update", collection, filter);
5229
5462
  const result = await this.collection(collection).updateOne(filter, update);
@@ -5236,6 +5469,7 @@ class DocumentService {
5236
5469
  /** Changes the documents of a filter (checked by the caller: not empty unless intended). */
5237
5470
  async updateMany(user, collection, filter, operators) {
5238
5471
  this.require(user, collection, "write");
5472
+ this.checkOperators(filter, operators);
5239
5473
  const payload = await this.intercept("document:beforeUpdate", user, collection, { filter: await this.scope(user, collection, filter, "write"), update: operators, many: true });
5240
5474
  const old = await this.oldValues("document:update", collection, payload.filter);
5241
5475
  const result = await this.collection(collection).updateMany(payload.filter, payload.update);
@@ -5253,6 +5487,7 @@ class DocumentService {
5253
5487
  /** Deletes the documents of a filter (checked by the caller). */
5254
5488
  async removeMany(user, collection, filter) {
5255
5489
  this.require(user, collection, "write");
5490
+ this.checkOperators(filter);
5256
5491
  const { filter: scoped, instead } = await this.intercept("document:beforeDelete", user, collection, { filter: await this.scope(user, collection, filter, "write"), many: true });
5257
5492
  const old = await this.oldValues("document:delete", collection, scoped);
5258
5493
  const result = await this.deleteOrInstead(collection, scoped, true, instead);
@@ -5277,7 +5512,7 @@ class DocumentService {
5277
5512
  }
5278
5513
  /** The audit records of a filter (a document or the collection), newest first. */
5279
5514
  async auditRecords(filter, paging, count = "exact") {
5280
- return readPage(auditCollectionOf(this.context), { filter, sort: { at: -1, _id: -1 }, projection: {} }, paging, count);
5515
+ return readPage(auditCollectionOf(this.context), { filter, sort: { at: -1, _id: -1 }, projection: {} }, this.limited(paging), count);
5281
5516
  }
5282
5517
  }
5283
5518
 
@@ -5657,8 +5892,9 @@ function parseDate(text, timeZone = "UTC") {
5657
5892
  return (FullIsoDate.test(text) ? parseJodaIso(text, timeZone) : void 0) ?? parseSimplePatterns(text, timeZone);
5658
5893
  }
5659
5894
 
5895
+ const ObjectIdHex = /^[0-9a-f]{24}$/i;
5660
5896
  function luceneQueryToFilter(query, options = {}) {
5661
- const settings = { both: options.searchWithValueAndString ?? false, caseInsensitive: options.caseInsensitive ?? false, timeZone: options.timeZone ?? "UTC" };
5897
+ const settings = { both: options.searchWithValueAndString ?? false, caseInsensitive: options.caseInsensitive ?? false, timeZone: options.timeZone ?? "UTC", idFields: new Set(options.idFields ?? []) };
5662
5898
  return searchMap(query, false, settings);
5663
5899
  }
5664
5900
  function searchMap(query, negated, settings) {
@@ -5764,6 +6000,10 @@ function appendTerm(negated, result, field, termText, settings, quoted = false)
5764
6000
  }
5765
6001
  const both = settings.both || quoted;
5766
6002
  const text = termText.includes("*") ? unescape(termText) : termText;
6003
+ if (settings.idFields.has(field) && ObjectIdHex.test(text)) {
6004
+ result[field] = { [negated ? "$nin" : "$in"]: [new ObjectId(text), text] };
6005
+ return;
6006
+ }
5767
6007
  const value = convertTermValue(text, settings.timeZone);
5768
6008
  const operator = negated ? "$ne" : "$eq";
5769
6009
  if (!both || value === text) {
@@ -6335,7 +6575,8 @@ class Parser {
6335
6575
  }
6336
6576
  const match = quoted ? null : comparison.exec(text);
6337
6577
  if (match) {
6338
- const [, operator, bound] = match;
6578
+ const operator = match[1];
6579
+ const bound = match[2] ?? "";
6339
6580
  switch (operator) {
6340
6581
  case ">":
6341
6582
  return { type: "range", field, lower: bound, upper: null, includeLower: false, includeUpper: true };
@@ -6399,6 +6640,9 @@ function bodyFilter(input, options = {}) {
6399
6640
 
6400
6641
  const SystemUser = new AuthorizedUser({ userId: "system", password: "", apiKey: null, roles: ["system"] }, [{ name: "system", isAdmin: true, collectionGrants: [] }]);
6401
6642
  function idOf(target) {
6643
+ if (isPlainObject(target) && (!("_id" in target) || target._id === void 0 || target._id === null)) {
6644
+ throw new MongocampError("the document has no _id", 400);
6645
+ }
6402
6646
  const id = isPlainObject(target) && "_id" in target ? target._id : target;
6403
6647
  return id instanceof ObjectId ? id.toHexString() : idToString(id);
6404
6648
  }
@@ -6431,7 +6675,7 @@ function createServerCollection(context, name, options) {
6431
6675
  if (filter === void 0) {
6432
6676
  return {};
6433
6677
  }
6434
- return typeof filter === "string" ? filterParameter(filter, { timeZone: context.config.string(ConfigKeys.FilterTimeZone) }) : filter;
6678
+ return typeof filter === "string" ? filterParameter(filter, { timeZone: context.config.string(ConfigKeys.FilterTimeZone), idFields: context.collections.refFields(context, name) }) : filter;
6435
6679
  };
6436
6680
  const plain = (document) => plainNumbers(document);
6437
6681
  const decodedConflict = async (write) => {
@@ -6513,24 +6757,29 @@ function requestOrigin(request) {
6513
6757
  return origin;
6514
6758
  }
6515
6759
  const referer = request.headers.get("referer");
6516
- return referer ? referer.replace(/\/$/, "") : void 0;
6760
+ if (!referer) {
6761
+ return void 0;
6762
+ }
6763
+ try {
6764
+ const { origin: refererOrigin } = new URL(referer);
6765
+ return refererOrigin === "null" ? void 0 : refererOrigin;
6766
+ } catch {
6767
+ return void 0;
6768
+ }
6517
6769
  }
6518
6770
  function corsHeaders(config, origin) {
6519
6771
  const allowedOrigins = config.list(ConfigKeys.CorsOriginsAllowed).filter((entry) => entry !== "");
6520
- let allowOrigin;
6521
- if (origin !== void 0 && allowedOrigins.includes(origin)) {
6522
- allowOrigin = origin;
6523
- } else if (allowedOrigins.length === 0) {
6524
- allowOrigin = "*";
6525
- } else {
6526
- allowOrigin = allowedOrigins[0];
6527
- }
6528
- return {
6529
- "access-control-allow-origin": allowOrigin,
6530
- "access-control-allow-credentials": "true",
6772
+ const common = {
6531
6773
  "access-control-allow-headers": config.list(ConfigKeys.CorsHeadersAllowed).join(","),
6532
6774
  "access-control-expose-headers": config.list(ConfigKeys.CorsHeadersExposed).join(",")
6533
6775
  };
6776
+ if (allowedOrigins.length === 0) {
6777
+ return { "access-control-allow-origin": "*", ...common };
6778
+ }
6779
+ if (origin !== void 0 && allowedOrigins.includes(origin)) {
6780
+ return { "access-control-allow-origin": origin, "access-control-allow-credentials": "true", "vary": "Origin", ...common };
6781
+ }
6782
+ return { vary: "Origin", ...common };
6534
6783
  }
6535
6784
  function preflightResponse(request, config) {
6536
6785
  return new Response(null, {
@@ -6548,19 +6797,22 @@ function newRequestId() {
6548
6797
  function withCommonHeaders(response, request, config, version, requestId) {
6549
6798
  const headers = {
6550
6799
  ...corsHeaders(config, requestOrigin(request)),
6551
- "server": `${version.name}/${version.version}`,
6800
+ // 2.5.0: SERVER_HEADER_ENABLED=false hides the name and version of the server
6801
+ ...config.boolean(ConfigKeys.ServerHeaderEnabled) ? { server: `${version.name}/${version.version}` } : {},
6552
6802
  "x-request-id": requestId
6553
6803
  };
6554
- try {
6804
+ const apply = (target) => {
6555
6805
  for (const [name, value] of Object.entries(headers)) {
6556
- response.headers.set(name, value);
6806
+ const existing = name === "vary" ? target.get("vary") : null;
6807
+ target.set(name, existing && !existing.split(",").some((entry) => entry.trim().toLowerCase() === "origin") ? `${existing}, ${value}` : existing ?? value);
6557
6808
  }
6809
+ };
6810
+ try {
6811
+ apply(response.headers);
6558
6812
  return response;
6559
6813
  } catch {
6560
6814
  const copy = new Response(response.body, response);
6561
- for (const [name, value] of Object.entries(headers)) {
6562
- copy.headers.set(name, value);
6563
- }
6815
+ apply(copy.headers);
6564
6816
  return copy;
6565
6817
  }
6566
6818
  }
@@ -6624,7 +6876,7 @@ const operations = [
6624
6876
  ["GET", "/auth/authenticated", "isAuthenticated", "Auth", "Check Authentication"],
6625
6877
  ["GET", "/admin/users", "listUsers", "Admin", "List Users"],
6626
6878
  ["PUT", "/admin/users", "addUser", "Admin", "Add User"],
6627
- ["PATCH", "/admin/users/:userId/apikey", "gnerateNewApiKeyForUser", "Admin", "Update ApiKey"],
6879
+ ["PATCH", "/admin/users/:userId/apikey", "generateNewApiKeyForUser", "Admin", "Update ApiKey"],
6628
6880
  ["PATCH", "/admin/users/:userId/password", "updatePasswordForUser", "Admin", "Update Password"],
6629
6881
  ["PATCH", "/admin/users/:userId/roles", "updateRolesForUser", "Admin", "Update User Roles"],
6630
6882
  ["GET", "/admin/users/:userId", "getUser", "Admin", "UserProfile for userId"],
@@ -6634,6 +6886,7 @@ const operations = [
6634
6886
  ["GET", "/admin/roles/:roleName", "getRole", "Admin", "Get Role"],
6635
6887
  ["DELETE", "/admin/roles/:roleName", "deleteRole", "Admin", "Delete Role"],
6636
6888
  ["PATCH", "/admin/roles/:roleName", "updateRole", "Admin", "Update Role"],
6889
+ ["POST", "/mongodb/buckets/:bucketName/files/search", "searchFiles", "File", "Search Files in Bucket"],
6637
6890
  ["GET", "/mongodb/buckets/:bucketName/files", "listFiles", "File", "Files in Bucket"],
6638
6891
  ["PUT", "/mongodb/buckets/:bucketName/files", "insertFile", "File", "Insert File"],
6639
6892
  ["POST", "/mongodb/buckets/:bucketName/files", "findFiles", "File", "Files in Bucket"],
@@ -6666,6 +6919,7 @@ const operations = [
6666
6919
  ["GET", "/system/configurations", "listConfigurations", "Application", "List Configurations"],
6667
6920
  ["GET", "/system/configurations/:configurationKey", "getConfig", "Application", "Configuration for configurationKey"],
6668
6921
  ["PATCH", "/system/configurations/:configurationKey", "updateConfiguration", "Application", "Update Configuration"],
6922
+ ["DELETE", "/system/configurations/:configurationKey", "resetConfiguration", "Application", "Reset Configuration"],
6669
6923
  ["DELETE", "/system", "shutdown", "Application", "Shutdown MongoCamp"],
6670
6924
  ["GET", "/mongodb/databases", "ListDatabases", "Database", "List of Databases"],
6671
6925
  ["GET", "/mongodb/databases/infos", "databaseInfos", "Database", "List of Database Infos"],
@@ -6832,8 +7086,11 @@ function optionalInteger$1(body, field) {
6832
7086
  }
6833
7087
  return value;
6834
7088
  }
6835
- function stringList(value, field) {
6836
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
7089
+ function isStringList(value) {
7090
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
7091
+ }
7092
+ function stringList$1(value, field) {
7093
+ if (!isStringList(value)) {
6837
7094
  fail(field);
6838
7095
  }
6839
7096
  return value;
@@ -6862,7 +7119,7 @@ function readUserInformation(body) {
6862
7119
  userId: requiredString(object, "userId"),
6863
7120
  password: requiredString(object, "password"),
6864
7121
  apiKey: optionalString(object, "apiKey") ?? null,
6865
- roles: object.roles === void 0 || object.roles === null ? [] : stringList(object.roles, "roles")
7122
+ roles: object.roles === void 0 || object.roles === null ? [] : stringList$1(object.roles, "roles")
6866
7123
  };
6867
7124
  }
6868
7125
  function readGrant(value, index) {
@@ -6891,25 +7148,18 @@ function readUpdateRole(body) {
6891
7148
  };
6892
7149
  }
6893
7150
  function readRoleNames(body) {
6894
- return stringList(body, "body");
6895
- }
6896
-
6897
- async function readJson(event) {
6898
- const text = await event.req.text();
6899
- if (text.trim() === "") {
6900
- throw MongocampError.decodeFailure("body");
6901
- }
6902
- return parseJsonBody(text);
6903
- }
6904
- async function readDocumentBody(event) {
6905
- return convertFields(decodeAnyObject(await readJson(event)));
7151
+ return stringList$1(body, "body");
6906
7152
  }
6907
7153
 
6908
7154
  function pathParam(event, name) {
6909
- return getRouterParam(event, name, { decode: true }) ?? "";
7155
+ const value = getRouterParam(event, name, { decode: true });
7156
+ if (value === void 0 || value === "") {
7157
+ throw MongocampError.decodeFailure(`path parameter ${name}`);
7158
+ }
7159
+ return value;
6910
7160
  }
6911
7161
  function queryParams(event) {
6912
- return new URL(event.req.url).searchParams;
7162
+ return event.url.searchParams;
6913
7163
  }
6914
7164
  function intQuery(params, name) {
6915
7165
  const raw = params.get(name);
@@ -6933,19 +7183,62 @@ function booleanQuery(params, name, defaultValue) {
6933
7183
  }
6934
7184
  return normalized === "true";
6935
7185
  }
6936
- function filterOptions(params, config) {
7186
+ function filterOptions(params, config, idFields = []) {
6937
7187
  const timeZone = config.string(ConfigKeys.FilterTimeZone);
6938
7188
  if (!isTimeZone(timeZone)) {
6939
7189
  throw new MongocampError(`${ConfigKeys.FilterTimeZone} is no time zone: ${timeZone}`, 500);
6940
7190
  }
6941
- return { caseInsensitive: booleanQuery(params, "filterCaseInsensitive", false), timeZone };
7191
+ return { caseInsensitive: booleanQuery(params, "filterCaseInsensitive", false), timeZone, idFields };
7192
+ }
7193
+ function tooLarge() {
7194
+ return new MongocampError("the body of the request is greater than BODY_MAX_BYTES", 413, ErrorCodes.bodyTooLarge);
7195
+ }
7196
+ async function readText(event) {
7197
+ const max = event.context.mongocampBodyMaxBytes ?? 0;
7198
+ if (max <= 0 || event.req.body === null) {
7199
+ return event.req.text();
7200
+ }
7201
+ const declared = Number(event.req.headers.get("content-length") ?? Number.NaN);
7202
+ if (declared > max) {
7203
+ throw tooLarge();
7204
+ }
7205
+ const reader = event.req.body.getReader();
7206
+ const decoder = new TextDecoder();
7207
+ let text = "";
7208
+ let total = 0;
7209
+ for (; ; ) {
7210
+ const { done, value } = await reader.read();
7211
+ if (done) {
7212
+ return text + decoder.decode();
7213
+ }
7214
+ total += value.byteLength;
7215
+ if (total > max) {
7216
+ await reader.cancel().catch(() => void 0);
7217
+ throw tooLarge();
7218
+ }
7219
+ text += decoder.decode(value, { stream: true });
7220
+ }
7221
+ }
7222
+ async function readJson(event) {
7223
+ const text = await readText(event);
7224
+ if (text.trim() === "") {
7225
+ throw MongocampError.decodeFailure("body");
7226
+ }
7227
+ return parseJsonBody(text);
7228
+ }
7229
+ async function readOptionalJson(event) {
7230
+ const text = await readText(event);
7231
+ return text.trim() === "" ? void 0 : parseJsonBody(text);
7232
+ }
7233
+ async function readDocumentBody(event) {
7234
+ return convertFields(decodeAnyObject(await readJson(event)));
6942
7235
  }
6943
7236
 
6944
7237
  function registerAdminRoutes(app, context) {
6945
7238
  const { auth, events } = context;
6946
7239
  app.get("/admin/users", async (event) => {
6947
7240
  await auth.requireAdmin(event.req);
6948
- const params = new URL(event.req.url).searchParams;
7241
+ const params = queryParams(event);
6949
7242
  const { items, info } = await auth.holder.allUsers(params.get("filter") ?? void 0, readPaging(params));
6950
7243
  const profiles = await Promise.all(items.map((user) => auth.profileOf(user)));
6951
7244
  return jsonResponse(profiles, { headers: paginationHeaders(info) });
@@ -6956,7 +7249,7 @@ function registerAdminRoutes(app, context) {
6956
7249
  });
6957
7250
  app.get("/admin/roles", async (event) => {
6958
7251
  await auth.requireAdmin(event.req);
6959
- const params = new URL(event.req.url).searchParams;
7252
+ const params = queryParams(event);
6960
7253
  const { items, info } = await auth.holder.allRoles(params.get("filter") ?? void 0, readPaging(params));
6961
7254
  return jsonResponse(items, { headers: paginationHeaders(info) });
6962
7255
  });
@@ -7049,89 +7342,6 @@ function registerAdminRoutes(app, context) {
7049
7342
  });
7050
7343
  }
7051
7344
 
7052
- function normalizeStage(name) {
7053
- return name.startsWith("$") ? name : `$${name}`;
7054
- }
7055
- function refuseIfDenied(operator, denied) {
7056
- if (denied.has(operator)) {
7057
- throw MongocampError.forbidden(`the operator ${operator} is not allowed in an aggregation`, ErrorCodes.forbiddenStage);
7058
- }
7059
- }
7060
- function scan(value, denied) {
7061
- if (Array.isArray(value)) {
7062
- value.forEach((entry) => scan(entry, denied));
7063
- } else if (isPlainObject(value)) {
7064
- for (const [key, entry] of Object.entries(value)) {
7065
- refuseIfDenied(key, denied);
7066
- scan(entry, denied);
7067
- }
7068
- }
7069
- }
7070
- function checkDeniedOperators(pipeline, deniedOperators) {
7071
- const denied = new Set(deniedOperators.map(normalizeStage));
7072
- if (denied.size === 0) {
7073
- return;
7074
- }
7075
- for (const stage of pipeline) {
7076
- refuseIfDenied(normalizeStage(stage.stage), denied);
7077
- scan(stage.value, denied);
7078
- }
7079
- }
7080
- function referencedCollections(value) {
7081
- const fromValue = (from) => {
7082
- if (typeof from === "string") {
7083
- return [{ name: from }];
7084
- }
7085
- if (isPlainObject(from)) {
7086
- return [{ unsupported: "a reference to a collection of another database" }];
7087
- }
7088
- return [];
7089
- };
7090
- if (Array.isArray(value)) {
7091
- return value.flatMap(referencedCollections);
7092
- }
7093
- if (!isPlainObject(value)) {
7094
- return [];
7095
- }
7096
- return Object.entries(value).flatMap(([key, entry]) => {
7097
- let own = [];
7098
- if ((key === "$lookup" || key === "$graphLookup") && isPlainObject(entry)) {
7099
- own = fromValue(entry.from);
7100
- } else if (key === "$unionWith" && typeof entry === "string") {
7101
- own = [{ name: entry }];
7102
- } else if (key === "$unionWith" && isPlainObject(entry)) {
7103
- own = fromValue(entry.coll);
7104
- }
7105
- return [...own, ...referencedCollections(entry)];
7106
- });
7107
- }
7108
- function checkPipeline(user, collection, pipeline, deniedOperators) {
7109
- checkDeniedOperators(pipeline, deniedOperators);
7110
- const separator = collection.indexOf(":");
7111
- const prefix = separator >= 0 ? collection.slice(0, separator + 1) : "";
7112
- for (const stage of pipeline) {
7113
- for (const reference of referencedCollections({ [normalizeStage(stage.stage)]: stage.value })) {
7114
- if ("unsupported" in reference) {
7115
- throw MongocampError.forbidden(`${reference.unsupported} is not supported in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
7116
- }
7117
- if (!user.canRead(prefix + reference.name)) {
7118
- throw MongocampError.forbidden(`the user is not allowed to read the collection ${reference.name} in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
7119
- }
7120
- }
7121
- }
7122
- }
7123
- const firstStageOnly = /* @__PURE__ */ new Set(["$geoNear", "$search", "$searchMeta", "$vectorSearch", "$collStats", "$indexStats", "$documents"]);
7124
- function checkMatchBefore(pipeline) {
7125
- const first = pipeline[0];
7126
- if (first && firstStageOnly.has(normalizeStage(first.stage))) {
7127
- const stage = normalizeStage(first.stage);
7128
- throw MongocampError.badRequest(`the filter cannot be combined with a pipeline that starts with ${stage}, put the conditions in the stage itself`, ErrorCodes.filterNotSupported);
7129
- }
7130
- }
7131
- function toBsonPipeline(pipeline) {
7132
- return pipeline.map((stage) => ({ [normalizeStage(stage.stage)]: stage.value }));
7133
- }
7134
-
7135
7345
  function readAggregateRequest(body) {
7136
7346
  const object = asObject(body);
7137
7347
  if (!Array.isArray(object.pipeline)) {
@@ -7161,7 +7371,7 @@ function registerAggregationRoutes(app, context) {
7161
7371
  if (queryFilter !== null && queryFilter.trim() !== "" && request.filter !== void 0 && request.filter.trim() !== "") {
7162
7372
  throw MongocampError.badRequest("send the filter in the query or in the body, not in both", ErrorCodes.ambiguousFilter);
7163
7373
  }
7164
- const matchFilter = request.filter !== void 0 ? bodyFilter(request.filter, filterOptions(params, config)) : filterParameter(queryFilter, filterOptions(params, config));
7374
+ const matchFilter = request.filter !== void 0 ? bodyFilter(request.filter, filterOptions(params, config, context.collections.refFields(context, collection))) : filterParameter(queryFilter, filterOptions(params, config, context.collections.refFields(context, collection)));
7165
7375
  checkPipeline(user, collection, request.pipeline, config.list(ConfigKeys.AggregationStagesDenied));
7166
7376
  const prefix = [];
7167
7377
  if (Object.keys(matchFilter).length > 0) {
@@ -7246,7 +7456,7 @@ function registerAuthRoutes(app, context) {
7246
7456
  });
7247
7457
  app.get("/auth/permissions", async (event) => {
7248
7458
  const user = await auth.authenticate(event.req);
7249
- const collection = new URL(event.req.url).searchParams.get("collection");
7459
+ const collection = queryParams(event).get("collection");
7250
7460
  if (collection !== null) {
7251
7461
  return jsonResponse([user.permissionsFor(collection)]);
7252
7462
  }
@@ -7332,12 +7542,13 @@ async function findFile(bucket, id) {
7332
7542
  function uploadMetadata(text) {
7333
7543
  return convertFields(jsonMapParameter(text ?? null));
7334
7544
  }
7335
- async function uploadFile(bucket, request, fileNameOverride) {
7545
+ async function uploadFile(bucket, request, fileNameOverride, maxBytes = 0) {
7336
7546
  const contentType = request.headers.get("content-type") ?? "";
7337
7547
  if (!contentType.toLowerCase().startsWith("multipart/form-data") || !request.body) {
7338
7548
  throw MongocampError.decodeFailure("body", "a multipart/form-data body with the part file is expected");
7339
7549
  }
7340
- const parser = busboy({ headers: { "content-type": contentType } });
7550
+ const parser = busboy({ headers: { "content-type": contentType }, ...maxBytes > 0 ? { limits: { fileSize: maxBytes + 1 } } : {} });
7551
+ let truncated = false;
7341
7552
  const id = new ObjectId();
7342
7553
  let metadataText;
7343
7554
  let uploaded;
@@ -7354,6 +7565,9 @@ async function uploadFile(bucket, request, fileNameOverride) {
7354
7565
  }
7355
7566
  const fileName = fileNameOverride || info.filename || "file";
7356
7567
  metadataWithUpload = metadataText !== void 0;
7568
+ stream.on("limit", () => {
7569
+ truncated = true;
7570
+ });
7357
7571
  const target = gridFsBucket(bucket).openUploadStream(fileName, { id, metadata: uploadMetadata(metadataText) });
7358
7572
  uploaded = pipeline(stream, target);
7359
7573
  uploaded.catch(() => void 0);
@@ -7367,6 +7581,10 @@ async function uploadFile(bucket, request, fileNameOverride) {
7367
7581
  throw MongocampError.decodeFailure("body", "the part file is missing");
7368
7582
  }
7369
7583
  await uploaded;
7584
+ if (truncated) {
7585
+ await deleteFile(bucket, id);
7586
+ throw new MongocampError("the file is greater than GRIDFS_UPLOAD_MAX_BYTES", 413, ErrorCodes.uploadTooLarge);
7587
+ }
7370
7588
  if (!metadataWithUpload && metadataText !== void 0) {
7371
7589
  await filesCollection(bucket).updateOne({ _id: id }, { $set: { metadata: uploadMetadata(metadataText) } });
7372
7590
  }
@@ -7415,6 +7633,16 @@ function mapField$1(body, field) {
7415
7633
  }
7416
7634
  return decodeAny(value);
7417
7635
  }
7636
+ function stringList(body, field) {
7637
+ const value = body[field];
7638
+ if (value === void 0 || value === null) {
7639
+ return [];
7640
+ }
7641
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
7642
+ throw MongocampError.decodeFailure("body", `field ${field}`);
7643
+ }
7644
+ return value;
7645
+ }
7418
7646
  function registerBucketRoutes(app, context) {
7419
7647
  const { auth, database, config, events } = context;
7420
7648
  const base = "/mongodb/buckets/:bucketName";
@@ -7426,8 +7654,8 @@ function registerBucketRoutes(app, context) {
7426
7654
  };
7427
7655
  const fileId = (event) => convertIdField(pathParam(event, "fileId"));
7428
7656
  const requireExisting = async (bucket, name) => {
7429
- const files = filesCollection(bucket);
7430
- const found = await database.db(files.dbName).listCollections({ name: files.collectionName }, { nameOnly: true }).toArray();
7657
+ const files2 = filesCollection(bucket);
7658
+ const found = await database.db(files2.dbName).listCollections({ name: files2.collectionName }, { nameOnly: true }).toArray();
7431
7659
  if (found.length === 0) {
7432
7660
  throw MongocampError.notFound(`the bucket ${name} does not exist`);
7433
7661
  }
@@ -7460,22 +7688,37 @@ function registerBucketRoutes(app, context) {
7460
7688
  return jsonResponse({ value: chunks.acknowledged });
7461
7689
  });
7462
7690
  const filesResponse = (page) => jsonResponse(page.items, { headers: paginationHeaders(page.info) });
7691
+ const files = (bucket, request, params) => {
7692
+ checkDeniedFilterOperators([request.filter, request.projection], config.list(ConfigKeys.FilterOperatorsDenied));
7693
+ return findFiles(bucket, request, limitPaging(readPaging(params), config.number(ConfigKeys.PagingMaxRows)), readCountMode(params));
7694
+ };
7463
7695
  app.get(`${base}/files`, async (event) => {
7464
7696
  const { bucket } = await authorized(event, "read");
7465
7697
  const params = queryParams(event);
7466
7698
  const request = { filter: jsonMapParameter(params.get("filter")), sort: jsonMapParameter(params.get("sort")), projection: jsonMapParameter(params.get("projection")) };
7467
- return filesResponse(await findFiles(bucket, request, readPaging(params), readCountMode(params)));
7699
+ return filesResponse(await files(bucket, request, params));
7468
7700
  });
7469
7701
  app.post(`${base}/files`, async (event) => {
7470
7702
  const { bucket } = await authorized(event, "read");
7471
7703
  const body = asObject(await readJson(event));
7472
7704
  const request = { filter: mapField$1(body, "filter"), sort: mapField$1(body, "sort"), projection: mapField$1(body, "projection") };
7473
7705
  const params = queryParams(event);
7474
- return filesResponse(await findFiles(bucket, request, readPaging(params), readCountMode(params)));
7706
+ return filesResponse(await files(bucket, request, params));
7707
+ });
7708
+ app.post(`${base}/files/search`, async (event) => {
7709
+ const { bucket } = await authorized(event, "read");
7710
+ const params = queryParams(event);
7711
+ const body = asObject(await readJson(event));
7712
+ const request = {
7713
+ filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
7714
+ sort: sortFromList(stringList(body, "sort")),
7715
+ projection: projectionFromList(stringList(body, "projection"))
7716
+ };
7717
+ return filesResponse(await files(bucket, request, params));
7475
7718
  });
7476
7719
  app.put(`${base}/files`, async (event) => {
7477
7720
  const { bucket, name, user } = await authorized(event, "write");
7478
- const id = await uploadFile(bucket, event.req, queryParams(event).get("fileName") ?? void 0);
7721
+ const id = await uploadFile(bucket, event.req, queryParams(event).get("fileName") ?? void 0, context.config.number(ConfigKeys.GridfsUploadMaxBytes));
7479
7722
  const response = { wasAcknowledged: true, insertedIds: [id.toHexString()] };
7480
7723
  events.publish("file:create", { user, bucketName: name, insertResponse: response });
7481
7724
  return jsonResponse(response);
@@ -8379,9 +8622,8 @@ function registerCollectionRoutes(app, context) {
8379
8622
  app.put("/mongodb/collections/:collectionName", async (event) => {
8380
8623
  const collection = collectionParam(event);
8381
8624
  const user = await auth.requireCollection(event.req, collection, "administrate");
8382
- const text = await event.req.text();
8383
- const parsed = text.trim() === "" ? null : parseJsonBody(text);
8384
- const options = parsed === null ? emptyOptions : readCollectionOptions(parsed);
8625
+ const parsed = await readOptionalJson(event);
8626
+ const options = parsed === void 0 ? emptyOptions : readCollectionOptions(parsed);
8385
8627
  const name = parseCollectionName(collection);
8386
8628
  checkName(name.name, systemPrefix(), "the name of the collection");
8387
8629
  checkForCreate(options);
@@ -8457,7 +8699,7 @@ function registerCollectionRoutes(app, context) {
8457
8699
  if (!await existsIn(source)) {
8458
8700
  throw new MongocampError(`the collection ${fullName(source)} does not exist`, 404, ErrorCodes.invalidCollectionName);
8459
8701
  }
8460
- const filter = bodyFilter(request.filter, filterOptions(queryParams(event), config));
8702
+ const filter = bodyFilter(request.filter, filterOptions(queryParams(event), config, context.collections.refFields(context, collection)));
8461
8703
  const targetExists = await checkTarget(user, target, request.dropTarget);
8462
8704
  const result = await copyCollection(database, source, target, filter, request.withIndexes, targetExists, systemPrefix());
8463
8705
  context.events.publish("collection:copy", { user: user.user, collectionName: fullName(source), newCollectionName: fullName(target) });
@@ -9137,7 +9379,7 @@ paths:
9137
9379
  - Admin
9138
9380
  summary: Update ApiKey
9139
9381
  description: Generate a new API key for the user
9140
- operationId: gnerateNewApiKeyForUser
9382
+ operationId: generateNewApiKeyForUser
9141
9383
  parameters:
9142
9384
  - name: userId
9143
9385
  in: path
@@ -9575,13 +9817,63 @@ paths:
9575
9817
  get:
9576
9818
  tags:
9577
9819
  - Admin
9578
- summary: Get Role
9579
- description: Get Role by RoleKey
9580
- operationId: getRole
9820
+ summary: Get Role
9821
+ description: Get Role by RoleKey
9822
+ operationId: getRole
9823
+ parameters:
9824
+ - name: roleName
9825
+ in: path
9826
+ description: RoleKey to search
9827
+ required: true
9828
+ schema:
9829
+ type: string
9830
+ responses:
9831
+ '200':
9832
+ description: ''
9833
+ content:
9834
+ application/json:
9835
+ schema:
9836
+ $ref: '#/components/schemas/Role'
9837
+ default:
9838
+ description: ''
9839
+ headers:
9840
+ x-error-code:
9841
+ description: Error Code
9842
+ required: true
9843
+ schema:
9844
+ type: integer
9845
+ format: int32
9846
+ example: 100
9847
+ x-error-message:
9848
+ description: Message of the MongoCampException
9849
+ required: true
9850
+ schema:
9851
+ type: string
9852
+ example: Error Message
9853
+ x-error-additional-info:
9854
+ description: Additional information for the MongoCampException
9855
+ required: true
9856
+ schema:
9857
+ type: string
9858
+ example: Additional Error Info
9859
+ content:
9860
+ application/json:
9861
+ schema:
9862
+ $ref: '#/components/schemas/ErrorDescription'
9863
+ security:
9864
+ - httpAuth: []
9865
+ - httpAuth1: []
9866
+ - apiKeyAuth: []
9867
+ delete:
9868
+ tags:
9869
+ - Admin
9870
+ summary: Delete Role
9871
+ description: 'Delete Role. 404 for a role that does not exist (2.0.0).'
9872
+ operationId: deleteRole
9581
9873
  parameters:
9582
9874
  - name: roleName
9583
9875
  in: path
9584
- description: RoleKey to search
9876
+ description: RoleKey
9585
9877
  required: true
9586
9878
  schema:
9587
9879
  type: string
@@ -9591,7 +9883,7 @@ paths:
9591
9883
  content:
9592
9884
  application/json:
9593
9885
  schema:
9594
- $ref: '#/components/schemas/Role'
9886
+ $ref: '#/components/schemas/JsonValue_Boolean'
9595
9887
  default:
9596
9888
  description: ''
9597
9889
  headers:
@@ -9622,12 +9914,12 @@ paths:
9622
9914
  - httpAuth: []
9623
9915
  - httpAuth1: []
9624
9916
  - apiKeyAuth: []
9625
- delete:
9917
+ patch:
9626
9918
  tags:
9627
9919
  - Admin
9628
- summary: Delete Role
9629
- description: 'Delete Role. 404 for a role that does not exist (2.0.0).'
9630
- operationId: deleteRole
9920
+ summary: Update Role
9921
+ description: Update Role
9922
+ operationId: updateRole
9631
9923
  parameters:
9632
9924
  - name: roleName
9633
9925
  in: path
@@ -9635,13 +9927,25 @@ paths:
9635
9927
  required: true
9636
9928
  schema:
9637
9929
  type: string
9930
+ requestBody:
9931
+ content:
9932
+ application/json:
9933
+ schema:
9934
+ $ref: '#/components/schemas/UpdateRoleRequest'
9935
+ required: true
9638
9936
  responses:
9639
9937
  '200':
9640
9938
  description: ''
9641
9939
  content:
9642
9940
  application/json:
9643
9941
  schema:
9644
- $ref: '#/components/schemas/JsonValue_Boolean'
9942
+ $ref: '#/components/schemas/Role'
9943
+ '400':
9944
+ description: 'Invalid value for: body'
9945
+ content:
9946
+ text/plain:
9947
+ schema:
9948
+ type: string
9645
9949
  default:
9646
9950
  description: ''
9647
9951
  headers:
@@ -9672,34 +9976,118 @@ paths:
9672
9976
  - httpAuth: []
9673
9977
  - httpAuth1: []
9674
9978
  - apiKeyAuth: []
9675
- patch:
9979
+ /mongodb/buckets/{bucketName}/files/search:
9980
+ post:
9676
9981
  tags:
9677
- - Admin
9678
- summary: Update Role
9679
- description: Update Role
9680
- operationId: updateRole
9982
+ - File
9983
+ summary: Search Files in Bucket
9984
+ description: 'The files of the bucket with a Lucene filter (2.6.0), like the search of documents: filter, sort and projection in the request body (no URL limit), fields of the files collection (filename, length, uploadDate, metadata.*). The operators of FILTER_OPERATORS_DENIED are refused; PAGING_MAX_ROWS applies.'
9985
+ operationId: searchFiles
9681
9986
  parameters:
9682
- - name: roleName
9987
+ - name: bucketName
9683
9988
  in: path
9684
- description: RoleKey
9989
+ description: The name of your MongoDb Collection
9685
9990
  required: true
9686
9991
  schema:
9687
9992
  type: string
9993
+ - name: rowsPerPage
9994
+ in: query
9995
+ description: Count elements per page
9996
+ required: false
9997
+ schema:
9998
+ type: integer
9999
+ format: int64
10000
+ example: 100
10001
+ - name: page
10002
+ in: query
10003
+ description: Requested page of the ResultSets
10004
+ required: false
10005
+ schema:
10006
+ type: integer
10007
+ format: int64
10008
+ example: 1
10009
+ - name: count
10010
+ in: query
10011
+ description: 'How the result is counted: exact (default) or none (no count headers, no count query)'
10012
+ required: false
10013
+ schema:
10014
+ type: string
10015
+ enum:
10016
+ - exact
10017
+ - none
10018
+ default: exact
10019
+ example: exact
10020
+ - name: after
10021
+ in: query
10022
+ description: 'Cursor paging: the x-pagination-next value of the previous page, empty for the first page. The sort always ends
10023
+ with _id; cannot be combined with page'
10024
+ required: false
10025
+ schema:
10026
+ type: string
10027
+ example: ''
10028
+ - name: filterCaseInsensitive
10029
+ in: query
10030
+ description: 'true: wildcards and prefixes of the Lucene filter ignore the case.'
10031
+ required: false
10032
+ schema:
10033
+ type: boolean
10034
+ default: false
9688
10035
  requestBody:
9689
10036
  content:
9690
10037
  application/json:
9691
10038
  schema:
9692
- $ref: '#/components/schemas/UpdateRoleRequest'
10039
+ $ref: '#/components/schemas/SearchRequest'
10040
+ example:
10041
+ filter: filename:report* AND metadata.year:2024
10042
+ sort:
10043
+ - -uploadDate
9693
10044
  required: true
9694
10045
  responses:
9695
10046
  '200':
9696
10047
  description: ''
10048
+ headers:
10049
+ x-pagination-count-rows:
10050
+ description: count all elements
10051
+ required: false
10052
+ schema:
10053
+ type: integer
10054
+ format: int64
10055
+ example: 200
10056
+ x-pagination-rows-per-page:
10057
+ description: Count elements per page
10058
+ required: true
10059
+ schema:
10060
+ type: integer
10061
+ format: int64
10062
+ example: 20
10063
+ x-pagination-current-page:
10064
+ description: Current page
10065
+ required: true
10066
+ schema:
10067
+ type: integer
10068
+ format: int64
10069
+ example: 1
10070
+ x-pagination-count-pages:
10071
+ description: Count pages
10072
+ required: false
10073
+ schema:
10074
+ type: integer
10075
+ format: int64
10076
+ example: 10
10077
+ x-pagination-next:
10078
+ description: 'Cursor of the next page (only with the parameter after, missing on the last page)'
10079
+ required: false
10080
+ schema:
10081
+ type: string
9697
10082
  content:
9698
10083
  application/json:
9699
10084
  schema:
9700
- $ref: '#/components/schemas/Role'
10085
+ type: array
10086
+ items:
10087
+ $ref: '#/components/schemas/FileInformation'
9701
10088
  '400':
9702
- description: 'Invalid value for: body'
10089
+ description: 'Invalid value for: query parameter rowsPerPage, Invalid value
10090
+ for: query parameter page'
9703
10091
  content:
9704
10092
  text/plain:
9705
10093
  schema:
@@ -12073,6 +12461,62 @@ paths:
12073
12461
  - httpAuth: []
12074
12462
  - httpAuth1: []
12075
12463
  - apiKeyAuth: []
12464
+ delete:
12465
+ tags:
12466
+ - Application
12467
+ summary: Reset Configuration
12468
+ description: 'Reset the Configuration to its default value (2.6.0), at once for a key that needs no restart. 404 for an unknown key, 400 for a key that is read at the start only, set by the environment or has a generated default (AUTH_SECRET).'
12469
+ operationId: resetConfiguration
12470
+ parameters:
12471
+ - name: configurationKey
12472
+ in: path
12473
+ description: configurationKey to reset
12474
+ required: true
12475
+ schema:
12476
+ type: string
12477
+ responses:
12478
+ '200':
12479
+ description: ''
12480
+ content:
12481
+ application/json:
12482
+ schema:
12483
+ $ref: '#/components/schemas/JsonValue_Boolean'
12484
+ '400':
12485
+ description: 'Invalid value for: path parameter configurationKey'
12486
+ content:
12487
+ text/plain:
12488
+ schema:
12489
+ type: string
12490
+ default:
12491
+ description: ''
12492
+ headers:
12493
+ x-error-code:
12494
+ description: Error Code
12495
+ required: true
12496
+ schema:
12497
+ type: integer
12498
+ format: int32
12499
+ example: 100
12500
+ x-error-message:
12501
+ description: Message of the MongoCampException
12502
+ required: true
12503
+ schema:
12504
+ type: string
12505
+ example: Error Message
12506
+ x-error-additional-info:
12507
+ description: Additional information for the MongoCampException
12508
+ required: true
12509
+ schema:
12510
+ type: string
12511
+ example: Additional Error Info
12512
+ content:
12513
+ application/json:
12514
+ schema:
12515
+ $ref: '#/components/schemas/ErrorDescription'
12516
+ security:
12517
+ - httpAuth: []
12518
+ - httpAuth1: []
12519
+ - apiKeyAuth: []
12076
12520
  /system:
12077
12521
  delete:
12078
12522
  tags:
@@ -15651,11 +16095,31 @@ components:
15651
16095
  type: object
15652
16096
  required:
15653
16097
  - importMaxBytes
16098
+ - bodyMaxBytes
16099
+ - pagingMaxRows
16100
+ - exportMaxDocuments
16101
+ - gridfsUploadMaxBytes
15654
16102
  - grantDeniedStatus
15655
16103
  properties:
15656
16104
  importMaxBytes:
15657
16105
  type: integer
15658
16106
  format: int64
16107
+ bodyMaxBytes:
16108
+ description: BODY_MAX_BYTES (2.6.0); 0 is no limit.
16109
+ type: integer
16110
+ format: int64
16111
+ pagingMaxRows:
16112
+ description: PAGING_MAX_ROWS (2.6.0); 0 is no limit.
16113
+ type: integer
16114
+ format: int64
16115
+ exportMaxDocuments:
16116
+ description: EXPORT_MAX_DOCUMENTS (2.6.0); 0 is no limit.
16117
+ type: integer
16118
+ format: int64
16119
+ gridfsUploadMaxBytes:
16120
+ description: GRIDFS_UPLOAD_MAX_BYTES (2.6.0); 0 is no limit.
16121
+ type: integer
16122
+ format: int64
15659
16123
  grantDeniedStatus:
15660
16124
  type: integer
15661
16125
  format: int32
@@ -16685,6 +17149,7 @@ components:
16685
17149
  - protectedFields
16686
17150
  - indexes
16687
17151
  - refs
17152
+ - referencedBy
16688
17153
  properties:
16689
17154
  name:
16690
17155
  type: string
@@ -16714,6 +17179,8 @@ components:
16714
17179
  - name
16715
17180
  - key
16716
17181
  - unique
17182
+ - sparse
17183
+ - origin
16717
17184
  properties:
16718
17185
  name:
16719
17186
  type: string
@@ -16722,6 +17189,28 @@ components:
16722
17189
  additionalProperties: true
16723
17190
  unique:
16724
17191
  type: boolean
17192
+ sparse:
17193
+ description: 2.6.0
17194
+ type: boolean
17195
+ origin:
17196
+ description: 'Declared, or added for a behaviour (owner = the index on the owner field), 2.6.0.'
17197
+ type: string
17198
+ enum:
17199
+ - declaration
17200
+ - owner
17201
+ partialFilterExpression:
17202
+ description: The partial filter as relaxed Extended JSON (2.6.0), as index details show it.
17203
+ type: object
17204
+ additionalProperties: true
17205
+ partialFilterFrom:
17206
+ description: softDelete when the soft delete behaviour added the partial filter to a unique index (2.6.0).
17207
+ type: string
17208
+ enum:
17209
+ - softDelete
17210
+ expireAfterSeconds:
17211
+ description: 2.6.0
17212
+ type: integer
17213
+ format: int64
16725
17214
  refs:
16726
17215
  description: The references of the declaration (2.4.0), the fields a read can expand (query parameter expand).
16727
17216
  type: array
@@ -16730,6 +17219,7 @@ components:
16730
17219
  required:
16731
17220
  - field
16732
17221
  - collection
17222
+ - many
16733
17223
  properties:
16734
17224
  field:
16735
17225
  type: string
@@ -16737,7 +17227,28 @@ components:
16737
17227
  description: The target collection (name or database:name).
16738
17228
  type: string
16739
17229
  many:
16740
- description: Whether the field holds an array of ids (from the schema); missing when the schema does not tell.
17230
+ description: Whether the field holds an array of ids (from the schema or the declaration); false when neither tells (2.6.0, before it was missing then).
17231
+ type: boolean
17232
+ referencedBy:
17233
+ description: The references of the declared collections to this collection (2.6.0), from the declarations of the server; empty when none.
17234
+ type: array
17235
+ items:
17236
+ type: object
17237
+ required:
17238
+ - collection
17239
+ - database
17240
+ - field
17241
+ - many
17242
+ properties:
17243
+ collection:
17244
+ description: The referencing collection as the routes name it (name or database:name).
17245
+ type: string
17246
+ database:
17247
+ type: string
17248
+ field:
17249
+ description: The field of the referencing collection that holds the id.
17250
+ type: string
17251
+ many:
16741
17252
  type: boolean
16742
17253
  timestamps:
16743
17254
  type: object
@@ -17110,7 +17621,7 @@ function registerDocsRoutes(app, context) {
17110
17621
  }
17111
17622
  }
17112
17623
 
17113
- function declarationInfo(declared) {
17624
+ function declarationInfo(declared, referencedBy = []) {
17114
17625
  const { behaviours } = declared;
17115
17626
  return {
17116
17627
  name: declared.definition.name,
@@ -17118,8 +17629,20 @@ function declarationInfo(declared) {
17118
17629
  validation: declared.validation,
17119
17630
  systemFields: systemFields(behaviours).map((entry) => entry.path),
17120
17631
  protectedFields: [...behaviours.protectedFields],
17121
- indexes: declared.indexes.map((index) => ({ name: index.name, key: { ...index.key }, unique: index.options.unique === true })),
17122
- refs: declared.refs.map((ref) => ({ ...ref })),
17632
+ // 2.6.0: the options as index details show them, and where the index comes from
17633
+ indexes: declared.indexes.map((index) => ({
17634
+ name: index.name,
17635
+ key: { ...index.key },
17636
+ unique: index.options.unique === true,
17637
+ sparse: index.options.sparse === true,
17638
+ origin: index.origin,
17639
+ ...index.options.partialFilterExpression !== void 0 ? { partialFilterExpression: documentToJson(index.options.partialFilterExpression, "relaxed") } : {},
17640
+ ...index.softDeleteFilter === true ? { partialFilterFrom: "softDelete" } : {},
17641
+ ...typeof index.options.expireAfterSeconds === "number" ? { expireAfterSeconds: index.options.expireAfterSeconds } : {}
17642
+ })),
17643
+ // 2.6.0: many is always given (false when neither the schema nor the declaration says an array), and the references to this collection
17644
+ refs: declared.refs.map((ref) => ({ ...ref, many: ref.many ?? false })),
17645
+ referencedBy: referencedBy.map((reference) => ({ ...reference })),
17123
17646
  ...behaviours.timestamps !== void 0 ? { timestamps: { ...behaviours.timestamps } } : {},
17124
17647
  ...behaviours.owner !== void 0 ? { owner: { field: behaviours.owner.field, read: typeof behaviours.owner.read === "function" ? "custom" : behaviours.owner.read } } : {},
17125
17648
  ...behaviours.softDelete !== void 0 ? { softDelete: { ...behaviours.softDelete } } : {},
@@ -17138,30 +17661,31 @@ function parseExportFormat(value) {
17138
17661
  }
17139
17662
  return format;
17140
17663
  }
17141
- function csvCell(value) {
17664
+ const formulaStart = /^[=+\-@\t\r]/;
17665
+ function csvCell(value, escapeFormulas = false) {
17142
17666
  let text;
17143
17667
  if (value === null || value === void 0) {
17144
17668
  text = "";
17145
17669
  } else if (typeof value === "string") {
17146
- text = value;
17670
+ text = escapeFormulas && formulaStart.test(value) ? `'${value}` : value;
17147
17671
  } else {
17148
17672
  text = stringifyJson(value);
17149
17673
  }
17150
17674
  return /[,"\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
17151
17675
  }
17152
- function csvHeader(columns) {
17153
- return `${columns.map(csvCell).join(",")}\r
17676
+ function csvHeader(columns, escapeFormulas = false) {
17677
+ return `${columns.map((column) => csvCell(column, escapeFormulas)).join(",")}\r
17154
17678
  `;
17155
17679
  }
17156
- function csvRow(columns, document) {
17157
- return `${columns.map((column) => csvCell(document[column])).join(",")}\r
17680
+ function csvRow(columns, document, escapeFormulas = false) {
17681
+ return `${columns.map((column) => csvCell(document[column], escapeFormulas)).join(",")}\r
17158
17682
  `;
17159
17683
  }
17160
- async function* renderExport(format, documents, columns) {
17684
+ async function* renderExport(format, documents, columns, escapeFormulas = false) {
17161
17685
  if (format === "csv") {
17162
- yield csvHeader(columns);
17686
+ yield csvHeader(columns, escapeFormulas);
17163
17687
  for await (const document of documents) {
17164
- yield csvRow(columns, document);
17688
+ yield csvRow(columns, document, escapeFormulas);
17165
17689
  }
17166
17690
  return;
17167
17691
  }
@@ -17218,12 +17742,12 @@ async function* converted(cursor, mode, secrets = [], expand) {
17218
17742
  yield* flush();
17219
17743
  }
17220
17744
  }
17221
- function endMarker(format, count) {
17745
+ function endMarker(format, count, capped = false) {
17222
17746
  if (format === "ndjson") {
17223
- return `${stringifyJson({ $end: true, count })}
17747
+ return `${stringifyJson(capped ? { $end: true, count, capped: true } : { $end: true, count })}
17224
17748
  `;
17225
17749
  }
17226
- return format === "csv" ? `# end ${count}\r
17750
+ return format === "csv" ? `# end ${count}${capped ? " capped" : ""}\r
17227
17751
  ` : "";
17228
17752
  }
17229
17753
  function errorMarker(format, error) {
@@ -17235,23 +17759,35 @@ function errorMarker(format, error) {
17235
17759
  return format === "csv" ? `# error ${message.replaceAll(/[\r\n]+/g, " ")}\r
17236
17760
  ` : "";
17237
17761
  }
17762
+ async function* upTo(cursor, cap, onCapped) {
17763
+ let count = 0;
17764
+ for await (const document of cursor) {
17765
+ if (cap !== void 0 && count >= cap) {
17766
+ onCapped();
17767
+ return;
17768
+ }
17769
+ count++;
17770
+ yield document;
17771
+ }
17772
+ }
17238
17773
  function exportStream(cursor, format, columns, options = {}) {
17239
17774
  const encoder = new TextEncoder();
17240
17775
  let count = 0;
17776
+ let capped = false;
17241
17777
  async function* counted() {
17242
- for await (const document of converted(cursor, options.mode, options.secrets, options.expand)) {
17778
+ for await (const document of converted(upTo(cursor, options.cap, () => capped = true), options.mode, options.secrets, options.expand)) {
17243
17779
  count++;
17244
17780
  yield document;
17245
17781
  }
17246
17782
  }
17247
- const pieces = renderExport(format, counted(), columns);
17783
+ const pieces = renderExport(format, counted(), columns, options.escapeFormulas ?? false);
17248
17784
  return new ReadableStream({
17249
17785
  async pull(controller) {
17250
17786
  try {
17251
17787
  const { value, done } = await pieces.next();
17252
17788
  if (done) {
17253
17789
  if (options.trailer) {
17254
- const marker = endMarker(format, count);
17790
+ const marker = endMarker(format, count, capped);
17255
17791
  if (marker) {
17256
17792
  controller.enqueue(encoder.encode(marker));
17257
17793
  }
@@ -17302,7 +17838,7 @@ function mapField(body, field, required = false) {
17302
17838
  if (!isPlainObject(value)) {
17303
17839
  throw MongocampError.decodeFailure("body", `field ${field}`);
17304
17840
  }
17305
- return decodeAny(value);
17841
+ return decodeAnyObject(value, `field ${field}`);
17306
17842
  }
17307
17843
  function expandOf(params, body) {
17308
17844
  const fromQuery = params.getAll("expand").flatMap((value) => value.split(","));
@@ -17337,12 +17873,13 @@ function registerDocumentRoutes(app, context) {
17337
17873
  const pageOf = (collection, result, mode) => pageResponse({ items: result.documents.map((document) => documentToJson(document, mode)), info: result.info }, secretFieldsOf(database, collection));
17338
17874
  const base = "/mongodb/collections/:collectionName/documents";
17339
17875
  const collectionParam = (event) => pathParam(event, "collectionName");
17876
+ const refFields = (collection) => context.collections.refFields(context, collection);
17340
17877
  app.get(base, async (event) => {
17341
17878
  const collection = collectionParam(event);
17342
17879
  const user = await auth.requireCollection(event.req, collection, "read");
17343
17880
  const params = queryParams(event);
17344
17881
  const request = {
17345
- filter: convertFields(filterParameter(params.get("filter"), filterOptions(params, config))),
17882
+ filter: convertFields(filterParameter(params.get("filter"), filterOptions(params, config, refFields(collection)))),
17346
17883
  sort: sortFromList(params.getAll("sort")),
17347
17884
  projection: projectionFromList(params.getAll("projection"))
17348
17885
  };
@@ -17353,7 +17890,7 @@ function registerDocumentRoutes(app, context) {
17353
17890
  const collection = collectionParam(event);
17354
17891
  const user = await auth.requireCollection(event.req, collection, "read");
17355
17892
  const params = queryParams(event);
17356
- const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config)));
17893
+ const filter = convertFields(filterParameter(params.get("filter"), filterOptions(params, config, refFields(collection))));
17357
17894
  return jsonResponse({ count: await service.count(user, collection, filter, withDeletedOf(params, user, collection)) });
17358
17895
  });
17359
17896
  app.post(`${base}/count`, async (event) => {
@@ -17361,7 +17898,7 @@ function registerDocumentRoutes(app, context) {
17361
17898
  const user = await auth.requireCollection(event.req, collection, "read");
17362
17899
  const params = queryParams(event);
17363
17900
  const body = asObject(await readJson(event));
17364
- const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config)));
17901
+ const filter = convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config, refFields(collection))));
17365
17902
  return jsonResponse({ count: await service.count(user, collection, filter, withDeletedOf(params, user, collection)) });
17366
17903
  });
17367
17904
  app.post(`${base}/search`, async (event) => {
@@ -17371,7 +17908,7 @@ function registerDocumentRoutes(app, context) {
17371
17908
  const mode = extendedJsonMode(params);
17372
17909
  const body = asObject(await readJson(event));
17373
17910
  const request = {
17374
- filter: convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config))),
17911
+ filter: convertFields(bodyFilter(optionalString(body, "filter"), filterOptions(params, config, refFields(collection)))),
17375
17912
  sort: sortFromList(stringListField(body, "sort")),
17376
17913
  projection: projectionFromList(stringListField(body, "projection"))
17377
17914
  };
@@ -17438,11 +17975,14 @@ function registerDocumentRoutes(app, context) {
17438
17975
  throw MongocampError.badRequest("limit has to be greater than 0");
17439
17976
  }
17440
17977
  const scoped = await service.exportFilter(user, collection, convertFields(request.filter), withDeletedOf(params, user, collection));
17978
+ const maxDocuments = config.number(ConfigKeys.ExportMaxDocuments);
17979
+ const cap = maxDocuments > 0 && (request.limit === void 0 || request.limit > maxDocuments) ? maxDocuments : void 0;
17441
17980
  const query = {
17442
17981
  filter: scoped.filter,
17443
17982
  sort: sortFromList(request.sort),
17444
17983
  projection: projectionFromList(request.projection),
17445
- limit: request.limit
17984
+ // 2.6.0: one more than the cap, so the end marker can tell that the cap cut the export
17985
+ limit: cap !== void 0 ? cap + 1 : request.limit
17446
17986
  };
17447
17987
  const target = collectionOf(database, collection);
17448
17988
  const secrets = secretFieldsOf(database, collection);
@@ -17456,10 +17996,12 @@ function registerDocumentRoutes(app, context) {
17456
17996
  }
17457
17997
  const trailer = booleanQuery(params, "trailer", false);
17458
17998
  const expand = refs.length > 0 ? (documents) => service.expand(user, documents, refs) : void 0;
17459
- return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer, expand }), {
17999
+ return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer, expand, escapeFormulas: config.boolean(ConfigKeys.ExportCsvEscapeFormulas), cap }), {
17460
18000
  headers: {
17461
18001
  "content-type": "text/plain; charset=UTF-8",
17462
- "content-disposition": `attachment; filename="${exportFileName(collection, format)}"`
18002
+ "content-disposition": `attachment; filename="${exportFileName(collection, format)}"`,
18003
+ // 2.6.0: the cap before the body (a json array has no end marker)
18004
+ ...maxDocuments > 0 ? { "x-export-max-documents": String(maxDocuments) } : {}
17463
18005
  }
17464
18006
  });
17465
18007
  };
@@ -17467,7 +18009,7 @@ function registerDocumentRoutes(app, context) {
17467
18009
  const collection = collectionParam(event);
17468
18010
  const user = await auth.requireCollection(event.req, collection, "read");
17469
18011
  const params = queryParams(event);
17470
- const filter = filterParameter(params.get("filter"), filterOptions(params, config));
18012
+ const filter = filterParameter(params.get("filter"), filterOptions(params, config, refFields(collection)));
17471
18013
  return exportResponse(user, collection, params, { filter, sort: params.getAll("sort"), projection: params.getAll("projection"), limit: intQuery(params, "limit"), expand: expandOf(params) });
17472
18014
  });
17473
18015
  app.post(`${base}/export`, async (event) => {
@@ -17476,7 +18018,7 @@ function registerDocumentRoutes(app, context) {
17476
18018
  const params = queryParams(event);
17477
18019
  const body = asObject(await readJson(event));
17478
18020
  return exportResponse(user, collection, params, {
17479
- filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config)),
18021
+ filter: bodyFilter(optionalString(body, "filter"), filterOptions(params, config, refFields(collection))),
17480
18022
  sort: stringListField(body, "sort"),
17481
18023
  projection: stringListField(body, "projection"),
17482
18024
  limit: optionalInteger$1(body, "limit"),
@@ -17489,7 +18031,7 @@ function registerDocumentRoutes(app, context) {
17489
18031
  const maxBytes = context.config.number(ConfigKeys.ImportMaxBytes);
17490
18032
  const length = Number(event.req.headers.get("content-length") ?? Number.NaN);
17491
18033
  if (Number.isFinite(length) && length > maxBytes) {
17492
- throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413);
18034
+ throw new MongocampError("the body of the request is greater than IMPORT_MAX_BYTES", 413, ErrorCodes.importTooLarge);
17493
18035
  }
17494
18036
  const state = await service.import(user, collection, event.req.body, maxBytes);
17495
18037
  return jsonResponse(state.response);
@@ -17513,16 +18055,16 @@ function registerDocumentRoutes(app, context) {
17513
18055
  const body = asObject(await readJson(event));
17514
18056
  const document = mapField(body, "document", true);
17515
18057
  const params = queryParams(event);
17516
- const filter = manyFilter(params, mapField(body, "filter"), filterOptions(params, config));
18058
+ const filter = manyFilter(params, mapField(body, "filter"), filterOptions(params, config, refFields(collection)));
17517
18059
  return jsonResponse(await service.updateMany(user, collection, filter, convertToOperationMap(convertFields(document))));
17518
18060
  });
17519
18061
  app.delete(`${base}/many/delete`, async (event) => {
17520
18062
  const collection = collectionParam(event);
17521
18063
  const user = await auth.requireCollection(event.req, collection, "write");
17522
- const text = await event.req.text();
17523
- const bodyMap = text.trim() === "" ? {} : decodeAnyObject(parseJsonBody(text));
18064
+ const body = await readOptionalJson(event);
18065
+ const bodyMap = body === void 0 ? {} : decodeAnyObject(body);
17524
18066
  const params = queryParams(event);
17525
- return jsonResponse(await service.removeMany(user, collection, manyFilter(params, bodyMap, filterOptions(params, config))));
18067
+ return jsonResponse(await service.removeMany(user, collection, manyFilter(params, bodyMap, filterOptions(params, config, refFields(collection)))));
17526
18068
  });
17527
18069
  app.post(`${base}/:documentId/restore`, async (event) => {
17528
18070
  const collection = collectionParam(event);
@@ -17536,7 +18078,7 @@ function registerDocumentRoutes(app, context) {
17536
18078
  if (declared === void 0) {
17537
18079
  throw MongocampError.notFound(`the collection ${collection} is not declared`);
17538
18080
  }
17539
- return jsonResponse(declarationInfo(declared));
18081
+ return jsonResponse(declarationInfo(declared, context.collections.referencesTo(context, declared)));
17540
18082
  });
17541
18083
  const auditedOf = (collection) => {
17542
18084
  const declared = context.collections.resolve(context, collection);
@@ -17704,7 +18246,7 @@ function collation(map) {
17704
18246
  if (!("locale" in map)) {
17705
18247
  throw invalid("a collation needs a locale");
17706
18248
  }
17707
- const result = {};
18249
+ const result = { locale: "" };
17708
18250
  const show = (value) => typeof value === "string" ? value : JSON.stringify(legacyValue(value));
17709
18251
  for (const [key, value] of Object.entries(map)) {
17710
18252
  switch (key) {
@@ -17884,8 +18426,8 @@ function registerIndexRoutes(app, context) {
17884
18426
  return collectionOf(database, collection);
17885
18427
  };
17886
18428
  const optionalOptions = async (event) => {
17887
- const text = await event.req.text();
17888
- return text.trim() === "" ? void 0 : readIndexOptions(parseJsonBody(text));
18429
+ const body = await readOptionalJson(event);
18430
+ return body === void 0 ? void 0 : readIndexOptions(body);
17889
18431
  };
17890
18432
  const created = (name) => jsonResponse({ name });
17891
18433
  app.get(base, async (event) => {
@@ -18241,9 +18783,10 @@ class MongocampMetrics {
18241
18783
  }
18242
18784
  }
18243
18785
  listen(client, name, listener) {
18244
- const emitter = client;
18245
- emitter.on(name, listener);
18246
- this.cleanups.push(() => emitter.off(name, listener));
18786
+ client.on(name, listener);
18787
+ this.cleanups.push(() => {
18788
+ client.off(name, listener);
18789
+ });
18247
18790
  }
18248
18791
  eventMetrics() {
18249
18792
  const registers = [this.events];
@@ -18385,22 +18928,48 @@ function registerInformationRoutes(app, context) {
18385
18928
 
18386
18929
  const HeartbeatMillis = 25e3;
18387
18930
  const ChangeStreamHistoryLost = 286;
18931
+ const ChangeStreamProbeRetryMillis = 3e4;
18932
+ const resumeTokenPattern = /^[0-9a-f]{2,2048}$/i;
18388
18933
  async function supportsChangeStreams(context) {
18389
18934
  const hello = await context.database.db().admin().command({ hello: 1 });
18390
18935
  return typeof hello.setName === "string" || hello.msg === "isdbgrid";
18391
18936
  }
18937
+ function changeStreamProbe(probe, now = Date.now) {
18938
+ let cached;
18939
+ return () => {
18940
+ if (cached === void 0) {
18941
+ cached = { result: probe().catch(() => false), at: now() };
18942
+ return cached.result;
18943
+ }
18944
+ const current = cached;
18945
+ return current.result.then((supported) => {
18946
+ if (!supported && now() - current.at >= ChangeStreamProbeRetryMillis && cached === current) {
18947
+ cached = { result: probe().catch(() => false), at: now() };
18948
+ return cached.result;
18949
+ }
18950
+ return supported;
18951
+ });
18952
+ };
18953
+ }
18954
+ const openStreams = /* @__PURE__ */ new WeakMap();
18955
+ async function closeWatches(context) {
18956
+ const open = openStreams.get(context);
18957
+ if (open !== void 0) {
18958
+ await Promise.allSettled([...open].map((close) => close()));
18959
+ }
18960
+ }
18392
18961
  function registerWatchRoutes(app, context) {
18393
18962
  const { auth, database, config } = context;
18394
- let support;
18963
+ const support = changeStreamProbe(() => supportsChangeStreams(context));
18395
18964
  const open = /* @__PURE__ */ new Set();
18965
+ openStreams.set(context, open);
18396
18966
  app.get("/mongodb/collections/:collectionName/documents/watch", async (event) => {
18397
18967
  const collection = pathParam(event, "collectionName");
18398
18968
  const user = await auth.requireCollection(event.req, collection, "read");
18399
18969
  if (isReservedName(collection.split(":").at(-1), config.string(ConfigKeys.AuthPrefix))) {
18400
18970
  throw MongocampError.badRequest("the collection belongs to the server or to a bucket and cannot be watched");
18401
18971
  }
18402
- support ??= supportsChangeStreams(context).catch(() => false);
18403
- if (!await support) {
18972
+ if (!await support()) {
18404
18973
  throw new MongocampError("live updates need a replica set or a sharded cluster (change streams); the client polls instead", 501, ErrorCodes.changeStreamsUnsupported);
18405
18974
  }
18406
18975
  if (open.size >= config.number(ConfigKeys.WatchMaxStreams)) {
@@ -18408,10 +18977,11 @@ function registerWatchRoutes(app, context) {
18408
18977
  }
18409
18978
  const params = queryParams(event);
18410
18979
  const refs = context.documents.refs(collection, params.getAll("expand").flatMap((value) => value.split(",")));
18411
- const scope = await readScope(context, user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config))), "watch");
18980
+ const scope = await readScope(context, user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config, context.collections.refFields(context, collection)))), "watch");
18412
18981
  const target = collectionOf(database, collection);
18413
18982
  const secrets = secretFieldsOf(database, collection);
18414
- const lastEventId = event.req.headers.get("last-event-id");
18983
+ const lastEventId = event.req.headers.get("last-event-id")?.trim() ?? "";
18984
+ const resumable = resumeTokenPattern.test(lastEventId);
18415
18985
  const stream = createEventStream(event);
18416
18986
  let changes;
18417
18987
  let closed = false;
@@ -18454,15 +19024,36 @@ function registerWatchRoutes(app, context) {
18454
19024
  ...resumeAfter !== void 0 ? { resumeAfter: { _data: resumeAfter } } : {}
18455
19025
  });
18456
19026
  let queue = Promise.resolve();
19027
+ let waiting = 0;
19028
+ let overflowed = false;
19029
+ const queueMax = config.number(ConfigKeys.WatchQueueMax);
18457
19030
  changes.on("change", (change) => {
19031
+ if (closed || overflowed) {
19032
+ return;
19033
+ }
19034
+ if (queueMax > 0 && waiting >= queueMax) {
19035
+ overflowed = true;
19036
+ stream.push({ event: "reset", data: "{}" }).catch(() => void 0).finally(() => {
19037
+ close().catch(() => void 0);
19038
+ });
19039
+ return;
19040
+ }
19041
+ waiting++;
18458
19042
  queue = queue.then(async () => {
18459
19043
  const message = closed ? void 0 : await toEvent(change);
18460
19044
  if (message !== void 0 && !closed) {
18461
19045
  await stream.push({ id: change._id._data, event: message.event, data: JSON.stringify(message.data) });
18462
19046
  }
18463
- }).catch(() => close());
19047
+ }).catch(() => close()).finally(() => {
19048
+ waiting--;
19049
+ });
18464
19050
  });
18465
19051
  changes.on("error", (error) => {
19052
+ const badToken = resumeAfter !== void 0 && error instanceof MongoServerError && error.code !== ChangeStreamHistoryLost;
19053
+ if (badToken && !closed) {
19054
+ stream.push({ event: "reset", data: "{}" }).then(() => start()).catch(() => close());
19055
+ return;
19056
+ }
18466
19057
  if (error instanceof MongoServerError && error.code === ChangeStreamHistoryLost && !closed) {
18467
19058
  stream.push({ event: "reset", data: "{}" }).then(() => start()).catch(() => close());
18468
19059
  return;
@@ -18470,7 +19061,10 @@ function registerWatchRoutes(app, context) {
18470
19061
  close().catch(() => void 0);
18471
19062
  });
18472
19063
  };
18473
- start(lastEventId !== null && lastEventId !== "" ? lastEventId : void 0);
19064
+ if (lastEventId !== "" && !resumable) {
19065
+ stream.push({ event: "reset", data: "{}" }).catch(() => close());
19066
+ }
19067
+ start(resumable ? lastEventId : void 0);
18474
19068
  stream.pushComment("open").catch(() => close());
18475
19069
  return stream;
18476
19070
  });
@@ -18588,6 +19182,11 @@ async function systemStats(admin) {
18588
19182
  function capabilityLimits(config) {
18589
19183
  return {
18590
19184
  importMaxBytes: config.number(ConfigKeys.ImportMaxBytes),
19185
+ // 2.6.0: the limits of 2.5 for every user, 0 is no limit
19186
+ bodyMaxBytes: config.number(ConfigKeys.BodyMaxBytes),
19187
+ pagingMaxRows: config.number(ConfigKeys.PagingMaxRows),
19188
+ exportMaxDocuments: config.number(ConfigKeys.ExportMaxDocuments),
19189
+ gridfsUploadMaxBytes: config.number(ConfigKeys.GridfsUploadMaxBytes),
18591
19190
  grantDeniedStatus: config.number(ConfigKeys.AuthGrantDeniedStatus) === 401 ? 401 : 403
18592
19191
  };
18593
19192
  }
@@ -18656,6 +19255,24 @@ function registerConfigurationRoutes(app, context) {
18656
19255
  const updated = await configurations.update(key, decodeAny(body.value));
18657
19256
  return jsonResponse({ value: updated });
18658
19257
  });
19258
+ app.delete("/system/configurations/:configurationKey", async (event) => {
19259
+ await auth.requireAdmin(event.req);
19260
+ const key = pathParam(event, "configurationKey");
19261
+ const definition = config.definition(key);
19262
+ if (!definition) {
19263
+ throw MongocampError.notFound("configuration not found");
19264
+ }
19265
+ if (!definition.persistent) {
19266
+ throw MongocampError.badRequest(`${key} cannot be changed at runtime, it is read at the start only`);
19267
+ }
19268
+ if (config.overrideOf(key) === "env") {
19269
+ throw MongocampError.badRequest(`${key} is set by the environment and cannot be changed`);
19270
+ }
19271
+ if (typeof definition.defaultValue === "function") {
19272
+ throw MongocampError.badRequest(`${key} has a generated default and cannot be reset`);
19273
+ }
19274
+ return jsonResponse({ value: await configurations.reset(key) });
19275
+ });
18659
19276
  app.delete("/system", async (event) => {
18660
19277
  await auth.requireAdmin(event.req);
18661
19278
  const shutdown = context.shutdown;
@@ -18712,11 +19329,22 @@ const routeGroups = [
18712
19329
  registerIndexRoutes,
18713
19330
  registerBucketRoutes
18714
19331
  ];
19332
+ function errorOptions(config, url) {
19333
+ let mode = DefaultExtendedJsonMode;
19334
+ try {
19335
+ mode = parseExtendedJsonMode(url.searchParams.get("extendedJson")) ?? DefaultExtendedJsonMode;
19336
+ } catch {
19337
+ }
19338
+ return { exposeInternal: config.boolean(ConfigKeys.ErrorsExposeInternal), currentIn: (document) => documentToJson(document, mode) };
19339
+ }
18715
19340
  function createApp(context) {
18716
19341
  const app = new H3({
18717
19342
  // errors are answered and logged (5xx) by toErrorResponse
18718
19343
  silent: true,
18719
- onError: (error) => toErrorResponse(error, errorLogger(context.logger))
19344
+ onError: (error, event) => toErrorResponse(error, errorLogger(context.logger), errorOptions(context.config, event.url))
19345
+ });
19346
+ app.use((event) => {
19347
+ event.context.mongocampBodyMaxBytes = context.config.number(ConfigKeys.BodyMaxBytes);
18720
19348
  });
18721
19349
  for (const register of routeGroups) {
18722
19350
  register(app, context);
@@ -18768,6 +19396,7 @@ async function createMongocampServer(options = {}) {
18768
19396
  await database.close();
18769
19397
  throw error;
18770
19398
  }
19399
+ let documents;
18771
19400
  const context = {
18772
19401
  config,
18773
19402
  logger,
@@ -18778,13 +19407,14 @@ async function createMongocampServer(options = {}) {
18778
19407
  events,
18779
19408
  interceptors,
18780
19409
  collections: new CollectionRegistry(),
18781
- // set right below: the service needs the context
18782
- documents: void 0,
19410
+ // created on first use: the service needs the context
19411
+ get documents() {
19412
+ return documents ??= new DocumentService(context);
19413
+ },
18783
19414
  jobs,
18784
19415
  systemInfo: buildInfoCache(database.db()),
18785
19416
  shutdown: options.shutdown
18786
19417
  };
18787
- context.documents = new DocumentService(context);
18788
19418
  const cleanups = [];
18789
19419
  const used = /* @__PURE__ */ new Set();
18790
19420
  const use = async (feature) => {
@@ -18822,7 +19452,7 @@ async function createMongocampServer(options = {}) {
18822
19452
  try {
18823
19453
  response = await app.fetch(request);
18824
19454
  } catch (error) {
18825
- response = toErrorResponse(error, errorLogger(logger));
19455
+ response = toErrorResponse(error, errorLogger(logger), errorOptions(config, new URL(request.url)));
18826
19456
  }
18827
19457
  requestEvents.completed(start, response);
18828
19458
  if (fetchOptions.log) {
@@ -18841,6 +19471,7 @@ async function createMongocampServer(options = {}) {
18841
19471
  collection: (name, collectionOptions) => createServerCollection(context, name, collectionOptions),
18842
19472
  routes: () => app["~routes"].filter((route) => route.route && route.method).map((route) => `${route.method} ${route.route}`),
18843
19473
  close: async () => {
19474
+ await closeWatches(context);
18844
19475
  await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
18845
19476
  jobs.close();
18846
19477
  configurations.close();
@@ -18876,4 +19507,4 @@ async function connectHooks(server, hooks) {
18876
19507
  };
18877
19508
  }
18878
19509
 
18879
- export { AuditCollection, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, JobScheduler, LuceneQueryError, MaxExpands, MongocampError, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf$1 as validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };
19510
+ export { AuditCollection, AuthorizedUser, BehaviourDefaults, CleanUpTokenJob, CleanUpTokenJobClass, CollectionRegistry, ConfigKeys, ConfigStore, ConfigurationError, DefaultRowsPerPage, DefaultValidationMode, DocumentService, ErrorCodes, EventBus, FilterDefaultField, HookPrefix, InternalErrorMessage, JobScheduler, LuceneQueryError, MaxExpands, MongocampError, OwnIndexPrefix, PaginationHeaders, SyncValidationLevel, SystemUser, TextMarker, WriteInterceptors, auditCollectionOf, auditRecords, bsonMarkerOptions, collections, combineScopes, configDefinitions, connectHooks, consoleLogger, convertFields, convertIdValue, createMongocampServer, createServerCollection, decodeAny, defineMongocampCollection, documentToJson, ensureAuditIndexes, filterParameter, forwardEventsToHooks, forwardInterceptorsToHooks, guardedPaths, luceneQueryToFilter, luceneToFilter, metrics, notDeleted, ownedBy, parseExtendedJsonMode, parseJson, parseLuceneQuery, pathIdFilter, purgeIndexName, readScope, refsOf, requestFields, requestLogging, resolveBehaviours, resolveIndexes, resolveRefs, restoreUpdate, sameValidator, stampInsert, stampReplace, stampUpdate, stringifyJson, stripDocument, stripUpdate, syncIndexes, syncPurgeIndex, syncValidator, systemFields, toErrorResponse, toMongoJsonSchema, validatorOf$1 as validatorOf, versionInDocument, versionInUpdate, withDeletedOf, withIncrement, withSystemFields, withVersion };