@sfxcode/mongocamp-server-core 2.4.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +137 -117
- package/dist/index.mjs +362 -174
- 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
|
|
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';
|
|
@@ -479,7 +479,8 @@ const defaultLogger = (error, status) => {
|
|
|
479
479
|
console.error("[mongocamp]", error);
|
|
480
480
|
}
|
|
481
481
|
};
|
|
482
|
-
|
|
482
|
+
const InternalErrorMessage = "internal server error, the log of the server has the details (x-request-id)";
|
|
483
|
+
function toErrorResponse(error, log = defaultLogger, options = {}) {
|
|
483
484
|
const cause = error instanceof HTTPError && error.cause instanceof Error ? error.cause : error;
|
|
484
485
|
if (cause instanceof MongocampError) {
|
|
485
486
|
return errorResponse(cause.status, cause.description);
|
|
@@ -494,7 +495,7 @@ function toErrorResponse(error, log = defaultLogger) {
|
|
|
494
495
|
return errorResponse(cause.status, { code: -1, msg: cause.message, additionalInfo: "" });
|
|
495
496
|
}
|
|
496
497
|
log(cause, 500);
|
|
497
|
-
const message = cause instanceof Error ? cause.message : "Unknown Error";
|
|
498
|
+
const message = !options.exposeInternal ? InternalErrorMessage : cause instanceof Error ? cause.message : "Unknown Error";
|
|
498
499
|
return errorResponse(500, { code: -1, msg: message, additionalInfo: "" });
|
|
499
500
|
}
|
|
500
501
|
|
|
@@ -689,6 +690,7 @@ class JobScheduler {
|
|
|
689
690
|
lastScheduledFireTime: entry.lastRun?.toISOString() ?? null,
|
|
690
691
|
nextScheduledFireTime: next?.toISOString() ?? null,
|
|
691
692
|
scheduleInformation
|
|
693
|
+
// the spec declares these fields optional, the API answers `null` (as the Scala server did): the generated type has no `null`
|
|
692
694
|
};
|
|
693
695
|
}
|
|
694
696
|
list() {
|
|
@@ -878,6 +880,8 @@ const ConfigKeys = {
|
|
|
878
880
|
ServerInterface: "SERVER_INTERFACE",
|
|
879
881
|
ServerPort: "SERVER_PORT",
|
|
880
882
|
AggregationStagesDenied: "AGGREGATION_STAGES_DENIED",
|
|
883
|
+
// new in 2.5.0: operators that run JavaScript on the database server are refused in the filters, projections and updates of clients
|
|
884
|
+
FilterOperatorsDenied: "FILTER_OPERATORS_DENIED",
|
|
881
885
|
AuthHandler: "AUTH_HANDLER",
|
|
882
886
|
AuthSecret: "AUTH_SECRET",
|
|
883
887
|
AuthApiKeyLength: "AUTH_APIKEYLENGTH",
|
|
@@ -887,6 +891,16 @@ const ConfigKeys = {
|
|
|
887
891
|
AuthGrantDeniedStatus: "AUTH_GRANT_DENIED_STATUS",
|
|
888
892
|
ImportMaxBytes: "IMPORT_MAX_BYTES",
|
|
889
893
|
WatchMaxStreams: "WATCH_MAX_STREAMS",
|
|
894
|
+
// 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
|
|
895
|
+
BodyMaxBytes: "BODY_MAX_BYTES",
|
|
896
|
+
PagingMaxRows: "PAGING_MAX_ROWS",
|
|
897
|
+
ExportMaxDocuments: "EXPORT_MAX_DOCUMENTS",
|
|
898
|
+
GridfsUploadMaxBytes: "GRIDFS_UPLOAD_MAX_BYTES",
|
|
899
|
+
WatchQueueMax: "WATCH_QUEUE_MAX",
|
|
900
|
+
// new in 2.5.0: what the answers of the server show (the `server` header, the messages of unexpected errors) and csv formula escaping
|
|
901
|
+
ServerHeaderEnabled: "SERVER_HEADER_ENABLED",
|
|
902
|
+
ErrorsExposeInternal: "ERRORS_EXPOSE_INTERNAL",
|
|
903
|
+
ExportCsvEscapeFormulas: "EXPORT_CSV_ESCAPE_FORMULAS",
|
|
890
904
|
// new in 2.0.0: the time zone of dates without offset in Lucene filters
|
|
891
905
|
FilterTimeZone: "FILTER_TIME_ZONE",
|
|
892
906
|
// new in 2.0.0: drop what the Scala server left in the database at the start (`system/scala-leftovers.ts`)
|
|
@@ -948,6 +962,7 @@ const configDefinitions = [
|
|
|
948
962
|
define(K.ServerInterface, "String", "0.0.0.0", restart),
|
|
949
963
|
define(K.ServerPort, "Long", 8080, restart),
|
|
950
964
|
define(K.AggregationStagesDenied, "List[String]", ["$function", "$accumulator", "$where", "$out", "$merge", "$currentOp", "$listSessions", "$collStats", "$indexStats"]),
|
|
965
|
+
define(K.FilterOperatorsDenied, "List[String]", ["$where", "$function", "$accumulator"]),
|
|
951
966
|
define(K.AuthHandler, "String", "mongo", restart),
|
|
952
967
|
// the Scala server registers a random secret (not the `secret_key` of reference.conf); it is persisted, so it survives restarts
|
|
953
968
|
define(K.AuthSecret, "String", () => randomAlphanumeric$1(32)),
|
|
@@ -960,6 +975,14 @@ const configDefinitions = [
|
|
|
960
975
|
define(K.ImportMaxBytes, "Long", 1073741824),
|
|
961
976
|
// 2.3.0: live updates, change streams open at the same time in one instance (each holds a cursor of the database)
|
|
962
977
|
define(K.WatchMaxStreams, "Long", 100),
|
|
978
|
+
define(K.BodyMaxBytes, "Long", 67108864),
|
|
979
|
+
define(K.PagingMaxRows, "Long", 0),
|
|
980
|
+
define(K.ExportMaxDocuments, "Long", 0),
|
|
981
|
+
define(K.GridfsUploadMaxBytes, "Long", 0),
|
|
982
|
+
define(K.WatchQueueMax, "Long", 1e3),
|
|
983
|
+
define(K.ServerHeaderEnabled, "Boolean", true),
|
|
984
|
+
define(K.ErrorsExposeInternal, "Boolean", false),
|
|
985
|
+
define(K.ExportCsvEscapeFormulas, "Boolean", false),
|
|
963
986
|
define(K.FilterTimeZone, "String", "UTC"),
|
|
964
987
|
define(K.MigrationDropScalaLeftovers, "Boolean", false, nonPersistent),
|
|
965
988
|
define(K.JobsEnabled, "Boolean", true, nonPersistent),
|
|
@@ -1101,6 +1124,9 @@ async function hashPassword(password) {
|
|
|
1101
1124
|
function equalBytes(a, b) {
|
|
1102
1125
|
return a.length === b.length && timingSafeEqual(a, b);
|
|
1103
1126
|
}
|
|
1127
|
+
function sameSecret(a, b) {
|
|
1128
|
+
return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
|
|
1129
|
+
}
|
|
1104
1130
|
async function verifyPassword(password, stored) {
|
|
1105
1131
|
const hash = parsePasswordHash(stored);
|
|
1106
1132
|
if (hash.algorithm === "sha256") {
|
|
@@ -1324,7 +1350,13 @@ class StaticAuthHolder {
|
|
|
1324
1350
|
async upgradePassword() {
|
|
1325
1351
|
}
|
|
1326
1352
|
async findUserByApiKeyOption(apiKey) {
|
|
1327
|
-
|
|
1353
|
+
let found;
|
|
1354
|
+
for (const user of this.users) {
|
|
1355
|
+
if (typeof user.apiKey === "string" && user.apiKey !== "" && sameSecret(user.apiKey, apiKey) && found === void 0) {
|
|
1356
|
+
found = user;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
return found;
|
|
1328
1360
|
}
|
|
1329
1361
|
async findRoles(names) {
|
|
1330
1362
|
return names.flatMap((name) => this.roles.filter((role) => role.name.toLowerCase() === name.toLowerCase()).slice(0, 1));
|
|
@@ -1542,7 +1574,6 @@ const BasicAuthCacheMillis = 6e4;
|
|
|
1542
1574
|
const BasicAuthCacheEntries = 1e3;
|
|
1543
1575
|
class AuthService {
|
|
1544
1576
|
constructor(database, config, version) {
|
|
1545
|
-
this.database = database;
|
|
1546
1577
|
this.config = config;
|
|
1547
1578
|
this.version = version;
|
|
1548
1579
|
this.holder = createAuthHolder(database, config);
|
|
@@ -2263,8 +2294,9 @@ class WriteInterceptors {
|
|
|
2263
2294
|
}
|
|
2264
2295
|
}
|
|
2265
2296
|
|
|
2297
|
+
const { rawJSON } = JSON;
|
|
2266
2298
|
function rawNumber(text) {
|
|
2267
|
-
return
|
|
2299
|
+
return rawJSON(text);
|
|
2268
2300
|
}
|
|
2269
2301
|
const maxLong = 9223372036854775807n;
|
|
2270
2302
|
const minLong = -9223372036854775808n;
|
|
@@ -2346,10 +2378,10 @@ function parseJsonBody(text) {
|
|
|
2346
2378
|
function stringifyJson(value) {
|
|
2347
2379
|
return JSON.stringify(value, (_key, entry) => {
|
|
2348
2380
|
if (typeof entry === "bigint") {
|
|
2349
|
-
return
|
|
2381
|
+
return rawNumber(entry.toString());
|
|
2350
2382
|
}
|
|
2351
2383
|
if (entry instanceof Long) {
|
|
2352
|
-
return
|
|
2384
|
+
return rawNumber(entry.toString());
|
|
2353
2385
|
}
|
|
2354
2386
|
return entry;
|
|
2355
2387
|
});
|
|
@@ -4722,6 +4754,108 @@ async function readLines(collection, body, maxBytes, state, beforeBatch) {
|
|
|
4722
4754
|
}
|
|
4723
4755
|
}
|
|
4724
4756
|
|
|
4757
|
+
function normalizeStage(name) {
|
|
4758
|
+
return name.startsWith("$") ? name : `$${name}`;
|
|
4759
|
+
}
|
|
4760
|
+
function refuseIfDenied(operator, denied) {
|
|
4761
|
+
if (denied.has(operator)) {
|
|
4762
|
+
throw MongocampError.forbidden(`the operator ${operator} is not allowed in an aggregation`, ErrorCodes.forbiddenStage);
|
|
4763
|
+
}
|
|
4764
|
+
}
|
|
4765
|
+
function scan(value, denied) {
|
|
4766
|
+
if (Array.isArray(value)) {
|
|
4767
|
+
value.forEach((entry) => scan(entry, denied));
|
|
4768
|
+
} else if (isPlainObject(value)) {
|
|
4769
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
4770
|
+
refuseIfDenied(key, denied);
|
|
4771
|
+
scan(entry, denied);
|
|
4772
|
+
}
|
|
4773
|
+
}
|
|
4774
|
+
}
|
|
4775
|
+
function checkDeniedFilterOperators(values, deniedOperators) {
|
|
4776
|
+
const denied = new Set(deniedOperators.map(normalizeStage));
|
|
4777
|
+
if (denied.size === 0) {
|
|
4778
|
+
return;
|
|
4779
|
+
}
|
|
4780
|
+
const visit = (value) => {
|
|
4781
|
+
if (Array.isArray(value)) {
|
|
4782
|
+
value.forEach(visit);
|
|
4783
|
+
} else if (isPlainObject(value)) {
|
|
4784
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
4785
|
+
if (denied.has(key)) {
|
|
4786
|
+
throw MongocampError.forbidden(`the operator ${key} is not allowed in a filter`, ErrorCodes.forbiddenStage);
|
|
4787
|
+
}
|
|
4788
|
+
visit(entry);
|
|
4789
|
+
}
|
|
4790
|
+
}
|
|
4791
|
+
};
|
|
4792
|
+
values.forEach(visit);
|
|
4793
|
+
}
|
|
4794
|
+
function checkDeniedOperators(pipeline, deniedOperators) {
|
|
4795
|
+
const denied = new Set(deniedOperators.map(normalizeStage));
|
|
4796
|
+
if (denied.size === 0) {
|
|
4797
|
+
return;
|
|
4798
|
+
}
|
|
4799
|
+
for (const stage of pipeline) {
|
|
4800
|
+
refuseIfDenied(normalizeStage(stage.stage), denied);
|
|
4801
|
+
scan(stage.value, denied);
|
|
4802
|
+
}
|
|
4803
|
+
}
|
|
4804
|
+
function referencedCollections(value) {
|
|
4805
|
+
const fromValue = (from) => {
|
|
4806
|
+
if (typeof from === "string") {
|
|
4807
|
+
return [{ name: from }];
|
|
4808
|
+
}
|
|
4809
|
+
if (isPlainObject(from)) {
|
|
4810
|
+
return [{ unsupported: "a reference to a collection of another database" }];
|
|
4811
|
+
}
|
|
4812
|
+
return [];
|
|
4813
|
+
};
|
|
4814
|
+
if (Array.isArray(value)) {
|
|
4815
|
+
return value.flatMap(referencedCollections);
|
|
4816
|
+
}
|
|
4817
|
+
if (!isPlainObject(value)) {
|
|
4818
|
+
return [];
|
|
4819
|
+
}
|
|
4820
|
+
return Object.entries(value).flatMap(([key, entry]) => {
|
|
4821
|
+
let own = [];
|
|
4822
|
+
if ((key === "$lookup" || key === "$graphLookup") && isPlainObject(entry)) {
|
|
4823
|
+
own = fromValue(entry.from);
|
|
4824
|
+
} else if (key === "$unionWith" && typeof entry === "string") {
|
|
4825
|
+
own = [{ name: entry }];
|
|
4826
|
+
} else if (key === "$unionWith" && isPlainObject(entry)) {
|
|
4827
|
+
own = fromValue(entry.coll);
|
|
4828
|
+
}
|
|
4829
|
+
return [...own, ...referencedCollections(entry)];
|
|
4830
|
+
});
|
|
4831
|
+
}
|
|
4832
|
+
function checkPipeline(user, collection, pipeline, deniedOperators) {
|
|
4833
|
+
checkDeniedOperators(pipeline, deniedOperators);
|
|
4834
|
+
const separator = collection.indexOf(":");
|
|
4835
|
+
const prefix = separator >= 0 ? collection.slice(0, separator + 1) : "";
|
|
4836
|
+
for (const stage of pipeline) {
|
|
4837
|
+
for (const reference of referencedCollections({ [normalizeStage(stage.stage)]: stage.value })) {
|
|
4838
|
+
if ("unsupported" in reference) {
|
|
4839
|
+
throw MongocampError.forbidden(`${reference.unsupported} is not supported in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
|
|
4840
|
+
}
|
|
4841
|
+
if (!user.canRead(prefix + reference.name)) {
|
|
4842
|
+
throw MongocampError.forbidden(`the user is not allowed to read the collection ${reference.name} in an aggregation`, ErrorCodes.forbiddenCollectionInStage);
|
|
4843
|
+
}
|
|
4844
|
+
}
|
|
4845
|
+
}
|
|
4846
|
+
}
|
|
4847
|
+
const firstStageOnly = /* @__PURE__ */ new Set(["$geoNear", "$search", "$searchMeta", "$vectorSearch", "$collStats", "$indexStats", "$documents"]);
|
|
4848
|
+
function checkMatchBefore(pipeline) {
|
|
4849
|
+
const first = pipeline[0];
|
|
4850
|
+
if (first && firstStageOnly.has(normalizeStage(first.stage))) {
|
|
4851
|
+
const stage = normalizeStage(first.stage);
|
|
4852
|
+
throw MongocampError.badRequest(`the filter cannot be combined with a pipeline that starts with ${stage}, put the conditions in the stage itself`, ErrorCodes.filterNotSupported);
|
|
4853
|
+
}
|
|
4854
|
+
}
|
|
4855
|
+
function toBsonPipeline(pipeline) {
|
|
4856
|
+
return pipeline.map((stage) => ({ [normalizeStage(stage.stage)]: stage.value }));
|
|
4857
|
+
}
|
|
4858
|
+
|
|
4725
4859
|
function cursorSort(sort) {
|
|
4726
4860
|
const keys = Object.entries(sort).map(([field, direction]) => [field, Number(direction) < 0 ? -1 : 1]);
|
|
4727
4861
|
return keys.some(([field]) => field === "_id") ? keys : [...keys, ["_id", 1]];
|
|
@@ -5001,6 +5135,15 @@ class DocumentService {
|
|
|
5001
5135
|
}
|
|
5002
5136
|
}
|
|
5003
5137
|
/** The filter with the read scope of the caller. */
|
|
5138
|
+
/** 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. */
|
|
5139
|
+
limited(paging) {
|
|
5140
|
+
const max = this.context.config.number(ConfigKeys.PagingMaxRows);
|
|
5141
|
+
return max > 0 && (paging.rowsPerPage ?? 0) > max ? { ...paging, rowsPerPage: max } : paging;
|
|
5142
|
+
}
|
|
5143
|
+
/** Refuses filters, projections and updates of the caller with an operator of `FILTER_OPERATORS_DENIED` (2.5.0). */
|
|
5144
|
+
checkOperators(...values) {
|
|
5145
|
+
checkDeniedFilterOperators(values, this.context.config.list(ConfigKeys.FilterOperatorsDenied));
|
|
5146
|
+
}
|
|
5004
5147
|
scope(user, collection, filter, operation, options = {}) {
|
|
5005
5148
|
return readScope(this.context, user, collection, filter, operation, options);
|
|
5006
5149
|
}
|
|
@@ -5068,14 +5211,16 @@ class DocumentService {
|
|
|
5068
5211
|
/** A page of documents (list, find, search), with the references of `options.expand` expanded. */
|
|
5069
5212
|
async page(user, collection, request, paging, count = "exact", options = {}) {
|
|
5070
5213
|
this.require(user, collection, "read", options);
|
|
5214
|
+
this.checkOperators(request.filter, request.projection);
|
|
5071
5215
|
const refs = this.refs(collection, options.expand);
|
|
5072
5216
|
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);
|
|
5217
|
+
const page = await readPage(this.collection(collection), { ...request, filter }, this.limited(paging), count);
|
|
5074
5218
|
return refs.length > 0 ? { ...page, documents: await this.expand(user, page.documents, refs) } : page;
|
|
5075
5219
|
}
|
|
5076
5220
|
/** The number of documents of a filter. */
|
|
5077
5221
|
async count(user, collection, filter, options = {}) {
|
|
5078
5222
|
this.require(user, collection, "read", options);
|
|
5223
|
+
this.checkOperators(filter);
|
|
5079
5224
|
return this.collection(collection).countDocuments(await this.scope(user, collection, filter, "count", options));
|
|
5080
5225
|
}
|
|
5081
5226
|
/** 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 +5233,7 @@ class DocumentService {
|
|
|
5088
5233
|
/** The filter of an export with the scope, and the scope alone (for the column sample of a csv export). */
|
|
5089
5234
|
async exportFilter(user, collection, filter, options = {}) {
|
|
5090
5235
|
this.require(user, collection, "read", options);
|
|
5236
|
+
this.checkOperators(filter);
|
|
5091
5237
|
return readScopeParts(this.context, user, collection, filter, "export", options);
|
|
5092
5238
|
}
|
|
5093
5239
|
/** The distinct values of a field, as aggregation results `{ _id, field }`. */
|
|
@@ -5096,7 +5242,7 @@ class DocumentService {
|
|
|
5096
5242
|
const scoped = await this.scope(user, collection, {}, "distinct", options);
|
|
5097
5243
|
const path = `$${field}`;
|
|
5098
5244
|
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);
|
|
5245
|
+
return paginatedAggregation(this.collection(collection), pipeline, true, this.limited(paging), count);
|
|
5100
5246
|
}
|
|
5101
5247
|
/**
|
|
5102
5248
|
* 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 +5252,7 @@ class DocumentService {
|
|
|
5106
5252
|
this.require(user, collection, "read", options);
|
|
5107
5253
|
const scoped = await this.scope(user, collection, {}, "aggregate", options);
|
|
5108
5254
|
const pipeline = [...Object.keys(scoped).length > 0 ? [{ $match: scoped }] : [], ...prefix, ...stages];
|
|
5109
|
-
return paginatedAggregation(this.collection(collection), pipeline, allowDiskUse, paging, count);
|
|
5255
|
+
return paginatedAggregation(this.collection(collection), pipeline, allowDiskUse, this.limited(paging), count);
|
|
5110
5256
|
}
|
|
5111
5257
|
// ----- writes -----
|
|
5112
5258
|
/**
|
|
@@ -5224,6 +5370,7 @@ class DocumentService {
|
|
|
5224
5370
|
/** Changes the document of the path id with an operator update (`$set`, ...). */
|
|
5225
5371
|
async update(user, collection, id, operators) {
|
|
5226
5372
|
this.require(user, collection, "write");
|
|
5373
|
+
this.checkOperators(operators);
|
|
5227
5374
|
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
5375
|
const old = await this.oldValues("document:update", collection, filter);
|
|
5229
5376
|
const result = await this.collection(collection).updateOne(filter, update);
|
|
@@ -5236,6 +5383,7 @@ class DocumentService {
|
|
|
5236
5383
|
/** Changes the documents of a filter (checked by the caller: not empty unless intended). */
|
|
5237
5384
|
async updateMany(user, collection, filter, operators) {
|
|
5238
5385
|
this.require(user, collection, "write");
|
|
5386
|
+
this.checkOperators(filter, operators);
|
|
5239
5387
|
const payload = await this.intercept("document:beforeUpdate", user, collection, { filter: await this.scope(user, collection, filter, "write"), update: operators, many: true });
|
|
5240
5388
|
const old = await this.oldValues("document:update", collection, payload.filter);
|
|
5241
5389
|
const result = await this.collection(collection).updateMany(payload.filter, payload.update);
|
|
@@ -5253,6 +5401,7 @@ class DocumentService {
|
|
|
5253
5401
|
/** Deletes the documents of a filter (checked by the caller). */
|
|
5254
5402
|
async removeMany(user, collection, filter) {
|
|
5255
5403
|
this.require(user, collection, "write");
|
|
5404
|
+
this.checkOperators(filter);
|
|
5256
5405
|
const { filter: scoped, instead } = await this.intercept("document:beforeDelete", user, collection, { filter: await this.scope(user, collection, filter, "write"), many: true });
|
|
5257
5406
|
const old = await this.oldValues("document:delete", collection, scoped);
|
|
5258
5407
|
const result = await this.deleteOrInstead(collection, scoped, true, instead);
|
|
@@ -5277,7 +5426,7 @@ class DocumentService {
|
|
|
5277
5426
|
}
|
|
5278
5427
|
/** The audit records of a filter (a document or the collection), newest first. */
|
|
5279
5428
|
async auditRecords(filter, paging, count = "exact") {
|
|
5280
|
-
return readPage(auditCollectionOf(this.context), { filter, sort: { at: -1, _id: -1 }, projection: {} }, paging, count);
|
|
5429
|
+
return readPage(auditCollectionOf(this.context), { filter, sort: { at: -1, _id: -1 }, projection: {} }, this.limited(paging), count);
|
|
5281
5430
|
}
|
|
5282
5431
|
}
|
|
5283
5432
|
|
|
@@ -6335,7 +6484,8 @@ class Parser {
|
|
|
6335
6484
|
}
|
|
6336
6485
|
const match = quoted ? null : comparison.exec(text);
|
|
6337
6486
|
if (match) {
|
|
6338
|
-
const
|
|
6487
|
+
const operator = match[1];
|
|
6488
|
+
const bound = match[2] ?? "";
|
|
6339
6489
|
switch (operator) {
|
|
6340
6490
|
case ">":
|
|
6341
6491
|
return { type: "range", field, lower: bound, upper: null, includeLower: false, includeUpper: true };
|
|
@@ -6399,6 +6549,9 @@ function bodyFilter(input, options = {}) {
|
|
|
6399
6549
|
|
|
6400
6550
|
const SystemUser = new AuthorizedUser({ userId: "system", password: "", apiKey: null, roles: ["system"] }, [{ name: "system", isAdmin: true, collectionGrants: [] }]);
|
|
6401
6551
|
function idOf(target) {
|
|
6552
|
+
if (isPlainObject(target) && (!("_id" in target) || target._id === void 0 || target._id === null)) {
|
|
6553
|
+
throw new MongocampError("the document has no _id", 400);
|
|
6554
|
+
}
|
|
6402
6555
|
const id = isPlainObject(target) && "_id" in target ? target._id : target;
|
|
6403
6556
|
return id instanceof ObjectId ? id.toHexString() : idToString(id);
|
|
6404
6557
|
}
|
|
@@ -6513,24 +6666,29 @@ function requestOrigin(request) {
|
|
|
6513
6666
|
return origin;
|
|
6514
6667
|
}
|
|
6515
6668
|
const referer = request.headers.get("referer");
|
|
6516
|
-
|
|
6669
|
+
if (!referer) {
|
|
6670
|
+
return void 0;
|
|
6671
|
+
}
|
|
6672
|
+
try {
|
|
6673
|
+
const { origin: refererOrigin } = new URL(referer);
|
|
6674
|
+
return refererOrigin === "null" ? void 0 : refererOrigin;
|
|
6675
|
+
} catch {
|
|
6676
|
+
return void 0;
|
|
6677
|
+
}
|
|
6517
6678
|
}
|
|
6518
6679
|
function corsHeaders(config, origin) {
|
|
6519
6680
|
const allowedOrigins = config.list(ConfigKeys.CorsOriginsAllowed).filter((entry) => entry !== "");
|
|
6520
|
-
|
|
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",
|
|
6681
|
+
const common = {
|
|
6531
6682
|
"access-control-allow-headers": config.list(ConfigKeys.CorsHeadersAllowed).join(","),
|
|
6532
6683
|
"access-control-expose-headers": config.list(ConfigKeys.CorsHeadersExposed).join(",")
|
|
6533
6684
|
};
|
|
6685
|
+
if (allowedOrigins.length === 0) {
|
|
6686
|
+
return { "access-control-allow-origin": "*", ...common };
|
|
6687
|
+
}
|
|
6688
|
+
if (origin !== void 0 && allowedOrigins.includes(origin)) {
|
|
6689
|
+
return { "access-control-allow-origin": origin, "access-control-allow-credentials": "true", "vary": "Origin", ...common };
|
|
6690
|
+
}
|
|
6691
|
+
return { vary: "Origin", ...common };
|
|
6534
6692
|
}
|
|
6535
6693
|
function preflightResponse(request, config) {
|
|
6536
6694
|
return new Response(null, {
|
|
@@ -6548,19 +6706,22 @@ function newRequestId() {
|
|
|
6548
6706
|
function withCommonHeaders(response, request, config, version, requestId) {
|
|
6549
6707
|
const headers = {
|
|
6550
6708
|
...corsHeaders(config, requestOrigin(request)),
|
|
6551
|
-
|
|
6709
|
+
// 2.5.0: SERVER_HEADER_ENABLED=false hides the name and version of the server
|
|
6710
|
+
...config.boolean(ConfigKeys.ServerHeaderEnabled) ? { server: `${version.name}/${version.version}` } : {},
|
|
6552
6711
|
"x-request-id": requestId
|
|
6553
6712
|
};
|
|
6554
|
-
|
|
6713
|
+
const apply = (target) => {
|
|
6555
6714
|
for (const [name, value] of Object.entries(headers)) {
|
|
6556
|
-
|
|
6715
|
+
const existing = name === "vary" ? target.get("vary") : null;
|
|
6716
|
+
target.set(name, existing && !existing.split(",").some((entry) => entry.trim().toLowerCase() === "origin") ? `${existing}, ${value}` : existing ?? value);
|
|
6557
6717
|
}
|
|
6718
|
+
};
|
|
6719
|
+
try {
|
|
6720
|
+
apply(response.headers);
|
|
6558
6721
|
return response;
|
|
6559
6722
|
} catch {
|
|
6560
6723
|
const copy = new Response(response.body, response);
|
|
6561
|
-
|
|
6562
|
-
copy.headers.set(name, value);
|
|
6563
|
-
}
|
|
6724
|
+
apply(copy.headers);
|
|
6564
6725
|
return copy;
|
|
6565
6726
|
}
|
|
6566
6727
|
}
|
|
@@ -6832,8 +6993,11 @@ function optionalInteger$1(body, field) {
|
|
|
6832
6993
|
}
|
|
6833
6994
|
return value;
|
|
6834
6995
|
}
|
|
6996
|
+
function isStringList(value) {
|
|
6997
|
+
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
6998
|
+
}
|
|
6835
6999
|
function stringList(value, field) {
|
|
6836
|
-
if (!
|
|
7000
|
+
if (!isStringList(value)) {
|
|
6837
7001
|
fail(field);
|
|
6838
7002
|
}
|
|
6839
7003
|
return value;
|
|
@@ -6894,22 +7058,15 @@ function readRoleNames(body) {
|
|
|
6894
7058
|
return stringList(body, "body");
|
|
6895
7059
|
}
|
|
6896
7060
|
|
|
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)));
|
|
6906
|
-
}
|
|
6907
|
-
|
|
6908
7061
|
function pathParam(event, name) {
|
|
6909
|
-
|
|
7062
|
+
const value = getRouterParam(event, name, { decode: true });
|
|
7063
|
+
if (value === void 0 || value === "") {
|
|
7064
|
+
throw MongocampError.decodeFailure(`path parameter ${name}`);
|
|
7065
|
+
}
|
|
7066
|
+
return value;
|
|
6910
7067
|
}
|
|
6911
7068
|
function queryParams(event) {
|
|
6912
|
-
return
|
|
7069
|
+
return event.url.searchParams;
|
|
6913
7070
|
}
|
|
6914
7071
|
function intQuery(params, name) {
|
|
6915
7072
|
const raw = params.get(name);
|
|
@@ -6940,12 +7097,55 @@ function filterOptions(params, config) {
|
|
|
6940
7097
|
}
|
|
6941
7098
|
return { caseInsensitive: booleanQuery(params, "filterCaseInsensitive", false), timeZone };
|
|
6942
7099
|
}
|
|
7100
|
+
function tooLarge() {
|
|
7101
|
+
return new MongocampError("the body of the request is greater than BODY_MAX_BYTES", 413);
|
|
7102
|
+
}
|
|
7103
|
+
async function readText(event) {
|
|
7104
|
+
const max = event.context.mongocampBodyMaxBytes ?? 0;
|
|
7105
|
+
if (max <= 0 || event.req.body === null) {
|
|
7106
|
+
return event.req.text();
|
|
7107
|
+
}
|
|
7108
|
+
const declared = Number(event.req.headers.get("content-length") ?? Number.NaN);
|
|
7109
|
+
if (declared > max) {
|
|
7110
|
+
throw tooLarge();
|
|
7111
|
+
}
|
|
7112
|
+
const reader = event.req.body.getReader();
|
|
7113
|
+
const decoder = new TextDecoder();
|
|
7114
|
+
let text = "";
|
|
7115
|
+
let total = 0;
|
|
7116
|
+
for (; ; ) {
|
|
7117
|
+
const { done, value } = await reader.read();
|
|
7118
|
+
if (done) {
|
|
7119
|
+
return text + decoder.decode();
|
|
7120
|
+
}
|
|
7121
|
+
total += value.byteLength;
|
|
7122
|
+
if (total > max) {
|
|
7123
|
+
await reader.cancel().catch(() => void 0);
|
|
7124
|
+
throw tooLarge();
|
|
7125
|
+
}
|
|
7126
|
+
text += decoder.decode(value, { stream: true });
|
|
7127
|
+
}
|
|
7128
|
+
}
|
|
7129
|
+
async function readJson(event) {
|
|
7130
|
+
const text = await readText(event);
|
|
7131
|
+
if (text.trim() === "") {
|
|
7132
|
+
throw MongocampError.decodeFailure("body");
|
|
7133
|
+
}
|
|
7134
|
+
return parseJsonBody(text);
|
|
7135
|
+
}
|
|
7136
|
+
async function readOptionalJson(event) {
|
|
7137
|
+
const text = await readText(event);
|
|
7138
|
+
return text.trim() === "" ? void 0 : parseJsonBody(text);
|
|
7139
|
+
}
|
|
7140
|
+
async function readDocumentBody(event) {
|
|
7141
|
+
return convertFields(decodeAnyObject(await readJson(event)));
|
|
7142
|
+
}
|
|
6943
7143
|
|
|
6944
7144
|
function registerAdminRoutes(app, context) {
|
|
6945
7145
|
const { auth, events } = context;
|
|
6946
7146
|
app.get("/admin/users", async (event) => {
|
|
6947
7147
|
await auth.requireAdmin(event.req);
|
|
6948
|
-
const params =
|
|
7148
|
+
const params = queryParams(event);
|
|
6949
7149
|
const { items, info } = await auth.holder.allUsers(params.get("filter") ?? void 0, readPaging(params));
|
|
6950
7150
|
const profiles = await Promise.all(items.map((user) => auth.profileOf(user)));
|
|
6951
7151
|
return jsonResponse(profiles, { headers: paginationHeaders(info) });
|
|
@@ -6956,7 +7156,7 @@ function registerAdminRoutes(app, context) {
|
|
|
6956
7156
|
});
|
|
6957
7157
|
app.get("/admin/roles", async (event) => {
|
|
6958
7158
|
await auth.requireAdmin(event.req);
|
|
6959
|
-
const params =
|
|
7159
|
+
const params = queryParams(event);
|
|
6960
7160
|
const { items, info } = await auth.holder.allRoles(params.get("filter") ?? void 0, readPaging(params));
|
|
6961
7161
|
return jsonResponse(items, { headers: paginationHeaders(info) });
|
|
6962
7162
|
});
|
|
@@ -7049,89 +7249,6 @@ function registerAdminRoutes(app, context) {
|
|
|
7049
7249
|
});
|
|
7050
7250
|
}
|
|
7051
7251
|
|
|
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
7252
|
function readAggregateRequest(body) {
|
|
7136
7253
|
const object = asObject(body);
|
|
7137
7254
|
if (!Array.isArray(object.pipeline)) {
|
|
@@ -7246,7 +7363,7 @@ function registerAuthRoutes(app, context) {
|
|
|
7246
7363
|
});
|
|
7247
7364
|
app.get("/auth/permissions", async (event) => {
|
|
7248
7365
|
const user = await auth.authenticate(event.req);
|
|
7249
|
-
const collection =
|
|
7366
|
+
const collection = queryParams(event).get("collection");
|
|
7250
7367
|
if (collection !== null) {
|
|
7251
7368
|
return jsonResponse([user.permissionsFor(collection)]);
|
|
7252
7369
|
}
|
|
@@ -7332,12 +7449,13 @@ async function findFile(bucket, id) {
|
|
|
7332
7449
|
function uploadMetadata(text) {
|
|
7333
7450
|
return convertFields(jsonMapParameter(text ?? null));
|
|
7334
7451
|
}
|
|
7335
|
-
async function uploadFile(bucket, request, fileNameOverride) {
|
|
7452
|
+
async function uploadFile(bucket, request, fileNameOverride, maxBytes = 0) {
|
|
7336
7453
|
const contentType = request.headers.get("content-type") ?? "";
|
|
7337
7454
|
if (!contentType.toLowerCase().startsWith("multipart/form-data") || !request.body) {
|
|
7338
7455
|
throw MongocampError.decodeFailure("body", "a multipart/form-data body with the part file is expected");
|
|
7339
7456
|
}
|
|
7340
|
-
const parser = busboy({ headers: { "content-type": contentType } });
|
|
7457
|
+
const parser = busboy({ headers: { "content-type": contentType }, ...maxBytes > 0 ? { limits: { fileSize: maxBytes + 1 } } : {} });
|
|
7458
|
+
let truncated = false;
|
|
7341
7459
|
const id = new ObjectId();
|
|
7342
7460
|
let metadataText;
|
|
7343
7461
|
let uploaded;
|
|
@@ -7354,6 +7472,9 @@ async function uploadFile(bucket, request, fileNameOverride) {
|
|
|
7354
7472
|
}
|
|
7355
7473
|
const fileName = fileNameOverride || info.filename || "file";
|
|
7356
7474
|
metadataWithUpload = metadataText !== void 0;
|
|
7475
|
+
stream.on("limit", () => {
|
|
7476
|
+
truncated = true;
|
|
7477
|
+
});
|
|
7357
7478
|
const target = gridFsBucket(bucket).openUploadStream(fileName, { id, metadata: uploadMetadata(metadataText) });
|
|
7358
7479
|
uploaded = pipeline(stream, target);
|
|
7359
7480
|
uploaded.catch(() => void 0);
|
|
@@ -7367,6 +7488,10 @@ async function uploadFile(bucket, request, fileNameOverride) {
|
|
|
7367
7488
|
throw MongocampError.decodeFailure("body", "the part file is missing");
|
|
7368
7489
|
}
|
|
7369
7490
|
await uploaded;
|
|
7491
|
+
if (truncated) {
|
|
7492
|
+
await deleteFile(bucket, id);
|
|
7493
|
+
throw new MongocampError("the file is greater than GRIDFS_UPLOAD_MAX_BYTES", 413);
|
|
7494
|
+
}
|
|
7370
7495
|
if (!metadataWithUpload && metadataText !== void 0) {
|
|
7371
7496
|
await filesCollection(bucket).updateOne({ _id: id }, { $set: { metadata: uploadMetadata(metadataText) } });
|
|
7372
7497
|
}
|
|
@@ -7426,8 +7551,8 @@ function registerBucketRoutes(app, context) {
|
|
|
7426
7551
|
};
|
|
7427
7552
|
const fileId = (event) => convertIdField(pathParam(event, "fileId"));
|
|
7428
7553
|
const requireExisting = async (bucket, name) => {
|
|
7429
|
-
const
|
|
7430
|
-
const found = await database.db(
|
|
7554
|
+
const files2 = filesCollection(bucket);
|
|
7555
|
+
const found = await database.db(files2.dbName).listCollections({ name: files2.collectionName }, { nameOnly: true }).toArray();
|
|
7431
7556
|
if (found.length === 0) {
|
|
7432
7557
|
throw MongocampError.notFound(`the bucket ${name} does not exist`);
|
|
7433
7558
|
}
|
|
@@ -7460,22 +7585,26 @@ function registerBucketRoutes(app, context) {
|
|
|
7460
7585
|
return jsonResponse({ value: chunks.acknowledged });
|
|
7461
7586
|
});
|
|
7462
7587
|
const filesResponse = (page) => jsonResponse(page.items, { headers: paginationHeaders(page.info) });
|
|
7588
|
+
const files = (bucket, request, params) => {
|
|
7589
|
+
checkDeniedFilterOperators([request.filter, request.projection], config.list(ConfigKeys.FilterOperatorsDenied));
|
|
7590
|
+
return findFiles(bucket, request, readPaging(params), readCountMode(params));
|
|
7591
|
+
};
|
|
7463
7592
|
app.get(`${base}/files`, async (event) => {
|
|
7464
7593
|
const { bucket } = await authorized(event, "read");
|
|
7465
7594
|
const params = queryParams(event);
|
|
7466
7595
|
const request = { filter: jsonMapParameter(params.get("filter")), sort: jsonMapParameter(params.get("sort")), projection: jsonMapParameter(params.get("projection")) };
|
|
7467
|
-
return filesResponse(await
|
|
7596
|
+
return filesResponse(await files(bucket, request, params));
|
|
7468
7597
|
});
|
|
7469
7598
|
app.post(`${base}/files`, async (event) => {
|
|
7470
7599
|
const { bucket } = await authorized(event, "read");
|
|
7471
7600
|
const body = asObject(await readJson(event));
|
|
7472
7601
|
const request = { filter: mapField$1(body, "filter"), sort: mapField$1(body, "sort"), projection: mapField$1(body, "projection") };
|
|
7473
7602
|
const params = queryParams(event);
|
|
7474
|
-
return filesResponse(await
|
|
7603
|
+
return filesResponse(await files(bucket, request, params));
|
|
7475
7604
|
});
|
|
7476
7605
|
app.put(`${base}/files`, async (event) => {
|
|
7477
7606
|
const { bucket, name, user } = await authorized(event, "write");
|
|
7478
|
-
const id = await uploadFile(bucket, event.req, queryParams(event).get("fileName") ?? void 0);
|
|
7607
|
+
const id = await uploadFile(bucket, event.req, queryParams(event).get("fileName") ?? void 0, context.config.number(ConfigKeys.GridfsUploadMaxBytes));
|
|
7479
7608
|
const response = { wasAcknowledged: true, insertedIds: [id.toHexString()] };
|
|
7480
7609
|
events.publish("file:create", { user, bucketName: name, insertResponse: response });
|
|
7481
7610
|
return jsonResponse(response);
|
|
@@ -8379,9 +8508,8 @@ function registerCollectionRoutes(app, context) {
|
|
|
8379
8508
|
app.put("/mongodb/collections/:collectionName", async (event) => {
|
|
8380
8509
|
const collection = collectionParam(event);
|
|
8381
8510
|
const user = await auth.requireCollection(event.req, collection, "administrate");
|
|
8382
|
-
const
|
|
8383
|
-
const
|
|
8384
|
-
const options = parsed === null ? emptyOptions : readCollectionOptions(parsed);
|
|
8511
|
+
const parsed = await readOptionalJson(event);
|
|
8512
|
+
const options = parsed === void 0 ? emptyOptions : readCollectionOptions(parsed);
|
|
8385
8513
|
const name = parseCollectionName(collection);
|
|
8386
8514
|
checkName(name.name, systemPrefix(), "the name of the collection");
|
|
8387
8515
|
checkForCreate(options);
|
|
@@ -17138,30 +17266,31 @@ function parseExportFormat(value) {
|
|
|
17138
17266
|
}
|
|
17139
17267
|
return format;
|
|
17140
17268
|
}
|
|
17141
|
-
|
|
17269
|
+
const formulaStart = /^[=+\-@\t\r]/;
|
|
17270
|
+
function csvCell(value, escapeFormulas = false) {
|
|
17142
17271
|
let text;
|
|
17143
17272
|
if (value === null || value === void 0) {
|
|
17144
17273
|
text = "";
|
|
17145
17274
|
} else if (typeof value === "string") {
|
|
17146
|
-
text = value;
|
|
17275
|
+
text = escapeFormulas && formulaStart.test(value) ? `'${value}` : value;
|
|
17147
17276
|
} else {
|
|
17148
17277
|
text = stringifyJson(value);
|
|
17149
17278
|
}
|
|
17150
17279
|
return /[,"\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
17151
17280
|
}
|
|
17152
|
-
function csvHeader(columns) {
|
|
17153
|
-
return `${columns.map(csvCell).join(",")}\r
|
|
17281
|
+
function csvHeader(columns, escapeFormulas = false) {
|
|
17282
|
+
return `${columns.map((column) => csvCell(column, escapeFormulas)).join(",")}\r
|
|
17154
17283
|
`;
|
|
17155
17284
|
}
|
|
17156
|
-
function csvRow(columns, document) {
|
|
17157
|
-
return `${columns.map((column) => csvCell(document[column])).join(",")}\r
|
|
17285
|
+
function csvRow(columns, document, escapeFormulas = false) {
|
|
17286
|
+
return `${columns.map((column) => csvCell(document[column], escapeFormulas)).join(",")}\r
|
|
17158
17287
|
`;
|
|
17159
17288
|
}
|
|
17160
|
-
async function* renderExport(format, documents, columns) {
|
|
17289
|
+
async function* renderExport(format, documents, columns, escapeFormulas = false) {
|
|
17161
17290
|
if (format === "csv") {
|
|
17162
|
-
yield csvHeader(columns);
|
|
17291
|
+
yield csvHeader(columns, escapeFormulas);
|
|
17163
17292
|
for await (const document of documents) {
|
|
17164
|
-
yield csvRow(columns, document);
|
|
17293
|
+
yield csvRow(columns, document, escapeFormulas);
|
|
17165
17294
|
}
|
|
17166
17295
|
return;
|
|
17167
17296
|
}
|
|
@@ -17244,7 +17373,7 @@ function exportStream(cursor, format, columns, options = {}) {
|
|
|
17244
17373
|
yield document;
|
|
17245
17374
|
}
|
|
17246
17375
|
}
|
|
17247
|
-
const pieces = renderExport(format, counted(), columns);
|
|
17376
|
+
const pieces = renderExport(format, counted(), columns, options.escapeFormulas ?? false);
|
|
17248
17377
|
return new ReadableStream({
|
|
17249
17378
|
async pull(controller) {
|
|
17250
17379
|
try {
|
|
@@ -17302,7 +17431,7 @@ function mapField(body, field, required = false) {
|
|
|
17302
17431
|
if (!isPlainObject(value)) {
|
|
17303
17432
|
throw MongocampError.decodeFailure("body", `field ${field}`);
|
|
17304
17433
|
}
|
|
17305
|
-
return
|
|
17434
|
+
return decodeAnyObject(value, `field ${field}`);
|
|
17306
17435
|
}
|
|
17307
17436
|
function expandOf(params, body) {
|
|
17308
17437
|
const fromQuery = params.getAll("expand").flatMap((value) => value.split(","));
|
|
@@ -17438,11 +17567,12 @@ function registerDocumentRoutes(app, context) {
|
|
|
17438
17567
|
throw MongocampError.badRequest("limit has to be greater than 0");
|
|
17439
17568
|
}
|
|
17440
17569
|
const scoped = await service.exportFilter(user, collection, convertFields(request.filter), withDeletedOf(params, user, collection));
|
|
17570
|
+
const maxDocuments = config.number(ConfigKeys.ExportMaxDocuments);
|
|
17441
17571
|
const query = {
|
|
17442
17572
|
filter: scoped.filter,
|
|
17443
17573
|
sort: sortFromList(request.sort),
|
|
17444
17574
|
projection: projectionFromList(request.projection),
|
|
17445
|
-
limit: request.limit
|
|
17575
|
+
limit: maxDocuments > 0 ? Math.min(request.limit ?? maxDocuments, maxDocuments) : request.limit
|
|
17446
17576
|
};
|
|
17447
17577
|
const target = collectionOf(database, collection);
|
|
17448
17578
|
const secrets = secretFieldsOf(database, collection);
|
|
@@ -17456,7 +17586,7 @@ function registerDocumentRoutes(app, context) {
|
|
|
17456
17586
|
}
|
|
17457
17587
|
const trailer = booleanQuery(params, "trailer", false);
|
|
17458
17588
|
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 }), {
|
|
17589
|
+
return new Response(exportStream(exportCursor(target, query), format, columns, { mode, secrets, trailer, expand, escapeFormulas: config.boolean(ConfigKeys.ExportCsvEscapeFormulas) }), {
|
|
17460
17590
|
headers: {
|
|
17461
17591
|
"content-type": "text/plain; charset=UTF-8",
|
|
17462
17592
|
"content-disposition": `attachment; filename="${exportFileName(collection, format)}"`
|
|
@@ -17519,8 +17649,8 @@ function registerDocumentRoutes(app, context) {
|
|
|
17519
17649
|
app.delete(`${base}/many/delete`, async (event) => {
|
|
17520
17650
|
const collection = collectionParam(event);
|
|
17521
17651
|
const user = await auth.requireCollection(event.req, collection, "write");
|
|
17522
|
-
const
|
|
17523
|
-
const bodyMap =
|
|
17652
|
+
const body = await readOptionalJson(event);
|
|
17653
|
+
const bodyMap = body === void 0 ? {} : decodeAnyObject(body);
|
|
17524
17654
|
const params = queryParams(event);
|
|
17525
17655
|
return jsonResponse(await service.removeMany(user, collection, manyFilter(params, bodyMap, filterOptions(params, config))));
|
|
17526
17656
|
});
|
|
@@ -17704,7 +17834,7 @@ function collation(map) {
|
|
|
17704
17834
|
if (!("locale" in map)) {
|
|
17705
17835
|
throw invalid("a collation needs a locale");
|
|
17706
17836
|
}
|
|
17707
|
-
const result = {};
|
|
17837
|
+
const result = { locale: "" };
|
|
17708
17838
|
const show = (value) => typeof value === "string" ? value : JSON.stringify(legacyValue(value));
|
|
17709
17839
|
for (const [key, value] of Object.entries(map)) {
|
|
17710
17840
|
switch (key) {
|
|
@@ -17884,8 +18014,8 @@ function registerIndexRoutes(app, context) {
|
|
|
17884
18014
|
return collectionOf(database, collection);
|
|
17885
18015
|
};
|
|
17886
18016
|
const optionalOptions = async (event) => {
|
|
17887
|
-
const
|
|
17888
|
-
return
|
|
18017
|
+
const body = await readOptionalJson(event);
|
|
18018
|
+
return body === void 0 ? void 0 : readIndexOptions(body);
|
|
17889
18019
|
};
|
|
17890
18020
|
const created = (name) => jsonResponse({ name });
|
|
17891
18021
|
app.get(base, async (event) => {
|
|
@@ -18241,9 +18371,10 @@ class MongocampMetrics {
|
|
|
18241
18371
|
}
|
|
18242
18372
|
}
|
|
18243
18373
|
listen(client, name, listener) {
|
|
18244
|
-
|
|
18245
|
-
|
|
18246
|
-
|
|
18374
|
+
client.on(name, listener);
|
|
18375
|
+
this.cleanups.push(() => {
|
|
18376
|
+
client.off(name, listener);
|
|
18377
|
+
});
|
|
18247
18378
|
}
|
|
18248
18379
|
eventMetrics() {
|
|
18249
18380
|
const registers = [this.events];
|
|
@@ -18385,22 +18516,48 @@ function registerInformationRoutes(app, context) {
|
|
|
18385
18516
|
|
|
18386
18517
|
const HeartbeatMillis = 25e3;
|
|
18387
18518
|
const ChangeStreamHistoryLost = 286;
|
|
18519
|
+
const ChangeStreamProbeRetryMillis = 3e4;
|
|
18520
|
+
const resumeTokenPattern = /^[0-9a-f]{2,2048}$/i;
|
|
18388
18521
|
async function supportsChangeStreams(context) {
|
|
18389
18522
|
const hello = await context.database.db().admin().command({ hello: 1 });
|
|
18390
18523
|
return typeof hello.setName === "string" || hello.msg === "isdbgrid";
|
|
18391
18524
|
}
|
|
18525
|
+
function changeStreamProbe(probe, now = Date.now) {
|
|
18526
|
+
let cached;
|
|
18527
|
+
return () => {
|
|
18528
|
+
if (cached === void 0) {
|
|
18529
|
+
cached = { result: probe().catch(() => false), at: now() };
|
|
18530
|
+
return cached.result;
|
|
18531
|
+
}
|
|
18532
|
+
const current = cached;
|
|
18533
|
+
return current.result.then((supported) => {
|
|
18534
|
+
if (!supported && now() - current.at >= ChangeStreamProbeRetryMillis && cached === current) {
|
|
18535
|
+
cached = { result: probe().catch(() => false), at: now() };
|
|
18536
|
+
return cached.result;
|
|
18537
|
+
}
|
|
18538
|
+
return supported;
|
|
18539
|
+
});
|
|
18540
|
+
};
|
|
18541
|
+
}
|
|
18542
|
+
const openStreams = /* @__PURE__ */ new WeakMap();
|
|
18543
|
+
async function closeWatches(context) {
|
|
18544
|
+
const open = openStreams.get(context);
|
|
18545
|
+
if (open !== void 0) {
|
|
18546
|
+
await Promise.allSettled([...open].map((close) => close()));
|
|
18547
|
+
}
|
|
18548
|
+
}
|
|
18392
18549
|
function registerWatchRoutes(app, context) {
|
|
18393
18550
|
const { auth, database, config } = context;
|
|
18394
|
-
|
|
18551
|
+
const support = changeStreamProbe(() => supportsChangeStreams(context));
|
|
18395
18552
|
const open = /* @__PURE__ */ new Set();
|
|
18553
|
+
openStreams.set(context, open);
|
|
18396
18554
|
app.get("/mongodb/collections/:collectionName/documents/watch", async (event) => {
|
|
18397
18555
|
const collection = pathParam(event, "collectionName");
|
|
18398
18556
|
const user = await auth.requireCollection(event.req, collection, "read");
|
|
18399
18557
|
if (isReservedName(collection.split(":").at(-1), config.string(ConfigKeys.AuthPrefix))) {
|
|
18400
18558
|
throw MongocampError.badRequest("the collection belongs to the server or to a bucket and cannot be watched");
|
|
18401
18559
|
}
|
|
18402
|
-
|
|
18403
|
-
if (!await support) {
|
|
18560
|
+
if (!await support()) {
|
|
18404
18561
|
throw new MongocampError("live updates need a replica set or a sharded cluster (change streams); the client polls instead", 501, ErrorCodes.changeStreamsUnsupported);
|
|
18405
18562
|
}
|
|
18406
18563
|
if (open.size >= config.number(ConfigKeys.WatchMaxStreams)) {
|
|
@@ -18411,7 +18568,8 @@ function registerWatchRoutes(app, context) {
|
|
|
18411
18568
|
const scope = await readScope(context, user, collection, convertFields(filterParameter(params.get("filter"), filterOptions(params, config))), "watch");
|
|
18412
18569
|
const target = collectionOf(database, collection);
|
|
18413
18570
|
const secrets = secretFieldsOf(database, collection);
|
|
18414
|
-
const lastEventId = event.req.headers.get("last-event-id");
|
|
18571
|
+
const lastEventId = event.req.headers.get("last-event-id")?.trim() ?? "";
|
|
18572
|
+
const resumable = resumeTokenPattern.test(lastEventId);
|
|
18415
18573
|
const stream = createEventStream(event);
|
|
18416
18574
|
let changes;
|
|
18417
18575
|
let closed = false;
|
|
@@ -18454,15 +18612,36 @@ function registerWatchRoutes(app, context) {
|
|
|
18454
18612
|
...resumeAfter !== void 0 ? { resumeAfter: { _data: resumeAfter } } : {}
|
|
18455
18613
|
});
|
|
18456
18614
|
let queue = Promise.resolve();
|
|
18615
|
+
let waiting = 0;
|
|
18616
|
+
let overflowed = false;
|
|
18617
|
+
const queueMax = config.number(ConfigKeys.WatchQueueMax);
|
|
18457
18618
|
changes.on("change", (change) => {
|
|
18619
|
+
if (closed || overflowed) {
|
|
18620
|
+
return;
|
|
18621
|
+
}
|
|
18622
|
+
if (queueMax > 0 && waiting >= queueMax) {
|
|
18623
|
+
overflowed = true;
|
|
18624
|
+
stream.push({ event: "reset", data: "{}" }).catch(() => void 0).finally(() => {
|
|
18625
|
+
close().catch(() => void 0);
|
|
18626
|
+
});
|
|
18627
|
+
return;
|
|
18628
|
+
}
|
|
18629
|
+
waiting++;
|
|
18458
18630
|
queue = queue.then(async () => {
|
|
18459
18631
|
const message = closed ? void 0 : await toEvent(change);
|
|
18460
18632
|
if (message !== void 0 && !closed) {
|
|
18461
18633
|
await stream.push({ id: change._id._data, event: message.event, data: JSON.stringify(message.data) });
|
|
18462
18634
|
}
|
|
18463
|
-
}).catch(() => close())
|
|
18635
|
+
}).catch(() => close()).finally(() => {
|
|
18636
|
+
waiting--;
|
|
18637
|
+
});
|
|
18464
18638
|
});
|
|
18465
18639
|
changes.on("error", (error) => {
|
|
18640
|
+
const badToken = resumeAfter !== void 0 && error instanceof MongoServerError && error.code !== ChangeStreamHistoryLost;
|
|
18641
|
+
if (badToken && !closed) {
|
|
18642
|
+
stream.push({ event: "reset", data: "{}" }).then(() => start()).catch(() => close());
|
|
18643
|
+
return;
|
|
18644
|
+
}
|
|
18466
18645
|
if (error instanceof MongoServerError && error.code === ChangeStreamHistoryLost && !closed) {
|
|
18467
18646
|
stream.push({ event: "reset", data: "{}" }).then(() => start()).catch(() => close());
|
|
18468
18647
|
return;
|
|
@@ -18470,7 +18649,10 @@ function registerWatchRoutes(app, context) {
|
|
|
18470
18649
|
close().catch(() => void 0);
|
|
18471
18650
|
});
|
|
18472
18651
|
};
|
|
18473
|
-
|
|
18652
|
+
if (lastEventId !== "" && !resumable) {
|
|
18653
|
+
stream.push({ event: "reset", data: "{}" }).catch(() => close());
|
|
18654
|
+
}
|
|
18655
|
+
start(resumable ? lastEventId : void 0);
|
|
18474
18656
|
stream.pushComment("open").catch(() => close());
|
|
18475
18657
|
return stream;
|
|
18476
18658
|
});
|
|
@@ -18716,7 +18898,10 @@ function createApp(context) {
|
|
|
18716
18898
|
const app = new H3({
|
|
18717
18899
|
// errors are answered and logged (5xx) by toErrorResponse
|
|
18718
18900
|
silent: true,
|
|
18719
|
-
onError: (error) => toErrorResponse(error, errorLogger(context.logger))
|
|
18901
|
+
onError: (error) => toErrorResponse(error, errorLogger(context.logger), { exposeInternal: context.config.boolean(ConfigKeys.ErrorsExposeInternal) })
|
|
18902
|
+
});
|
|
18903
|
+
app.use((event) => {
|
|
18904
|
+
event.context.mongocampBodyMaxBytes = context.config.number(ConfigKeys.BodyMaxBytes);
|
|
18720
18905
|
});
|
|
18721
18906
|
for (const register of routeGroups) {
|
|
18722
18907
|
register(app, context);
|
|
@@ -18768,6 +18953,7 @@ async function createMongocampServer(options = {}) {
|
|
|
18768
18953
|
await database.close();
|
|
18769
18954
|
throw error;
|
|
18770
18955
|
}
|
|
18956
|
+
let documents;
|
|
18771
18957
|
const context = {
|
|
18772
18958
|
config,
|
|
18773
18959
|
logger,
|
|
@@ -18778,13 +18964,14 @@ async function createMongocampServer(options = {}) {
|
|
|
18778
18964
|
events,
|
|
18779
18965
|
interceptors,
|
|
18780
18966
|
collections: new CollectionRegistry(),
|
|
18781
|
-
//
|
|
18782
|
-
documents
|
|
18967
|
+
// created on first use: the service needs the context
|
|
18968
|
+
get documents() {
|
|
18969
|
+
return documents ??= new DocumentService(context);
|
|
18970
|
+
},
|
|
18783
18971
|
jobs,
|
|
18784
18972
|
systemInfo: buildInfoCache(database.db()),
|
|
18785
18973
|
shutdown: options.shutdown
|
|
18786
18974
|
};
|
|
18787
|
-
context.documents = new DocumentService(context);
|
|
18788
18975
|
const cleanups = [];
|
|
18789
18976
|
const used = /* @__PURE__ */ new Set();
|
|
18790
18977
|
const use = async (feature) => {
|
|
@@ -18822,7 +19009,7 @@ async function createMongocampServer(options = {}) {
|
|
|
18822
19009
|
try {
|
|
18823
19010
|
response = await app.fetch(request);
|
|
18824
19011
|
} catch (error) {
|
|
18825
|
-
response = toErrorResponse(error, errorLogger(logger));
|
|
19012
|
+
response = toErrorResponse(error, errorLogger(logger), { exposeInternal: config.boolean(ConfigKeys.ErrorsExposeInternal) });
|
|
18826
19013
|
}
|
|
18827
19014
|
requestEvents.completed(start, response);
|
|
18828
19015
|
if (fetchOptions.log) {
|
|
@@ -18841,6 +19028,7 @@ async function createMongocampServer(options = {}) {
|
|
|
18841
19028
|
collection: (name, collectionOptions) => createServerCollection(context, name, collectionOptions),
|
|
18842
19029
|
routes: () => app["~routes"].filter((route) => route.route && route.method).map((route) => `${route.method} ${route.route}`),
|
|
18843
19030
|
close: async () => {
|
|
19031
|
+
await closeWatches(context);
|
|
18844
19032
|
await Promise.allSettled(cleanups.map((cleanup) => cleanup()));
|
|
18845
19033
|
jobs.close();
|
|
18846
19034
|
configurations.close();
|
|
@@ -18876,4 +19064,4 @@ async function connectHooks(server, hooks) {
|
|
|
18876
19064
|
};
|
|
18877
19065
|
}
|
|
18878
19066
|
|
|
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 };
|
|
19067
|
+
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 };
|