@caprogramacion/mongo-call 0.0.0-stage → 1.1.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/README.md +194 -2
- package/dist/client/index.cjs +113 -0
- package/dist/client/index.d.cts +26 -0
- package/dist/client/index.d.ts +26 -0
- package/dist/client/index.js +90 -0
- package/dist/server/index.d.ts +265 -0
- package/dist/server/index.js +2094 -0
- package/package.json +60 -3
|
@@ -0,0 +1,2094 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
8
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
9
|
+
}) : x)(function(x) {
|
|
10
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
11
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
12
|
+
});
|
|
13
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
14
|
+
try {
|
|
15
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
16
|
+
} catch (e) {
|
|
17
|
+
throw mod = 0, e;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var __copyProps = (to, from, except, desc) => {
|
|
21
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
22
|
+
for (let key of __getOwnPropNames(from))
|
|
23
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
24
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
25
|
+
}
|
|
26
|
+
return to;
|
|
27
|
+
};
|
|
28
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
29
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
30
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
31
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
32
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
33
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
34
|
+
mod
|
|
35
|
+
));
|
|
36
|
+
|
|
37
|
+
// node_modules/.pnpm/@phc+format@1.0.0/node_modules/@phc/format/index.js
|
|
38
|
+
var require_format = __commonJS({
|
|
39
|
+
"node_modules/.pnpm/@phc+format@1.0.0/node_modules/@phc/format/index.js"(exports, module) {
|
|
40
|
+
"use strict";
|
|
41
|
+
var idRegex = /^[a-z0-9-]{1,32}$/;
|
|
42
|
+
var nameRegex = /^[a-z0-9-]{1,32}$/;
|
|
43
|
+
var valueRegex = /^[a-zA-Z0-9/+.-]+$/;
|
|
44
|
+
var b64Regex = /^([a-zA-Z0-9/+.-]+|)$/;
|
|
45
|
+
var decimalRegex = /^((-)?[1-9]\d*|0)$/;
|
|
46
|
+
var versionRegex = /^v=(\d+)$/;
|
|
47
|
+
function objToKeyVal(obj) {
|
|
48
|
+
return objectKeys(obj).map((k) => [k, obj[k]].join("=")).join(",");
|
|
49
|
+
}
|
|
50
|
+
function keyValtoObj(str) {
|
|
51
|
+
const obj = {};
|
|
52
|
+
str.split(",").forEach((ps) => {
|
|
53
|
+
const pss = ps.split("=");
|
|
54
|
+
if (pss.length < 2) {
|
|
55
|
+
throw new TypeError(`params must be in the format name=value`);
|
|
56
|
+
}
|
|
57
|
+
obj[pss.shift()] = pss.join("=");
|
|
58
|
+
});
|
|
59
|
+
return obj;
|
|
60
|
+
}
|
|
61
|
+
function objectKeys(object) {
|
|
62
|
+
return Object.keys(object);
|
|
63
|
+
}
|
|
64
|
+
function objectValues(object) {
|
|
65
|
+
if (typeof Object.values === "function") return Object.values(object);
|
|
66
|
+
return objectKeys(object).map((k) => object[k]);
|
|
67
|
+
}
|
|
68
|
+
function serialize(opts) {
|
|
69
|
+
const fields = [""];
|
|
70
|
+
if (typeof opts !== "object" || opts === null) {
|
|
71
|
+
throw new TypeError("opts must be an object");
|
|
72
|
+
}
|
|
73
|
+
if (typeof opts.id !== "string") {
|
|
74
|
+
throw new TypeError("id must be a string");
|
|
75
|
+
}
|
|
76
|
+
if (!idRegex.test(opts.id)) {
|
|
77
|
+
throw new TypeError(`id must satisfy ${idRegex}`);
|
|
78
|
+
}
|
|
79
|
+
fields.push(opts.id);
|
|
80
|
+
if (typeof opts.version !== "undefined") {
|
|
81
|
+
if (typeof opts.version !== "number" || opts.version < 0 || !Number.isInteger(opts.version)) {
|
|
82
|
+
throw new TypeError("version must be a positive integer number");
|
|
83
|
+
}
|
|
84
|
+
fields.push(`v=${opts.version}`);
|
|
85
|
+
}
|
|
86
|
+
if (typeof opts.params !== "undefined") {
|
|
87
|
+
if (typeof opts.params !== "object" || opts.params === null) {
|
|
88
|
+
throw new TypeError("params must be an object");
|
|
89
|
+
}
|
|
90
|
+
const pk = objectKeys(opts.params);
|
|
91
|
+
if (!pk.every((p) => nameRegex.test(p))) {
|
|
92
|
+
throw new TypeError(`params names must satisfy ${nameRegex}`);
|
|
93
|
+
}
|
|
94
|
+
pk.forEach((k) => {
|
|
95
|
+
if (typeof opts.params[k] === "number") {
|
|
96
|
+
opts.params[k] = opts.params[k].toString();
|
|
97
|
+
} else if (Buffer.isBuffer(opts.params[k])) {
|
|
98
|
+
opts.params[k] = opts.params[k].toString("base64").split("=")[0];
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
const pv = objectValues(opts.params);
|
|
102
|
+
if (!pv.every((v) => typeof v === "string")) {
|
|
103
|
+
throw new TypeError("params values must be strings");
|
|
104
|
+
}
|
|
105
|
+
if (!pv.every((v) => valueRegex.test(v))) {
|
|
106
|
+
throw new TypeError(`params values must satisfy ${valueRegex}`);
|
|
107
|
+
}
|
|
108
|
+
const strpar = objToKeyVal(opts.params);
|
|
109
|
+
fields.push(strpar);
|
|
110
|
+
}
|
|
111
|
+
if (typeof opts.salt !== "undefined") {
|
|
112
|
+
if (!Buffer.isBuffer(opts.salt)) {
|
|
113
|
+
throw new TypeError("salt must be a Buffer");
|
|
114
|
+
}
|
|
115
|
+
fields.push(opts.salt.toString("base64").split("=")[0]);
|
|
116
|
+
if (typeof opts.hash !== "undefined") {
|
|
117
|
+
if (!Buffer.isBuffer(opts.hash)) {
|
|
118
|
+
throw new TypeError("hash must be a Buffer");
|
|
119
|
+
}
|
|
120
|
+
fields.push(opts.hash.toString("base64").split("=")[0]);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const phcstr = fields.join("$");
|
|
124
|
+
return phcstr;
|
|
125
|
+
}
|
|
126
|
+
function deserialize(phcstr) {
|
|
127
|
+
if (typeof phcstr !== "string" || phcstr === "") {
|
|
128
|
+
throw new TypeError("pchstr must be a non-empty string");
|
|
129
|
+
}
|
|
130
|
+
if (phcstr[0] !== "$") {
|
|
131
|
+
throw new TypeError("pchstr must contain a $ as first char");
|
|
132
|
+
}
|
|
133
|
+
const fields = phcstr.split("$");
|
|
134
|
+
fields.shift();
|
|
135
|
+
let maxf = 5;
|
|
136
|
+
if (!versionRegex.test(fields[1])) maxf--;
|
|
137
|
+
if (fields.length > maxf) {
|
|
138
|
+
throw new TypeError(
|
|
139
|
+
`pchstr contains too many fileds: ${fields.length}/${maxf}`
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
const id = fields.shift();
|
|
143
|
+
if (!idRegex.test(id)) {
|
|
144
|
+
throw new TypeError(`id must satisfy ${idRegex}`);
|
|
145
|
+
}
|
|
146
|
+
let version;
|
|
147
|
+
if (versionRegex.test(fields[0])) {
|
|
148
|
+
version = parseInt(fields.shift().match(versionRegex)[1], 10);
|
|
149
|
+
}
|
|
150
|
+
let hash;
|
|
151
|
+
let salt;
|
|
152
|
+
if (b64Regex.test(fields[fields.length - 1])) {
|
|
153
|
+
if (fields.length > 1 && b64Regex.test(fields[fields.length - 2])) {
|
|
154
|
+
hash = Buffer.from(fields.pop(), "base64");
|
|
155
|
+
salt = Buffer.from(fields.pop(), "base64");
|
|
156
|
+
} else {
|
|
157
|
+
salt = Buffer.from(fields.pop(), "base64");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
let params;
|
|
161
|
+
if (fields.length > 0) {
|
|
162
|
+
const parstr = fields.pop();
|
|
163
|
+
params = keyValtoObj(parstr);
|
|
164
|
+
if (!objectKeys(params).every((p) => nameRegex.test(p))) {
|
|
165
|
+
throw new TypeError(`params names must satisfy ${nameRegex}`);
|
|
166
|
+
}
|
|
167
|
+
const pv = objectValues(params);
|
|
168
|
+
if (!pv.every((v) => valueRegex.test(v))) {
|
|
169
|
+
throw new TypeError(`params values must satisfy ${valueRegex}`);
|
|
170
|
+
}
|
|
171
|
+
const pk = objectKeys(params);
|
|
172
|
+
pk.forEach((k) => {
|
|
173
|
+
params[k] = decimalRegex.test(params[k]) ? parseInt(params[k], 10) : params[k];
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
if (fields.length > 0) {
|
|
177
|
+
throw new TypeError(`pchstr contains unrecognized fileds: ${fields}`);
|
|
178
|
+
}
|
|
179
|
+
const phcobj = { id };
|
|
180
|
+
if (version) phcobj.version = version;
|
|
181
|
+
if (params) phcobj.params = params;
|
|
182
|
+
if (salt) phcobj.salt = salt;
|
|
183
|
+
if (hash) phcobj.hash = hash;
|
|
184
|
+
return phcobj;
|
|
185
|
+
}
|
|
186
|
+
module.exports = {
|
|
187
|
+
serialize,
|
|
188
|
+
deserialize
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js
|
|
194
|
+
var require_node_gyp_build = __commonJS({
|
|
195
|
+
"node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports, module) {
|
|
196
|
+
"use strict";
|
|
197
|
+
var fs = __require("fs");
|
|
198
|
+
var path = __require("path");
|
|
199
|
+
var os = __require("os");
|
|
200
|
+
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
201
|
+
var vars = process.config && process.config.variables || {};
|
|
202
|
+
var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
|
|
203
|
+
var abi = process.versions.modules;
|
|
204
|
+
var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
|
|
205
|
+
var arch = process.env.npm_config_arch || os.arch();
|
|
206
|
+
var platform = process.env.npm_config_platform || os.platform();
|
|
207
|
+
var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
|
|
208
|
+
var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
|
|
209
|
+
var uv = (process.versions.uv || "").split(".")[0];
|
|
210
|
+
module.exports = load;
|
|
211
|
+
function load(dir) {
|
|
212
|
+
return runtimeRequire(load.resolve(dir));
|
|
213
|
+
}
|
|
214
|
+
load.resolve = load.path = function(dir) {
|
|
215
|
+
dir = path.resolve(dir || ".");
|
|
216
|
+
try {
|
|
217
|
+
var name = runtimeRequire(path.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
|
|
218
|
+
if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
|
|
219
|
+
} catch (err) {
|
|
220
|
+
}
|
|
221
|
+
if (!prebuildsOnly) {
|
|
222
|
+
var release = getFirst(path.join(dir, "build/Release"), matchBuild);
|
|
223
|
+
if (release) return release;
|
|
224
|
+
var debug = getFirst(path.join(dir, "build/Debug"), matchBuild);
|
|
225
|
+
if (debug) return debug;
|
|
226
|
+
}
|
|
227
|
+
var prebuild = resolve(dir);
|
|
228
|
+
if (prebuild) return prebuild;
|
|
229
|
+
var nearby = resolve(path.dirname(process.execPath));
|
|
230
|
+
if (nearby) return nearby;
|
|
231
|
+
var target = [
|
|
232
|
+
"platform=" + platform,
|
|
233
|
+
"arch=" + arch,
|
|
234
|
+
"runtime=" + runtime,
|
|
235
|
+
"abi=" + abi,
|
|
236
|
+
"uv=" + uv,
|
|
237
|
+
armv ? "armv=" + armv : "",
|
|
238
|
+
"libc=" + libc,
|
|
239
|
+
"node=" + process.versions.node,
|
|
240
|
+
process.versions.electron ? "electron=" + process.versions.electron : "",
|
|
241
|
+
typeof __webpack_require__ === "function" ? "webpack=true" : ""
|
|
242
|
+
// eslint-disable-line
|
|
243
|
+
].filter(Boolean).join(" ");
|
|
244
|
+
throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
|
|
245
|
+
function resolve(dir2) {
|
|
246
|
+
var tuples = readdirSync(path.join(dir2, "prebuilds")).map(parseTuple);
|
|
247
|
+
var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
|
|
248
|
+
if (!tuple) return;
|
|
249
|
+
var prebuilds = path.join(dir2, "prebuilds", tuple.name);
|
|
250
|
+
var parsed = readdirSync(prebuilds).map(parseTags);
|
|
251
|
+
var candidates = parsed.filter(matchTags(runtime, abi));
|
|
252
|
+
var winner = candidates.sort(compareTags(runtime))[0];
|
|
253
|
+
if (winner) return path.join(prebuilds, winner.file);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
function readdirSync(dir) {
|
|
257
|
+
try {
|
|
258
|
+
return fs.readdirSync(dir);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function getFirst(dir, filter) {
|
|
264
|
+
var files = readdirSync(dir).filter(filter);
|
|
265
|
+
return files[0] && path.join(dir, files[0]);
|
|
266
|
+
}
|
|
267
|
+
function matchBuild(name) {
|
|
268
|
+
return /\.node$/.test(name);
|
|
269
|
+
}
|
|
270
|
+
function parseTuple(name) {
|
|
271
|
+
var arr = name.split("-");
|
|
272
|
+
if (arr.length !== 2) return;
|
|
273
|
+
var platform2 = arr[0];
|
|
274
|
+
var architectures = arr[1].split("+");
|
|
275
|
+
if (!platform2) return;
|
|
276
|
+
if (!architectures.length) return;
|
|
277
|
+
if (!architectures.every(Boolean)) return;
|
|
278
|
+
return { name, platform: platform2, architectures };
|
|
279
|
+
}
|
|
280
|
+
function matchTuple(platform2, arch2) {
|
|
281
|
+
return function(tuple) {
|
|
282
|
+
if (tuple == null) return false;
|
|
283
|
+
if (tuple.platform !== platform2) return false;
|
|
284
|
+
return tuple.architectures.includes(arch2);
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function compareTuples(a, b) {
|
|
288
|
+
return a.architectures.length - b.architectures.length;
|
|
289
|
+
}
|
|
290
|
+
function parseTags(file) {
|
|
291
|
+
var arr = file.split(".");
|
|
292
|
+
var extension = arr.pop();
|
|
293
|
+
var tags = { file, specificity: 0 };
|
|
294
|
+
if (extension !== "node") return;
|
|
295
|
+
for (var i = 0; i < arr.length; i++) {
|
|
296
|
+
var tag = arr[i];
|
|
297
|
+
if (tag === "node" || tag === "electron" || tag === "node-webkit") {
|
|
298
|
+
tags.runtime = tag;
|
|
299
|
+
} else if (tag === "napi") {
|
|
300
|
+
tags.napi = true;
|
|
301
|
+
} else if (tag.slice(0, 3) === "abi") {
|
|
302
|
+
tags.abi = tag.slice(3);
|
|
303
|
+
} else if (tag.slice(0, 2) === "uv") {
|
|
304
|
+
tags.uv = tag.slice(2);
|
|
305
|
+
} else if (tag.slice(0, 4) === "armv") {
|
|
306
|
+
tags.armv = tag.slice(4);
|
|
307
|
+
} else if (tag === "glibc" || tag === "musl") {
|
|
308
|
+
tags.libc = tag;
|
|
309
|
+
} else {
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
tags.specificity++;
|
|
313
|
+
}
|
|
314
|
+
return tags;
|
|
315
|
+
}
|
|
316
|
+
function matchTags(runtime2, abi2) {
|
|
317
|
+
return function(tags) {
|
|
318
|
+
if (tags == null) return false;
|
|
319
|
+
if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
|
|
320
|
+
if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
|
|
321
|
+
if (tags.uv && tags.uv !== uv) return false;
|
|
322
|
+
if (tags.armv && tags.armv !== armv) return false;
|
|
323
|
+
if (tags.libc && tags.libc !== libc) return false;
|
|
324
|
+
return true;
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
function runtimeAgnostic(tags) {
|
|
328
|
+
return tags.runtime === "node" && tags.napi;
|
|
329
|
+
}
|
|
330
|
+
function compareTags(runtime2) {
|
|
331
|
+
return function(a, b) {
|
|
332
|
+
if (a.runtime !== b.runtime) {
|
|
333
|
+
return a.runtime === runtime2 ? -1 : 1;
|
|
334
|
+
} else if (a.abi !== b.abi) {
|
|
335
|
+
return a.abi ? -1 : 1;
|
|
336
|
+
} else if (a.specificity !== b.specificity) {
|
|
337
|
+
return a.specificity > b.specificity ? -1 : 1;
|
|
338
|
+
} else {
|
|
339
|
+
return 0;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
function isNwjs() {
|
|
344
|
+
return !!(process.versions && process.versions.nw);
|
|
345
|
+
}
|
|
346
|
+
function isElectron() {
|
|
347
|
+
if (process.versions && process.versions.electron) return true;
|
|
348
|
+
if (process.env.ELECTRON_RUN_AS_NODE) return true;
|
|
349
|
+
return typeof window !== "undefined" && window.process && window.process.type === "renderer";
|
|
350
|
+
}
|
|
351
|
+
function isAlpine(platform2) {
|
|
352
|
+
return platform2 === "linux" && fs.existsSync("/etc/alpine-release");
|
|
353
|
+
}
|
|
354
|
+
load.parseTags = parseTags;
|
|
355
|
+
load.matchTags = matchTags;
|
|
356
|
+
load.compareTags = compareTags;
|
|
357
|
+
load.parseTuple = parseTuple;
|
|
358
|
+
load.matchTuple = matchTuple;
|
|
359
|
+
load.compareTuples = compareTuples;
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
// node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js
|
|
364
|
+
var require_node_gyp_build2 = __commonJS({
|
|
365
|
+
"node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports, module) {
|
|
366
|
+
"use strict";
|
|
367
|
+
var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
368
|
+
if (typeof runtimeRequire.addon === "function") {
|
|
369
|
+
module.exports = runtimeRequire.addon.bind(runtimeRequire);
|
|
370
|
+
} else {
|
|
371
|
+
module.exports = require_node_gyp_build();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
// node_modules/.pnpm/argon2@0.45.2/node_modules/argon2/argon2.cjs
|
|
377
|
+
var require_argon2 = __commonJS({
|
|
378
|
+
"node_modules/.pnpm/argon2@0.45.2/node_modules/argon2/argon2.cjs"(exports, module) {
|
|
379
|
+
"use strict";
|
|
380
|
+
var { randomBytes: randomBytes2, timingSafeEqual: timingSafeEqual3 } = __require("crypto");
|
|
381
|
+
var { promisify } = __require("util");
|
|
382
|
+
var { deserialize, serialize } = require_format();
|
|
383
|
+
var gypBuild = require_node_gyp_build2();
|
|
384
|
+
var { hash: bindingsHash } = gypBuild(__dirname);
|
|
385
|
+
var generateSalt = promisify(randomBytes2);
|
|
386
|
+
var argon2d = 0;
|
|
387
|
+
var argon2i = 1;
|
|
388
|
+
var argon2id = 2;
|
|
389
|
+
module.exports.argon2d = argon2d;
|
|
390
|
+
module.exports.argon2i = argon2i;
|
|
391
|
+
module.exports.argon2id = argon2id;
|
|
392
|
+
var types = Object.freeze({ argon2d, argon2i, argon2id });
|
|
393
|
+
var names = Object.freeze({
|
|
394
|
+
[types.argon2d]: "argon2d",
|
|
395
|
+
[types.argon2i]: "argon2i",
|
|
396
|
+
[types.argon2id]: "argon2id"
|
|
397
|
+
});
|
|
398
|
+
var defaults = {
|
|
399
|
+
hashLength: 32,
|
|
400
|
+
memoryCost: 1 << 16,
|
|
401
|
+
parallelism: 4,
|
|
402
|
+
timeCost: 3,
|
|
403
|
+
type: argon2id,
|
|
404
|
+
version: 19
|
|
405
|
+
};
|
|
406
|
+
async function hash(password, options) {
|
|
407
|
+
const { raw, salt: _salt, ...rest } = { ...defaults, ...options };
|
|
408
|
+
if (rest.hashLength > 2 ** 32 - 1) {
|
|
409
|
+
throw new RangeError("Hash length is too large");
|
|
410
|
+
}
|
|
411
|
+
if (rest.memoryCost > 2 ** 32 - 1) {
|
|
412
|
+
throw new RangeError("Memory cost is too large");
|
|
413
|
+
}
|
|
414
|
+
if (rest.timeCost > 2 ** 32 - 1) {
|
|
415
|
+
throw new RangeError("Time cost is too large");
|
|
416
|
+
}
|
|
417
|
+
if (rest.parallelism > 2 ** 24 - 1) {
|
|
418
|
+
throw new RangeError("Parallelism is too large");
|
|
419
|
+
}
|
|
420
|
+
const salt = _salt ?? await generateSalt(16);
|
|
421
|
+
const {
|
|
422
|
+
hashLength,
|
|
423
|
+
secret = Buffer.alloc(0),
|
|
424
|
+
type,
|
|
425
|
+
version,
|
|
426
|
+
memoryCost: m,
|
|
427
|
+
timeCost: t,
|
|
428
|
+
parallelism: p,
|
|
429
|
+
associatedData: data = Buffer.alloc(0)
|
|
430
|
+
} = rest;
|
|
431
|
+
const result = await bindingsHash({
|
|
432
|
+
data,
|
|
433
|
+
hashLength,
|
|
434
|
+
m,
|
|
435
|
+
p,
|
|
436
|
+
password: Buffer.from(password),
|
|
437
|
+
salt,
|
|
438
|
+
secret,
|
|
439
|
+
t,
|
|
440
|
+
type,
|
|
441
|
+
version
|
|
442
|
+
});
|
|
443
|
+
if (raw) {
|
|
444
|
+
return result;
|
|
445
|
+
}
|
|
446
|
+
const params = { m, t, p };
|
|
447
|
+
if (data.byteLength > 0) {
|
|
448
|
+
params.data = data;
|
|
449
|
+
}
|
|
450
|
+
return serialize({
|
|
451
|
+
hash: result,
|
|
452
|
+
id: names[type],
|
|
453
|
+
params,
|
|
454
|
+
salt,
|
|
455
|
+
version
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
module.exports.hash = hash;
|
|
459
|
+
function needsRehash(digest, options = {}) {
|
|
460
|
+
const { memoryCost, timeCost, parallelism, version } = {
|
|
461
|
+
...defaults,
|
|
462
|
+
...options
|
|
463
|
+
};
|
|
464
|
+
const {
|
|
465
|
+
version: v,
|
|
466
|
+
params: { m, t, p }
|
|
467
|
+
} = deserialize(digest);
|
|
468
|
+
return Number(v) !== Number(version) || Number(m) !== Number(memoryCost) || Number(t) !== Number(timeCost) || Number(p) !== Number(parallelism);
|
|
469
|
+
}
|
|
470
|
+
module.exports.needsRehash = needsRehash;
|
|
471
|
+
async function verify(digest, password, options = {}) {
|
|
472
|
+
const { id, ...rest } = deserialize(digest);
|
|
473
|
+
if (!(id in types)) {
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
const {
|
|
477
|
+
version = 16,
|
|
478
|
+
params: { m, t, p, data = "" },
|
|
479
|
+
salt,
|
|
480
|
+
hash: actual
|
|
481
|
+
} = rest;
|
|
482
|
+
const { secret = Buffer.alloc(0) } = options;
|
|
483
|
+
const expected = await bindingsHash({
|
|
484
|
+
data: Buffer.from(data, "base64"),
|
|
485
|
+
hashLength: actual.byteLength,
|
|
486
|
+
m: Number(m),
|
|
487
|
+
p: Number(p),
|
|
488
|
+
password: Buffer.from(password),
|
|
489
|
+
salt,
|
|
490
|
+
secret,
|
|
491
|
+
t: Number(t),
|
|
492
|
+
type: types[id],
|
|
493
|
+
version: Number(version)
|
|
494
|
+
});
|
|
495
|
+
return timingSafeEqual3(expected, actual);
|
|
496
|
+
}
|
|
497
|
+
module.exports.verify = verify;
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
// src/server/onCall.ts
|
|
502
|
+
import cors from "cors";
|
|
503
|
+
import cookieParser from "cookie-parser";
|
|
504
|
+
import express from "express";
|
|
505
|
+
import helmet from "helmet";
|
|
506
|
+
|
|
507
|
+
// src/shared/errors.ts
|
|
508
|
+
var HTTP_STATUS_MAP = {
|
|
509
|
+
"invalid-argument": 400,
|
|
510
|
+
unauthenticated: 401,
|
|
511
|
+
"permission-denied": 403,
|
|
512
|
+
"not-found": 404,
|
|
513
|
+
"already-exists": 409,
|
|
514
|
+
"failed-precondition": 412,
|
|
515
|
+
"resource-exhausted": 429,
|
|
516
|
+
unavailable: 503,
|
|
517
|
+
internal: 500
|
|
518
|
+
};
|
|
519
|
+
var CallError = class extends Error {
|
|
520
|
+
code;
|
|
521
|
+
statusCode;
|
|
522
|
+
details;
|
|
523
|
+
constructor(code, message, details) {
|
|
524
|
+
super(message);
|
|
525
|
+
this.name = "CallError";
|
|
526
|
+
this.code = code;
|
|
527
|
+
this.statusCode = HTTP_STATUS_MAP[code] ?? 500;
|
|
528
|
+
this.details = details;
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
var isCallError = (err) => err instanceof CallError;
|
|
532
|
+
var toCallErrorBody = (err) => ({
|
|
533
|
+
error: {
|
|
534
|
+
code: err.code,
|
|
535
|
+
message: err.message,
|
|
536
|
+
...err.details !== void 0 ? { details: err.details } : {}
|
|
537
|
+
}
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
// src/server/tokens.ts
|
|
541
|
+
import { SignJWT, jwtVerify } from "jose";
|
|
542
|
+
|
|
543
|
+
// src/server/security.ts
|
|
544
|
+
import { timingSafeEqual } from "crypto";
|
|
545
|
+
import { ObjectId } from "mongodb";
|
|
546
|
+
var PROTOTYPE_POLLUTION_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
547
|
+
var OBJECT_ID_HEX_REGEX = /^[a-fA-F0-9]{24}$/;
|
|
548
|
+
var isPlainObject = (value) => {
|
|
549
|
+
if (typeof value !== "object" || value === null) return false;
|
|
550
|
+
const proto = Object.getPrototypeOf(value);
|
|
551
|
+
return proto === Object.prototype || proto === null;
|
|
552
|
+
};
|
|
553
|
+
function sanitizeNoSqlPayload(input, mode = "reject", currentPath = "data") {
|
|
554
|
+
if (mode === "off" || input === null || typeof input !== "object") {
|
|
555
|
+
return input;
|
|
556
|
+
}
|
|
557
|
+
if (!isPlainObject(input)) {
|
|
558
|
+
return input;
|
|
559
|
+
}
|
|
560
|
+
if (Array.isArray(input)) {
|
|
561
|
+
return input.map(
|
|
562
|
+
(item, index) => sanitizeNoSqlPayload(item, mode, `${currentPath}[${index}]`)
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
const cleanObject = {};
|
|
566
|
+
for (const key of Object.keys(input)) {
|
|
567
|
+
const isPrototypeKey = PROTOTYPE_POLLUTION_KEYS.has(key);
|
|
568
|
+
const isMongoOperator = key.startsWith("$") || key.includes(".");
|
|
569
|
+
if (isPrototypeKey || isMongoOperator) {
|
|
570
|
+
if (mode === "reject") {
|
|
571
|
+
throw new CallError(
|
|
572
|
+
"invalid-argument",
|
|
573
|
+
`Disallowed key "${key}" detected at "${currentPath}".`
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
const value = input[key];
|
|
579
|
+
cleanObject[key] = sanitizeNoSqlPayload(value, mode, `${currentPath}.${key}`);
|
|
580
|
+
}
|
|
581
|
+
return cleanObject;
|
|
582
|
+
}
|
|
583
|
+
function assertStrongJwtSecret(secret) {
|
|
584
|
+
if (!secret) {
|
|
585
|
+
throw new Error("JWT_SECRET is not configured on the server.");
|
|
586
|
+
}
|
|
587
|
+
if (secret.length < 32) {
|
|
588
|
+
throw new Error(
|
|
589
|
+
"Security error: JWT_SECRET must be at least 32 characters (256 bits) long."
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
return new TextEncoder().encode(secret);
|
|
593
|
+
}
|
|
594
|
+
function toObjectId(id, fieldName = "id") {
|
|
595
|
+
if (typeof id !== "string" || !OBJECT_ID_HEX_REGEX.test(id) || !ObjectId.isValid(id)) {
|
|
596
|
+
throw new CallError(
|
|
597
|
+
"invalid-argument",
|
|
598
|
+
`Identifier "${fieldName}" is not a valid ObjectId.`
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
return new ObjectId(id);
|
|
602
|
+
}
|
|
603
|
+
function safeEqual(left, right) {
|
|
604
|
+
const leftBuffer = Buffer.from(left, "utf8");
|
|
605
|
+
const rightBuffer = Buffer.from(right, "utf8");
|
|
606
|
+
if (leftBuffer.length !== rightBuffer.length) return false;
|
|
607
|
+
return timingSafeEqual(leftBuffer, rightBuffer);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// src/server/tokens.ts
|
|
611
|
+
var getSecretKey = (secret) => assertStrongJwtSecret(secret);
|
|
612
|
+
async function signSessionToken(claims, options) {
|
|
613
|
+
let token = new SignJWT({ tv: claims.tokenVersion, am: claims.authMethod }).setProtectedHeader({ alg: "HS256" }).setSubject(claims.userId).setIssuedAt().setExpirationTime(`${options.ttlSeconds}s`);
|
|
614
|
+
if (options.issuer) token = token.setIssuer(options.issuer);
|
|
615
|
+
if (options.audience) token = token.setAudience(options.audience);
|
|
616
|
+
return token.sign(getSecretKey(options.secret));
|
|
617
|
+
}
|
|
618
|
+
async function verifySessionToken(token, options) {
|
|
619
|
+
try {
|
|
620
|
+
const { payload } = await jwtVerify(token, getSecretKey(options.secret), {
|
|
621
|
+
algorithms: options.algorithms ?? ["HS256"],
|
|
622
|
+
issuer: options.issuer,
|
|
623
|
+
audience: options.audience
|
|
624
|
+
});
|
|
625
|
+
const userId = typeof payload.sub === "string" ? payload.sub.trim() : "";
|
|
626
|
+
const tokenVersion = typeof payload.tv === "number" ? payload.tv : NaN;
|
|
627
|
+
const authMethod = payload.am === "classic" ? "classic" : void 0;
|
|
628
|
+
if (!userId || !Number.isInteger(tokenVersion) || tokenVersion < 1 || !authMethod) {
|
|
629
|
+
throw new CallError("unauthenticated", "Invalid session token payload.");
|
|
630
|
+
}
|
|
631
|
+
return { userId, tokenVersion, authMethod };
|
|
632
|
+
} catch (err) {
|
|
633
|
+
if (err instanceof CallError) throw err;
|
|
634
|
+
throw new CallError("unauthenticated", "Session token is invalid or expired.");
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// src/server/authenticate.ts
|
|
639
|
+
var extractBearerToken = (headerValue) => {
|
|
640
|
+
if (!headerValue) return null;
|
|
641
|
+
const match = /^Bearer\s+(.+)$/i.exec(headerValue.trim());
|
|
642
|
+
return match?.[1]?.trim() || null;
|
|
643
|
+
};
|
|
644
|
+
var resolveUserCaller = async (store, session) => {
|
|
645
|
+
const userDoc = await store.getUserById(session.userId);
|
|
646
|
+
if (!userDoc) {
|
|
647
|
+
throw new CallError("unauthenticated", "Session user no longer exists.");
|
|
648
|
+
}
|
|
649
|
+
if (userDoc.data.isActive === false || userDoc.data.active === false) {
|
|
650
|
+
throw new CallError("unauthenticated", "This account has been deactivated.");
|
|
651
|
+
}
|
|
652
|
+
const storedVersion = typeof userDoc.data.tokenVersion === "number" ? userDoc.data.tokenVersion : 1;
|
|
653
|
+
if (storedVersion !== session.tokenVersion) {
|
|
654
|
+
throw new CallError("unauthenticated", "Session has been revoked.");
|
|
655
|
+
}
|
|
656
|
+
return {
|
|
657
|
+
uid: userDoc.id,
|
|
658
|
+
userDocId: userDoc.id,
|
|
659
|
+
email: typeof userDoc.data.email === "string" ? userDoc.data.email : null,
|
|
660
|
+
emailVerified: true,
|
|
661
|
+
displayName: typeof userDoc.data.displayName === "string" ? userDoc.data.displayName : null,
|
|
662
|
+
authMethod: "classic",
|
|
663
|
+
mustChangePassword: Boolean(userDoc.data.mustChangePassword),
|
|
664
|
+
tokenClaims: {},
|
|
665
|
+
userData: userDoc.data
|
|
666
|
+
};
|
|
667
|
+
};
|
|
668
|
+
var authenticateRequest = async (req, options) => {
|
|
669
|
+
const bearerToken = extractBearerToken(req.header("authorization"));
|
|
670
|
+
if (bearerToken) {
|
|
671
|
+
const session = await verifySessionToken(bearerToken, {
|
|
672
|
+
secret: options.secret,
|
|
673
|
+
algorithms: options.algorithms,
|
|
674
|
+
issuer: options.issuer,
|
|
675
|
+
audience: options.audience
|
|
676
|
+
});
|
|
677
|
+
return resolveUserCaller(options.store, session);
|
|
678
|
+
}
|
|
679
|
+
if (options.cookieEnabled && options.cookieName) {
|
|
680
|
+
const cookieToken = req.cookies?.[options.cookieName];
|
|
681
|
+
if (typeof cookieToken === "string" && cookieToken.trim()) {
|
|
682
|
+
const session = await verifySessionToken(cookieToken.trim(), {
|
|
683
|
+
secret: options.secret,
|
|
684
|
+
algorithms: options.algorithms,
|
|
685
|
+
issuer: options.issuer,
|
|
686
|
+
audience: options.audience
|
|
687
|
+
});
|
|
688
|
+
return resolveUserCaller(options.store, session);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return null;
|
|
692
|
+
};
|
|
693
|
+
var createAuthMiddleware = (options) => {
|
|
694
|
+
return async (req, _res, next) => {
|
|
695
|
+
try {
|
|
696
|
+
req.caller = await authenticateRequest(req, options);
|
|
697
|
+
next();
|
|
698
|
+
} catch (err) {
|
|
699
|
+
next(err);
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
// src/server/authRoutes.ts
|
|
705
|
+
import { Router } from "express";
|
|
706
|
+
|
|
707
|
+
// src/server/cookies.ts
|
|
708
|
+
import crypto from "crypto";
|
|
709
|
+
var generateCsrfToken = () => crypto.randomBytes(32).toString("hex");
|
|
710
|
+
var cookieSettings = (config) => {
|
|
711
|
+
const cookie = config.cookies ?? {};
|
|
712
|
+
return {
|
|
713
|
+
enabled: cookie.enabled ?? false,
|
|
714
|
+
secure: cookie.secure ?? false,
|
|
715
|
+
sessionCookieName: cookie.sessionCookieName ?? "session",
|
|
716
|
+
csrfCookieName: cookie.csrfCookieName ?? "csrf",
|
|
717
|
+
ttlSeconds: config.jwtOptions?.ttlSeconds ?? 28800,
|
|
718
|
+
basePath: config.apiBasePath ?? ""
|
|
719
|
+
};
|
|
720
|
+
};
|
|
721
|
+
var setSessionCookies = (res, sessionJwt, config) => {
|
|
722
|
+
const settings = cookieSettings(config);
|
|
723
|
+
const csrfToken = generateCsrfToken();
|
|
724
|
+
const maxAgeMs = settings.ttlSeconds * 1e3;
|
|
725
|
+
res.cookie(settings.sessionCookieName, sessionJwt, {
|
|
726
|
+
httpOnly: true,
|
|
727
|
+
sameSite: "lax",
|
|
728
|
+
secure: settings.secure,
|
|
729
|
+
path: settings.basePath || "/",
|
|
730
|
+
maxAge: maxAgeMs
|
|
731
|
+
});
|
|
732
|
+
res.cookie(settings.csrfCookieName, csrfToken, {
|
|
733
|
+
httpOnly: false,
|
|
734
|
+
sameSite: "lax",
|
|
735
|
+
secure: settings.secure,
|
|
736
|
+
path: "/",
|
|
737
|
+
maxAge: maxAgeMs
|
|
738
|
+
});
|
|
739
|
+
return csrfToken;
|
|
740
|
+
};
|
|
741
|
+
var ensureCsrfCookie = (req, res, config) => {
|
|
742
|
+
const settings = cookieSettings(config);
|
|
743
|
+
const existing = req.cookies?.[settings.csrfCookieName];
|
|
744
|
+
if (typeof existing === "string" && existing.length >= 32) {
|
|
745
|
+
return existing;
|
|
746
|
+
}
|
|
747
|
+
const csrfToken = generateCsrfToken();
|
|
748
|
+
res.cookie(settings.csrfCookieName, csrfToken, {
|
|
749
|
+
httpOnly: false,
|
|
750
|
+
sameSite: "lax",
|
|
751
|
+
secure: settings.secure,
|
|
752
|
+
path: "/",
|
|
753
|
+
maxAge: settings.ttlSeconds * 1e3
|
|
754
|
+
});
|
|
755
|
+
return csrfToken;
|
|
756
|
+
};
|
|
757
|
+
var clearSessionCookies = (res, config) => {
|
|
758
|
+
const settings = cookieSettings(config);
|
|
759
|
+
res.clearCookie(settings.sessionCookieName, {
|
|
760
|
+
httpOnly: true,
|
|
761
|
+
sameSite: "lax",
|
|
762
|
+
secure: settings.secure,
|
|
763
|
+
path: settings.basePath || "/"
|
|
764
|
+
});
|
|
765
|
+
res.clearCookie(settings.csrfCookieName, {
|
|
766
|
+
httpOnly: false,
|
|
767
|
+
sameSite: "lax",
|
|
768
|
+
secure: settings.secure,
|
|
769
|
+
path: "/"
|
|
770
|
+
});
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
// src/server/password.ts
|
|
774
|
+
import { randomBytes, scrypt as scryptCallback, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
775
|
+
var scryptAsync = (password, salt, keyLength, options) => new Promise((resolve, reject) => {
|
|
776
|
+
scryptCallback(password, salt, keyLength, options, (err, derivedKey) => {
|
|
777
|
+
if (err) reject(err);
|
|
778
|
+
else resolve(derivedKey);
|
|
779
|
+
});
|
|
780
|
+
});
|
|
781
|
+
var DEFAULT_SCRYPT_N = 16384;
|
|
782
|
+
var DEFAULT_SCRYPT_R = 8;
|
|
783
|
+
var DEFAULT_SCRYPT_P = 1;
|
|
784
|
+
var DEFAULT_SCRYPT_KEY_LENGTH = 64;
|
|
785
|
+
var isArgon2Module = (value) => {
|
|
786
|
+
if (typeof value !== "object" || value === null) return false;
|
|
787
|
+
const candidate = value;
|
|
788
|
+
return typeof candidate.hash === "function" && typeof candidate.verify === "function" && typeof candidate.argon2id === "number";
|
|
789
|
+
};
|
|
790
|
+
var loadArgon2 = async () => {
|
|
791
|
+
try {
|
|
792
|
+
const mod = await Promise.resolve().then(() => __toESM(require_argon2(), 1));
|
|
793
|
+
const resolved = mod.default ?? mod;
|
|
794
|
+
return isArgon2Module(resolved) ? resolved : null;
|
|
795
|
+
} catch {
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
function assertPasswordComplexity(password, minLength = 8) {
|
|
800
|
+
if (typeof password !== "string" || password.length < minLength) {
|
|
801
|
+
throw new CallError(
|
|
802
|
+
"invalid-argument",
|
|
803
|
+
`Password must be at least ${minLength} characters long.`
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
if (password.length > 128) {
|
|
807
|
+
throw new CallError("invalid-argument", "Password must not exceed 128 characters.");
|
|
808
|
+
}
|
|
809
|
+
return password;
|
|
810
|
+
}
|
|
811
|
+
var encodeScrypt = (params) => `scrypt$${params.N}$${params.r}$${params.p}$${params.salt.toString("base64url")}$${params.hash.toString("base64url")}`;
|
|
812
|
+
var hashWithScrypt = async (password, options) => {
|
|
813
|
+
const N = options.scryptN ?? DEFAULT_SCRYPT_N;
|
|
814
|
+
const r = options.scryptR ?? DEFAULT_SCRYPT_R;
|
|
815
|
+
const p = options.scryptP ?? DEFAULT_SCRYPT_P;
|
|
816
|
+
const keyLength = options.scryptKeyLength ?? DEFAULT_SCRYPT_KEY_LENGTH;
|
|
817
|
+
const salt = randomBytes(16);
|
|
818
|
+
const derived = await scryptAsync(password, salt, keyLength, {
|
|
819
|
+
N,
|
|
820
|
+
r,
|
|
821
|
+
p,
|
|
822
|
+
maxmem: 128 * 1024 * 1024
|
|
823
|
+
});
|
|
824
|
+
return encodeScrypt({ N, r, p, salt, hash: derived });
|
|
825
|
+
};
|
|
826
|
+
var verifyScrypt = async (hash, candidate) => {
|
|
827
|
+
const parts = hash.split("$");
|
|
828
|
+
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
|
|
829
|
+
const N = Number(parts[1]);
|
|
830
|
+
const r = Number(parts[2]);
|
|
831
|
+
const p = Number(parts[3]);
|
|
832
|
+
const salt = Buffer.from(parts[4] ?? "", "base64url");
|
|
833
|
+
const expected = Buffer.from(parts[5] ?? "", "base64url");
|
|
834
|
+
if (![N, r, p].every(Number.isInteger) || N < 2 || r < 1 || p < 1) return false;
|
|
835
|
+
if (salt.length === 0 || expected.length === 0) return false;
|
|
836
|
+
try {
|
|
837
|
+
const derived = await scryptAsync(candidate, salt, expected.length, {
|
|
838
|
+
N,
|
|
839
|
+
r,
|
|
840
|
+
p,
|
|
841
|
+
maxmem: 128 * 1024 * 1024
|
|
842
|
+
});
|
|
843
|
+
return timingSafeEqual2(derived, expected);
|
|
844
|
+
} catch {
|
|
845
|
+
return false;
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
async function hashPassword(password, options = {}) {
|
|
849
|
+
const minLength = options.minLength ?? 8;
|
|
850
|
+
const valid = assertPasswordComplexity(password, minLength);
|
|
851
|
+
if (options.algo === "scrypt") {
|
|
852
|
+
return hashWithScrypt(valid, options);
|
|
853
|
+
}
|
|
854
|
+
if (options.algo === "argon2") {
|
|
855
|
+
const argon22 = await loadArgon2();
|
|
856
|
+
if (!argon22) {
|
|
857
|
+
throw new CallError(
|
|
858
|
+
"unavailable",
|
|
859
|
+
"argon2 is required for PASSWORD_HASH_ALGO=argon2 but is not installed."
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
return argon22.hash(valid, {
|
|
863
|
+
type: argon22.argon2id,
|
|
864
|
+
memoryCost: 19456,
|
|
865
|
+
timeCost: 2,
|
|
866
|
+
parallelism: 1
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
const argon2 = await loadArgon2();
|
|
870
|
+
if (argon2) {
|
|
871
|
+
return argon2.hash(valid, {
|
|
872
|
+
type: argon2.argon2id,
|
|
873
|
+
memoryCost: 19456,
|
|
874
|
+
timeCost: 2,
|
|
875
|
+
parallelism: 1
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
return hashWithScrypt(valid, options);
|
|
879
|
+
}
|
|
880
|
+
async function verifyPassword(hash, candidate) {
|
|
881
|
+
if (!hash || !candidate) return false;
|
|
882
|
+
if (hash.startsWith("scrypt$")) {
|
|
883
|
+
return verifyScrypt(hash, candidate);
|
|
884
|
+
}
|
|
885
|
+
const argon2 = await loadArgon2();
|
|
886
|
+
if (argon2) {
|
|
887
|
+
try {
|
|
888
|
+
return await argon2.verify(hash, candidate);
|
|
889
|
+
} catch {
|
|
890
|
+
return false;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// src/server/rbac.ts
|
|
897
|
+
var resolveCallerRole = async (store, caller) => {
|
|
898
|
+
if (!caller) {
|
|
899
|
+
throw new CallError("unauthenticated", "The request must be authenticated.");
|
|
900
|
+
}
|
|
901
|
+
const userDocId = caller.userDocId;
|
|
902
|
+
const userData = caller.userData;
|
|
903
|
+
if (userData.isActive === false || userData.active === false) {
|
|
904
|
+
return { role: "none", readOnly: true, userDocId };
|
|
905
|
+
}
|
|
906
|
+
const foundRole = typeof userData.role === "string" && userData.role.trim() ? userData.role.trim() : null;
|
|
907
|
+
if (!foundRole || foundRole === "user" || foundRole === "none") {
|
|
908
|
+
return { role: "none", readOnly: true, userDocId };
|
|
909
|
+
}
|
|
910
|
+
if (foundRole === "superadmin") {
|
|
911
|
+
return { role: "superadmin", readOnly: false, userDocId };
|
|
912
|
+
}
|
|
913
|
+
if (foundRole === "admin") {
|
|
914
|
+
const adminDoc = await store.getRole("admin");
|
|
915
|
+
if (adminDoc && adminDoc.data.isActive === false) {
|
|
916
|
+
return { role: "none", readOnly: true, userDocId };
|
|
917
|
+
}
|
|
918
|
+
return {
|
|
919
|
+
role: "admin",
|
|
920
|
+
readOnly: adminDoc ? Boolean(adminDoc.data.readOnly) : false,
|
|
921
|
+
userDocId
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
if (foundRole === "viewer") {
|
|
925
|
+
const viewerDoc = await store.getRole("viewer");
|
|
926
|
+
if (viewerDoc && viewerDoc.data.isActive === false) {
|
|
927
|
+
return { role: "none", readOnly: true, userDocId };
|
|
928
|
+
}
|
|
929
|
+
return {
|
|
930
|
+
role: "viewer",
|
|
931
|
+
readOnly: viewerDoc ? viewerDoc.data.readOnly !== false : true,
|
|
932
|
+
userDocId
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
const customRoleDoc = await store.getRole(foundRole);
|
|
936
|
+
if (customRoleDoc) {
|
|
937
|
+
const roleData = customRoleDoc.data;
|
|
938
|
+
if (roleData.isActive === false) {
|
|
939
|
+
return { role: "none", readOnly: true, userDocId };
|
|
940
|
+
}
|
|
941
|
+
return {
|
|
942
|
+
role: foundRole,
|
|
943
|
+
readOnly: Boolean(roleData.readOnly),
|
|
944
|
+
userDocId
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
return { role: "none", readOnly: true, userDocId };
|
|
948
|
+
};
|
|
949
|
+
var assertAllowedRole = (access, allowedRoles, options = {}) => {
|
|
950
|
+
if (access.role === "none") {
|
|
951
|
+
throw new CallError("permission-denied", "This action requires an active role.");
|
|
952
|
+
}
|
|
953
|
+
if (options.superadminBypass !== false && access.role === "superadmin") {
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
if (options.writeAccess && access.readOnly) {
|
|
957
|
+
throw new CallError("permission-denied", `Role "${access.role}" has read-only access.`);
|
|
958
|
+
}
|
|
959
|
+
if (allowedRoles.length > 0 && !allowedRoles.includes(access.role)) {
|
|
960
|
+
throw new CallError(
|
|
961
|
+
"permission-denied",
|
|
962
|
+
`Role "${access.role}" is not permitted to call this function.`
|
|
963
|
+
);
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
|
|
967
|
+
// src/server/authRoutes.ts
|
|
968
|
+
var dummyHashPromise = null;
|
|
969
|
+
var getDummyHash = (minLength) => {
|
|
970
|
+
dummyHashPromise ??= hashPassword("dummy-password-for-timing", {
|
|
971
|
+
minLength,
|
|
972
|
+
algo: "scrypt"
|
|
973
|
+
});
|
|
974
|
+
return dummyHashPromise;
|
|
975
|
+
};
|
|
976
|
+
var createAuthRouter = ({
|
|
977
|
+
store,
|
|
978
|
+
config,
|
|
979
|
+
authenticate,
|
|
980
|
+
csrf,
|
|
981
|
+
authLimiter
|
|
982
|
+
}) => {
|
|
983
|
+
const router = Router();
|
|
984
|
+
const cookie = config.cookies ?? {};
|
|
985
|
+
const cookieEnabled = cookie.enabled ?? false;
|
|
986
|
+
const returnToken = config.auth?.returnToken ?? true;
|
|
987
|
+
const minPasswordLength = config.minPasswordLength ?? 8;
|
|
988
|
+
const jwtOptions = config.jwtOptions ?? {};
|
|
989
|
+
const secret = config.jwtSecret ?? jwtOptions.secret ?? "";
|
|
990
|
+
const ttlSeconds = jwtOptions.ttlSeconds ?? 28800;
|
|
991
|
+
const sessionCookieName = cookie.sessionCookieName ?? "session";
|
|
992
|
+
router.post("/login", authLimiter, async (req, res, next) => {
|
|
993
|
+
try {
|
|
994
|
+
if (!isPlainObject(req.body)) {
|
|
995
|
+
throw new CallError("invalid-argument", "Request body must be an object.");
|
|
996
|
+
}
|
|
997
|
+
const rawEmail = req.body.email;
|
|
998
|
+
const rawPassword = req.body.password;
|
|
999
|
+
if (typeof rawEmail !== "string" || typeof rawPassword !== "string") {
|
|
1000
|
+
throw new CallError("invalid-argument", "Email and password are required.");
|
|
1001
|
+
}
|
|
1002
|
+
const email = rawEmail.trim().toLowerCase();
|
|
1003
|
+
if (!email || !rawPassword) {
|
|
1004
|
+
throw new CallError("invalid-argument", "Email and password are required.");
|
|
1005
|
+
}
|
|
1006
|
+
const userDoc = await store.findUserByEmail(email);
|
|
1007
|
+
const passwordHash = userDoc && typeof userDoc.data.passwordHash === "string" ? userDoc.data.passwordHash : "";
|
|
1008
|
+
const isActive = userDoc && userDoc.data.isActive !== false && userDoc.data.active !== false;
|
|
1009
|
+
if (!userDoc || !isActive || !passwordHash) {
|
|
1010
|
+
await verifyPassword(await getDummyHash(minPasswordLength), rawPassword);
|
|
1011
|
+
throw new CallError("unauthenticated", "Invalid email or password.");
|
|
1012
|
+
}
|
|
1013
|
+
const validPassword = await verifyPassword(passwordHash, rawPassword);
|
|
1014
|
+
if (!validPassword) {
|
|
1015
|
+
throw new CallError("unauthenticated", "Invalid email or password.");
|
|
1016
|
+
}
|
|
1017
|
+
const tokenVersion = typeof userDoc.data.tokenVersion === "number" && userDoc.data.tokenVersion >= 1 ? Math.floor(userDoc.data.tokenVersion) : 1;
|
|
1018
|
+
const jwt = await signSessionToken(
|
|
1019
|
+
{ userId: userDoc.id, tokenVersion, authMethod: "classic" },
|
|
1020
|
+
{
|
|
1021
|
+
secret,
|
|
1022
|
+
ttlSeconds,
|
|
1023
|
+
issuer: jwtOptions.issuer,
|
|
1024
|
+
audience: jwtOptions.audience
|
|
1025
|
+
}
|
|
1026
|
+
);
|
|
1027
|
+
let csrfToken = null;
|
|
1028
|
+
if (cookieEnabled) {
|
|
1029
|
+
csrfToken = setSessionCookies(res, jwt, config);
|
|
1030
|
+
}
|
|
1031
|
+
const mustChangePassword = Boolean(userDoc.data.mustChangePassword);
|
|
1032
|
+
const body = {
|
|
1033
|
+
user: {
|
|
1034
|
+
uid: userDoc.id,
|
|
1035
|
+
email: typeof userDoc.data.email === "string" ? userDoc.data.email : email,
|
|
1036
|
+
emailVerified: true,
|
|
1037
|
+
displayName: typeof userDoc.data.displayName === "string" ? userDoc.data.displayName : null,
|
|
1038
|
+
authMethod: "classic",
|
|
1039
|
+
mustChangePassword
|
|
1040
|
+
},
|
|
1041
|
+
authMethod: "classic",
|
|
1042
|
+
mustChangePassword
|
|
1043
|
+
};
|
|
1044
|
+
if (returnToken) body.token = jwt;
|
|
1045
|
+
if (cookieEnabled && csrfToken) body.csrfToken = csrfToken;
|
|
1046
|
+
res.json(body);
|
|
1047
|
+
} catch (err) {
|
|
1048
|
+
next(err);
|
|
1049
|
+
}
|
|
1050
|
+
});
|
|
1051
|
+
router.get("/me", authenticate, async (req, res, next) => {
|
|
1052
|
+
try {
|
|
1053
|
+
const caller = req.caller;
|
|
1054
|
+
if (!caller) {
|
|
1055
|
+
throw new CallError("unauthenticated", "Authentication required.");
|
|
1056
|
+
}
|
|
1057
|
+
let csrfToken = null;
|
|
1058
|
+
if (cookieEnabled) {
|
|
1059
|
+
csrfToken = ensureCsrfCookie(req, res, config);
|
|
1060
|
+
}
|
|
1061
|
+
const access = await resolveCallerRole(store, caller);
|
|
1062
|
+
const body = {
|
|
1063
|
+
user: {
|
|
1064
|
+
uid: caller.uid,
|
|
1065
|
+
email: caller.email,
|
|
1066
|
+
emailVerified: caller.emailVerified,
|
|
1067
|
+
displayName: caller.displayName ?? null,
|
|
1068
|
+
authMethod: caller.authMethod,
|
|
1069
|
+
mustChangePassword: caller.mustChangePassword,
|
|
1070
|
+
role: access.role === "none" ? "user" : access.role
|
|
1071
|
+
},
|
|
1072
|
+
authMethod: caller.authMethod,
|
|
1073
|
+
mustChangePassword: caller.mustChangePassword
|
|
1074
|
+
};
|
|
1075
|
+
if (cookieEnabled && csrfToken) body.csrfToken = csrfToken;
|
|
1076
|
+
res.json(body);
|
|
1077
|
+
} catch (err) {
|
|
1078
|
+
next(err);
|
|
1079
|
+
}
|
|
1080
|
+
});
|
|
1081
|
+
router.post("/change-password", authLimiter, authenticate, csrf, async (req, res, next) => {
|
|
1082
|
+
try {
|
|
1083
|
+
const caller = req.caller;
|
|
1084
|
+
if (!caller) {
|
|
1085
|
+
throw new CallError("unauthenticated", "Authentication required.");
|
|
1086
|
+
}
|
|
1087
|
+
if (!isPlainObject(req.body)) {
|
|
1088
|
+
throw new CallError("invalid-argument", "Request body must be an object.");
|
|
1089
|
+
}
|
|
1090
|
+
const currentPassword = req.body.currentPassword;
|
|
1091
|
+
const newPassword = req.body.newPassword;
|
|
1092
|
+
if (typeof currentPassword !== "string" || typeof newPassword !== "string") {
|
|
1093
|
+
throw new CallError(
|
|
1094
|
+
"invalid-argument",
|
|
1095
|
+
"Current password and new password are required."
|
|
1096
|
+
);
|
|
1097
|
+
}
|
|
1098
|
+
const userDoc = await store.getUserById(caller.userDocId);
|
|
1099
|
+
if (!userDoc || typeof userDoc.data.passwordHash !== "string") {
|
|
1100
|
+
throw new CallError("unauthenticated", "User account not found.");
|
|
1101
|
+
}
|
|
1102
|
+
const matches = await verifyPassword(userDoc.data.passwordHash, currentPassword);
|
|
1103
|
+
if (!matches) {
|
|
1104
|
+
throw new CallError("invalid-argument", "Current password is incorrect.");
|
|
1105
|
+
}
|
|
1106
|
+
if (currentPassword === newPassword) {
|
|
1107
|
+
throw new CallError(
|
|
1108
|
+
"invalid-argument",
|
|
1109
|
+
"New password must be different from your current password."
|
|
1110
|
+
);
|
|
1111
|
+
}
|
|
1112
|
+
const newHash = await hashPassword(newPassword, { minLength: minPasswordLength });
|
|
1113
|
+
const currentVersion = typeof userDoc.data.tokenVersion === "number" && userDoc.data.tokenVersion >= 1 ? Math.floor(userDoc.data.tokenVersion) : 1;
|
|
1114
|
+
const nextVersion = currentVersion + 1;
|
|
1115
|
+
const now = /* @__PURE__ */ new Date();
|
|
1116
|
+
await store.setUser(
|
|
1117
|
+
userDoc.id,
|
|
1118
|
+
{
|
|
1119
|
+
passwordHash: newHash,
|
|
1120
|
+
mustChangePassword: false,
|
|
1121
|
+
tokenVersion: nextVersion,
|
|
1122
|
+
passwordUpdatedAt: now,
|
|
1123
|
+
updatedAt: now
|
|
1124
|
+
},
|
|
1125
|
+
{ merge: true }
|
|
1126
|
+
);
|
|
1127
|
+
const freshJwt = await signSessionToken(
|
|
1128
|
+
{ userId: userDoc.id, tokenVersion: nextVersion, authMethod: "classic" },
|
|
1129
|
+
{
|
|
1130
|
+
secret,
|
|
1131
|
+
ttlSeconds,
|
|
1132
|
+
issuer: jwtOptions.issuer,
|
|
1133
|
+
audience: jwtOptions.audience
|
|
1134
|
+
}
|
|
1135
|
+
);
|
|
1136
|
+
let csrfToken = null;
|
|
1137
|
+
if (cookieEnabled) {
|
|
1138
|
+
csrfToken = setSessionCookies(res, freshJwt, config);
|
|
1139
|
+
}
|
|
1140
|
+
const body = { success: true, mustChangePassword: false };
|
|
1141
|
+
if (returnToken) body.token = freshJwt;
|
|
1142
|
+
if (cookieEnabled && csrfToken) body.csrfToken = csrfToken;
|
|
1143
|
+
res.json(body);
|
|
1144
|
+
} catch (err) {
|
|
1145
|
+
next(err);
|
|
1146
|
+
}
|
|
1147
|
+
});
|
|
1148
|
+
router.post("/logout", (req, res, next) => {
|
|
1149
|
+
const hasSessionCookie = typeof req.cookies?.[sessionCookieName] === "string";
|
|
1150
|
+
if (hasSessionCookie) {
|
|
1151
|
+
csrf(req, res, (err) => {
|
|
1152
|
+
if (err) {
|
|
1153
|
+
next(err);
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
clearSessionCookies(res, config);
|
|
1157
|
+
res.json({ success: true });
|
|
1158
|
+
});
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
try {
|
|
1162
|
+
clearSessionCookies(res, config);
|
|
1163
|
+
res.json({ success: true });
|
|
1164
|
+
} catch (err) {
|
|
1165
|
+
next(err);
|
|
1166
|
+
}
|
|
1167
|
+
});
|
|
1168
|
+
return router;
|
|
1169
|
+
};
|
|
1170
|
+
|
|
1171
|
+
// src/server/config.ts
|
|
1172
|
+
import { config as loadDotenv } from "dotenv";
|
|
1173
|
+
var parseBool = (value) => {
|
|
1174
|
+
if (value === void 0 || value.trim() === "") return void 0;
|
|
1175
|
+
return value.trim().toLowerCase() === "true";
|
|
1176
|
+
};
|
|
1177
|
+
var parseIntOr = (value, fallback) => {
|
|
1178
|
+
const parsed = Number(value);
|
|
1179
|
+
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
|
|
1180
|
+
};
|
|
1181
|
+
var parseTrustProxy = (value) => {
|
|
1182
|
+
if (value === void 0) return 1;
|
|
1183
|
+
const numeric = Number(value);
|
|
1184
|
+
if (Number.isInteger(numeric) && numeric >= 0) return numeric;
|
|
1185
|
+
return parseBool(value) ?? 1;
|
|
1186
|
+
};
|
|
1187
|
+
var parseSanitizeMode = (value) => {
|
|
1188
|
+
const normalized = (value ?? "").trim().toLowerCase();
|
|
1189
|
+
if (normalized === "off") return "off";
|
|
1190
|
+
if (normalized === "strip") return "strip";
|
|
1191
|
+
return "reject";
|
|
1192
|
+
};
|
|
1193
|
+
var parseCsv = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
|
|
1194
|
+
var normalizeBasePath = (raw) => {
|
|
1195
|
+
const trimmed = raw.trim();
|
|
1196
|
+
if (!trimmed || trimmed === "/") return "";
|
|
1197
|
+
const withLeading = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
1198
|
+
return withLeading.replace(/\/+$/, "");
|
|
1199
|
+
};
|
|
1200
|
+
var loadEnv = () => {
|
|
1201
|
+
loadDotenv();
|
|
1202
|
+
};
|
|
1203
|
+
var loadServerConfig = (env = process.env) => {
|
|
1204
|
+
const authEnabled = env.AUTH_ENABLED === void 0 ? true : parseBool(env.AUTH_ENABLED) ?? true;
|
|
1205
|
+
const mongoUri = (env.MONGO_URI ?? "").trim();
|
|
1206
|
+
if (!mongoUri) {
|
|
1207
|
+
throw new Error("Missing required environment variable MONGO_URI.");
|
|
1208
|
+
}
|
|
1209
|
+
const jwtSecret = (env.JWT_SECRET ?? "").trim();
|
|
1210
|
+
if (authEnabled && jwtSecret.length < 32) {
|
|
1211
|
+
throw new Error(
|
|
1212
|
+
"Missing or weak JWT_SECRET. When AUTH_ENABLED is true, JWT_SECRET must be at least 32 characters."
|
|
1213
|
+
);
|
|
1214
|
+
}
|
|
1215
|
+
const cookieEnabled = parseBool(env.AUTH_COOKIES_ENABLED) ?? true;
|
|
1216
|
+
return {
|
|
1217
|
+
mongoUri,
|
|
1218
|
+
dbName: (env.MONGO_DB_NAME ?? "").trim() || void 0,
|
|
1219
|
+
usersCollection: (env.USERS_COLLECTION ?? "").trim() || "users",
|
|
1220
|
+
rolesCollection: (env.ROLES_COLLECTION ?? "").trim() || "_roles",
|
|
1221
|
+
jwtSecret,
|
|
1222
|
+
jwtOptions: {
|
|
1223
|
+
secret: jwtSecret,
|
|
1224
|
+
algorithms: parseCsv(env.JWT_ALGORITHMS).length > 0 ? parseCsv(env.JWT_ALGORITHMS) : ["HS256"],
|
|
1225
|
+
issuer: (env.JWT_ISSUER ?? "").trim() || void 0,
|
|
1226
|
+
audience: (env.JWT_AUDIENCE ?? "").trim() || void 0,
|
|
1227
|
+
ttlSeconds: parseIntOr(env.JWT_TTL_SECONDS, 28800)
|
|
1228
|
+
},
|
|
1229
|
+
auth: {
|
|
1230
|
+
enabled: authEnabled,
|
|
1231
|
+
returnToken: true,
|
|
1232
|
+
allowPasswordRotationGate: false,
|
|
1233
|
+
loginRateLimit: {
|
|
1234
|
+
windowMs: parseIntOr(env.AUTH_RATE_LIMIT_WINDOW_MS, 15 * 60 * 1e3),
|
|
1235
|
+
max: parseIntOr(env.AUTH_RATE_LIMIT_MAX, 40)
|
|
1236
|
+
}
|
|
1237
|
+
},
|
|
1238
|
+
cookies: {
|
|
1239
|
+
enabled: cookieEnabled,
|
|
1240
|
+
secure: parseBool(env.COOKIE_SECURE) ?? false,
|
|
1241
|
+
sessionCookieName: (env.SESSION_COOKIE_NAME ?? "").trim() || "session",
|
|
1242
|
+
csrfCookieName: (env.CSRF_COOKIE_NAME ?? "").trim() || "csrf",
|
|
1243
|
+
csrfHeaderName: "x-csrf-token"
|
|
1244
|
+
},
|
|
1245
|
+
corsOrigin: parseCsv(env.CORS_ORIGINS).length > 0 ? parseCsv(env.CORS_ORIGINS) : void 0,
|
|
1246
|
+
bodyLimit: (env.BODY_LIMIT ?? "").trim() || "1mb",
|
|
1247
|
+
trustProxy: parseTrustProxy(env.TRUST_PROXY),
|
|
1248
|
+
helmet: parseBool(env.HELMET_ENABLED) ?? true,
|
|
1249
|
+
rateLimit: {
|
|
1250
|
+
windowMs: parseIntOr(env.RATE_LIMIT_WINDOW_MS, 6e4),
|
|
1251
|
+
max: parseIntOr(env.RATE_LIMIT_MAX, 120)
|
|
1252
|
+
},
|
|
1253
|
+
noSqlSanitize: parseSanitizeMode(env.NOSQL_SANITIZE),
|
|
1254
|
+
swagger: {
|
|
1255
|
+
enabled: parseBool(env.SWAGGER_ENABLED),
|
|
1256
|
+
path: (env.SWAGGER_PATH ?? "").trim() || "/docs",
|
|
1257
|
+
title: (env.API_TITLE ?? "").trim() || "API",
|
|
1258
|
+
version: (env.API_VERSION ?? "").trim() || "1.0.0",
|
|
1259
|
+
description: (env.API_DESCRIPTION ?? "").trim() || void 0,
|
|
1260
|
+
serverUrl: (env.SERVER_URL ?? "").trim() || void 0
|
|
1261
|
+
},
|
|
1262
|
+
minPasswordLength: parseIntOr(env.MIN_PASSWORD_LENGTH, 8),
|
|
1263
|
+
passwordHashAlgo: (() => {
|
|
1264
|
+
const raw = (env.PASSWORD_HASH_ALGO ?? "").trim().toLowerCase();
|
|
1265
|
+
return raw === "argon2" || raw === "scrypt" ? raw : "auto";
|
|
1266
|
+
})(),
|
|
1267
|
+
apiBasePath: normalizeBasePath(env.API_BASE_PATH ?? ""),
|
|
1268
|
+
port: parseIntOr(env.PORT, 4e3)
|
|
1269
|
+
};
|
|
1270
|
+
};
|
|
1271
|
+
|
|
1272
|
+
// src/server/csrf.ts
|
|
1273
|
+
var isOriginAllowed = (originOrReferer, req, allowedOrigins) => {
|
|
1274
|
+
try {
|
|
1275
|
+
const parsed = new URL(originOrReferer);
|
|
1276
|
+
if (allowedOrigins.includes(parsed.origin)) return true;
|
|
1277
|
+
const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim();
|
|
1278
|
+
const host = forwardedHost || req.header("host");
|
|
1279
|
+
if (!host) return false;
|
|
1280
|
+
return parsed.host === host;
|
|
1281
|
+
} catch {
|
|
1282
|
+
return false;
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
var assertSafeOrigin = (req, allowedOrigins) => {
|
|
1286
|
+
const origin = req.header("origin");
|
|
1287
|
+
if (origin && !isOriginAllowed(origin, req, allowedOrigins)) {
|
|
1288
|
+
throw new CallError("permission-denied", "Cross-origin request blocked.");
|
|
1289
|
+
}
|
|
1290
|
+
if (!origin) {
|
|
1291
|
+
const referer = req.header("referer");
|
|
1292
|
+
if (referer && !isOriginAllowed(referer, req, allowedOrigins)) {
|
|
1293
|
+
throw new CallError("permission-denied", "Cross-origin referer blocked.");
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
var createCsrfMiddleware = (config) => {
|
|
1298
|
+
return (req, _res, next) => {
|
|
1299
|
+
try {
|
|
1300
|
+
const method = req.method.toUpperCase();
|
|
1301
|
+
if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
|
|
1302
|
+
next();
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
assertSafeOrigin(req, config.corsOrigins);
|
|
1306
|
+
const authHeader = req.header("authorization") ?? "";
|
|
1307
|
+
const sessionCookie = req.cookies?.[config.sessionCookieName];
|
|
1308
|
+
if (authHeader.startsWith("Bearer ") && !sessionCookie) {
|
|
1309
|
+
next();
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
const csrfCookie = req.cookies?.[config.csrfCookieName];
|
|
1313
|
+
const csrfHeader = req.header(config.csrfHeaderName);
|
|
1314
|
+
if (typeof csrfCookie !== "string" || typeof csrfHeader !== "string" || !csrfCookie || !csrfHeader || !safeEqual(csrfCookie, csrfHeader)) {
|
|
1315
|
+
throw new CallError("permission-denied", "Missing or invalid CSRF token.");
|
|
1316
|
+
}
|
|
1317
|
+
next();
|
|
1318
|
+
} catch (err) {
|
|
1319
|
+
next(err);
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
};
|
|
1323
|
+
|
|
1324
|
+
// src/server/db.ts
|
|
1325
|
+
import { MongoClient } from "mongodb";
|
|
1326
|
+
var cachedClient = null;
|
|
1327
|
+
var cachedDb = null;
|
|
1328
|
+
async function getDatabase(uri, dbName) {
|
|
1329
|
+
if (cachedDb) return cachedDb;
|
|
1330
|
+
const mongoUri = uri || process.env.MONGO_URI;
|
|
1331
|
+
const databaseName = dbName || process.env.MONGO_DB_NAME;
|
|
1332
|
+
if (!mongoUri) {
|
|
1333
|
+
throw new Error("Missing MONGO_URI or MONGO_DB_NAME environment variables.");
|
|
1334
|
+
}
|
|
1335
|
+
cachedClient = new MongoClient(mongoUri, {
|
|
1336
|
+
maxPoolSize: 20,
|
|
1337
|
+
minPoolSize: 2,
|
|
1338
|
+
serverSelectionTimeoutMS: 5e3
|
|
1339
|
+
});
|
|
1340
|
+
await cachedClient.connect();
|
|
1341
|
+
cachedDb = databaseName ? cachedClient.db(databaseName) : cachedClient.db();
|
|
1342
|
+
return cachedDb;
|
|
1343
|
+
}
|
|
1344
|
+
var ensureMongoIndexes = async (db, names = {}) => {
|
|
1345
|
+
const users = db.collection(names.users ?? "users");
|
|
1346
|
+
await users.createIndex(
|
|
1347
|
+
{ email: 1 },
|
|
1348
|
+
{
|
|
1349
|
+
name: "users_email_unique_ci",
|
|
1350
|
+
unique: true,
|
|
1351
|
+
collation: { locale: "en", strength: 2 },
|
|
1352
|
+
partialFilterExpression: { email: { $type: "string" } }
|
|
1353
|
+
}
|
|
1354
|
+
);
|
|
1355
|
+
await users.createIndex(
|
|
1356
|
+
{ firebaseUid: 1 },
|
|
1357
|
+
{
|
|
1358
|
+
name: "users_firebase_uid_sparse",
|
|
1359
|
+
sparse: true
|
|
1360
|
+
}
|
|
1361
|
+
);
|
|
1362
|
+
};
|
|
1363
|
+
var pingDatabase = async (db) => {
|
|
1364
|
+
try {
|
|
1365
|
+
const result = await db.command({ ping: 1 });
|
|
1366
|
+
return result.ok === 1;
|
|
1367
|
+
} catch {
|
|
1368
|
+
return false;
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
var closeDatabase = async () => {
|
|
1372
|
+
if (cachedClient) {
|
|
1373
|
+
await cachedClient.close();
|
|
1374
|
+
cachedClient = null;
|
|
1375
|
+
cachedDb = null;
|
|
1376
|
+
}
|
|
1377
|
+
};
|
|
1378
|
+
|
|
1379
|
+
// src/server/rateLimit.ts
|
|
1380
|
+
import { rateLimit } from "express-rate-limit";
|
|
1381
|
+
var createRateLimiter = (config = {}) => rateLimit({
|
|
1382
|
+
windowMs: config.windowMs ?? 6e4,
|
|
1383
|
+
limit: config.max ?? 100,
|
|
1384
|
+
standardHeaders: true,
|
|
1385
|
+
legacyHeaders: false,
|
|
1386
|
+
skipSuccessfulRequests: config.skipSuccessfulRequests ?? false,
|
|
1387
|
+
handler: (_req, res) => {
|
|
1388
|
+
res.status(429).json({
|
|
1389
|
+
error: {
|
|
1390
|
+
code: "resource-exhausted",
|
|
1391
|
+
message: config.message ?? "Too many requests. Please try again later."
|
|
1392
|
+
}
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
});
|
|
1396
|
+
|
|
1397
|
+
// src/server/store.ts
|
|
1398
|
+
import crypto2 from "crypto";
|
|
1399
|
+
var generateAutoId = () => crypto2.randomBytes(10).toString("hex");
|
|
1400
|
+
var stripInternalId = (data) => {
|
|
1401
|
+
const copy = {};
|
|
1402
|
+
for (const [key, value] of Object.entries(data)) {
|
|
1403
|
+
if (key === "_id" || value === void 0) continue;
|
|
1404
|
+
copy[key] = value;
|
|
1405
|
+
}
|
|
1406
|
+
return copy;
|
|
1407
|
+
};
|
|
1408
|
+
var toStoredDocument = (doc) => {
|
|
1409
|
+
const { _id, ...rest } = doc;
|
|
1410
|
+
return { id: String(_id), data: rest };
|
|
1411
|
+
};
|
|
1412
|
+
var isDuplicateKeyError = (err) => typeof err === "object" && err !== null && "code" in err && err.code === 11e3;
|
|
1413
|
+
var MongoUserStore = class {
|
|
1414
|
+
constructor(db, names = {}) {
|
|
1415
|
+
this.db = db;
|
|
1416
|
+
this.usersCollection = names.users ?? "users";
|
|
1417
|
+
this.rolesCollection = names.roles ?? "_roles";
|
|
1418
|
+
}
|
|
1419
|
+
db;
|
|
1420
|
+
usersCollection;
|
|
1421
|
+
rolesCollection;
|
|
1422
|
+
coll(name) {
|
|
1423
|
+
return this.db.collection(name);
|
|
1424
|
+
}
|
|
1425
|
+
async getUserById(id) {
|
|
1426
|
+
const doc = await this.coll(this.usersCollection).findOne({ _id: id });
|
|
1427
|
+
return doc ? toStoredDocument(doc) : null;
|
|
1428
|
+
}
|
|
1429
|
+
async findUserByEmail(email) {
|
|
1430
|
+
const trimmed = email.trim();
|
|
1431
|
+
if (!trimmed) return null;
|
|
1432
|
+
const doc = await this.coll(this.usersCollection).findOne(
|
|
1433
|
+
{ email: trimmed },
|
|
1434
|
+
{ collation: { locale: "en", strength: 2 } }
|
|
1435
|
+
);
|
|
1436
|
+
return doc ? toStoredDocument(doc) : null;
|
|
1437
|
+
}
|
|
1438
|
+
async findUserByFirebaseUid(uid) {
|
|
1439
|
+
const trimmed = uid.trim();
|
|
1440
|
+
if (!trimmed) return null;
|
|
1441
|
+
const doc = await this.coll(this.usersCollection).findOne({ firebaseUid: trimmed });
|
|
1442
|
+
return doc ? toStoredDocument(doc) : null;
|
|
1443
|
+
}
|
|
1444
|
+
async getRole(roleId) {
|
|
1445
|
+
const doc = await this.coll(this.rolesCollection).findOne({ _id: roleId });
|
|
1446
|
+
return doc ? toStoredDocument(doc) : null;
|
|
1447
|
+
}
|
|
1448
|
+
async createUser(data, explicitId) {
|
|
1449
|
+
const id = explicitId ?? generateAutoId();
|
|
1450
|
+
const clean = stripInternalId(data);
|
|
1451
|
+
try {
|
|
1452
|
+
await this.coll(this.usersCollection).insertOne({ ...clean, _id: id });
|
|
1453
|
+
return { id, data: clean };
|
|
1454
|
+
} catch (err) {
|
|
1455
|
+
if (isDuplicateKeyError(err)) {
|
|
1456
|
+
throw new CallError(
|
|
1457
|
+
"already-exists",
|
|
1458
|
+
explicitId ? `A user with ID "${explicitId}" or duplicate unique key already exists.` : "A duplicate unique key already exists."
|
|
1459
|
+
);
|
|
1460
|
+
}
|
|
1461
|
+
throw err;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
async setUser(id, data, options = {}) {
|
|
1465
|
+
const clean = stripInternalId(data);
|
|
1466
|
+
if (options.merge) {
|
|
1467
|
+
if (Object.keys(clean).length > 0) {
|
|
1468
|
+
await this.coll(this.usersCollection).updateOne({ _id: id }, { $set: clean });
|
|
1469
|
+
}
|
|
1470
|
+
} else {
|
|
1471
|
+
await this.coll(this.usersCollection).replaceOne({ _id: id }, { ...clean, _id: id }, { upsert: true });
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
async hasAnyUser() {
|
|
1475
|
+
const doc = await this.coll(this.usersCollection).findOne({}, { projection: { _id: 1 } });
|
|
1476
|
+
return doc !== null;
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
var InMemoryUserStore = class {
|
|
1480
|
+
users = /* @__PURE__ */ new Map();
|
|
1481
|
+
roles = /* @__PURE__ */ new Map();
|
|
1482
|
+
constructor(initial) {
|
|
1483
|
+
for (const [id, data] of Object.entries(initial?.users ?? {})) {
|
|
1484
|
+
this.users.set(id, structuredClone(data));
|
|
1485
|
+
}
|
|
1486
|
+
for (const [id, data] of Object.entries(initial?.roles ?? {})) {
|
|
1487
|
+
this.roles.set(id, structuredClone(data));
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
normalizeEmail(email) {
|
|
1491
|
+
return email.trim().toLowerCase();
|
|
1492
|
+
}
|
|
1493
|
+
async getUserById(id) {
|
|
1494
|
+
const data = this.users.get(id);
|
|
1495
|
+
return data ? { id, data: structuredClone(data) } : null;
|
|
1496
|
+
}
|
|
1497
|
+
async findUserByEmail(email) {
|
|
1498
|
+
const target = this.normalizeEmail(email);
|
|
1499
|
+
if (!target) return null;
|
|
1500
|
+
for (const [id, data] of this.users.entries()) {
|
|
1501
|
+
if (typeof data.email === "string" && this.normalizeEmail(data.email) === target) {
|
|
1502
|
+
return { id, data: structuredClone(data) };
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
return null;
|
|
1506
|
+
}
|
|
1507
|
+
async findUserByFirebaseUid(uid) {
|
|
1508
|
+
const trimmed = uid.trim();
|
|
1509
|
+
if (!trimmed) return null;
|
|
1510
|
+
for (const [id, data] of this.users.entries()) {
|
|
1511
|
+
if (typeof data.firebaseUid === "string" && data.firebaseUid.trim() === trimmed) {
|
|
1512
|
+
return { id, data: structuredClone(data) };
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
return null;
|
|
1516
|
+
}
|
|
1517
|
+
async getRole(roleId) {
|
|
1518
|
+
const data = this.roles.get(roleId);
|
|
1519
|
+
return data ? { id: roleId, data: structuredClone(data) } : null;
|
|
1520
|
+
}
|
|
1521
|
+
async createUser(data, explicitId) {
|
|
1522
|
+
const id = explicitId ?? generateAutoId();
|
|
1523
|
+
if (this.users.has(id)) {
|
|
1524
|
+
throw new CallError("already-exists", `A user with ID "${id}" already exists.`);
|
|
1525
|
+
}
|
|
1526
|
+
const clean = stripInternalId(data);
|
|
1527
|
+
this.users.set(id, structuredClone(clean));
|
|
1528
|
+
return { id, data: structuredClone(clean) };
|
|
1529
|
+
}
|
|
1530
|
+
async setUser(id, data, options = {}) {
|
|
1531
|
+
const clean = stripInternalId(data);
|
|
1532
|
+
if (options.merge) {
|
|
1533
|
+
const current = this.users.get(id) ?? {};
|
|
1534
|
+
this.users.set(id, structuredClone({ ...current, ...clean }));
|
|
1535
|
+
} else {
|
|
1536
|
+
this.users.set(id, structuredClone(clean));
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
async hasAnyUser() {
|
|
1540
|
+
return this.users.size > 0;
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
var createLazyUserStore = (provider, names = {}) => {
|
|
1544
|
+
let store = null;
|
|
1545
|
+
const resolve = async () => {
|
|
1546
|
+
if (!store) {
|
|
1547
|
+
const db = await provider();
|
|
1548
|
+
store = new MongoUserStore(db, names);
|
|
1549
|
+
}
|
|
1550
|
+
return store;
|
|
1551
|
+
};
|
|
1552
|
+
return {
|
|
1553
|
+
async getUserById(id) {
|
|
1554
|
+
return resolve().then((s) => s.getUserById(id));
|
|
1555
|
+
},
|
|
1556
|
+
async findUserByEmail(email) {
|
|
1557
|
+
return resolve().then((s) => s.findUserByEmail(email));
|
|
1558
|
+
},
|
|
1559
|
+
async findUserByFirebaseUid(uid) {
|
|
1560
|
+
return resolve().then((s) => s.findUserByFirebaseUid(uid));
|
|
1561
|
+
},
|
|
1562
|
+
async getRole(roleId) {
|
|
1563
|
+
return resolve().then((s) => s.getRole(roleId));
|
|
1564
|
+
},
|
|
1565
|
+
async createUser(data, explicitId) {
|
|
1566
|
+
return resolve().then((s) => s.createUser(data, explicitId));
|
|
1567
|
+
},
|
|
1568
|
+
async setUser(id, data, options) {
|
|
1569
|
+
return resolve().then((s) => s.setUser(id, data, options));
|
|
1570
|
+
},
|
|
1571
|
+
async hasAnyUser() {
|
|
1572
|
+
return resolve().then((s) => s.hasAnyUser());
|
|
1573
|
+
}
|
|
1574
|
+
};
|
|
1575
|
+
};
|
|
1576
|
+
|
|
1577
|
+
// src/server/swagger.ts
|
|
1578
|
+
import swaggerUi from "swagger-ui-express";
|
|
1579
|
+
var roleSummary = (options) => {
|
|
1580
|
+
if (options.roles && options.roles.length > 0) {
|
|
1581
|
+
return `Requires role: ${options.roles.join(", ")}.`;
|
|
1582
|
+
}
|
|
1583
|
+
if (options.requireAuth) {
|
|
1584
|
+
return "Requires authentication.";
|
|
1585
|
+
}
|
|
1586
|
+
return "Public: no authentication required.";
|
|
1587
|
+
};
|
|
1588
|
+
var buildOpenApiSpec = (functions, config = {}) => {
|
|
1589
|
+
const paths = {};
|
|
1590
|
+
for (const [fnName, def] of Object.entries(functions)) {
|
|
1591
|
+
if (!def || !def.__isMongoCallable) continue;
|
|
1592
|
+
const options = def.options;
|
|
1593
|
+
const inputSchema = options.paramsSchema ?? {
|
|
1594
|
+
type: "object",
|
|
1595
|
+
additionalProperties: true
|
|
1596
|
+
};
|
|
1597
|
+
const outputSchema = options.responseSchema ?? {
|
|
1598
|
+
type: "object",
|
|
1599
|
+
additionalProperties: true
|
|
1600
|
+
};
|
|
1601
|
+
const requiresAuth = Boolean(options.requireAuth) || (options.roles?.length ?? 0) > 0;
|
|
1602
|
+
paths[`/${fnName}`] = {
|
|
1603
|
+
post: {
|
|
1604
|
+
summary: options.summary || `Execute ${fnName}`,
|
|
1605
|
+
description: (options.description ?? `RPC invocation for **${fnName}** following the \`{ data }\` protocol.`) + `
|
|
1606
|
+
|
|
1607
|
+
${roleSummary(options)}`,
|
|
1608
|
+
tags: options.tags || ["Functions"],
|
|
1609
|
+
security: requiresAuth ? [{ bearerAuth: [] }] : [],
|
|
1610
|
+
requestBody: {
|
|
1611
|
+
required: true,
|
|
1612
|
+
content: {
|
|
1613
|
+
"application/json": {
|
|
1614
|
+
schema: {
|
|
1615
|
+
type: "object",
|
|
1616
|
+
required: ["data"],
|
|
1617
|
+
properties: {
|
|
1618
|
+
data: inputSchema
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
},
|
|
1624
|
+
responses: {
|
|
1625
|
+
"200": {
|
|
1626
|
+
description: "Successful execution",
|
|
1627
|
+
content: {
|
|
1628
|
+
"application/json": {
|
|
1629
|
+
schema: {
|
|
1630
|
+
type: "object",
|
|
1631
|
+
properties: {
|
|
1632
|
+
result: outputSchema
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
},
|
|
1638
|
+
"400": {
|
|
1639
|
+
description: "Parameter validation error or unsafe payload (invalid-argument)"
|
|
1640
|
+
},
|
|
1641
|
+
"401": {
|
|
1642
|
+
description: "Unauthenticated or invalid JWT token (unauthenticated)"
|
|
1643
|
+
},
|
|
1644
|
+
"403": {
|
|
1645
|
+
description: "Insufficient role or read-only access (permission-denied)"
|
|
1646
|
+
},
|
|
1647
|
+
"429": {
|
|
1648
|
+
description: "Too many requests - Rate limit exceeded (resource-exhausted)"
|
|
1649
|
+
},
|
|
1650
|
+
"500": {
|
|
1651
|
+
description: "Internal server error (internal)"
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
return {
|
|
1658
|
+
openapi: "3.0.3",
|
|
1659
|
+
info: {
|
|
1660
|
+
title: config.title || "MongoCall API",
|
|
1661
|
+
version: config.version || "1.0.0",
|
|
1662
|
+
description: config.description || "Interactive API documentation auto-generated from `onCall` definitions."
|
|
1663
|
+
},
|
|
1664
|
+
servers: config.serverUrl ? [{ url: config.serverUrl }] : [{ url: "/" }],
|
|
1665
|
+
components: {
|
|
1666
|
+
securitySchemes: {
|
|
1667
|
+
bearerAuth: {
|
|
1668
|
+
type: "http",
|
|
1669
|
+
scheme: "bearer",
|
|
1670
|
+
bearerFormat: "JWT",
|
|
1671
|
+
description: "Enter your JWT token without the Bearer prefix"
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
},
|
|
1675
|
+
paths
|
|
1676
|
+
};
|
|
1677
|
+
};
|
|
1678
|
+
var setupSwaggerUI = (app, functions, config = {}) => {
|
|
1679
|
+
const isProd = process.env.NODE_ENV === "production";
|
|
1680
|
+
const enabled = config.enabled ?? !isProd;
|
|
1681
|
+
if (!enabled) return;
|
|
1682
|
+
const docsPath = config.path || "/docs";
|
|
1683
|
+
const spec = buildOpenApiSpec(functions, config);
|
|
1684
|
+
app.get(`${docsPath}.json`, (_req, res) => {
|
|
1685
|
+
res.json(spec);
|
|
1686
|
+
});
|
|
1687
|
+
app.use(
|
|
1688
|
+
docsPath,
|
|
1689
|
+
swaggerUi.serve,
|
|
1690
|
+
swaggerUi.setup(spec, {
|
|
1691
|
+
customSiteTitle: config.title || "MongoCall API Docs",
|
|
1692
|
+
swaggerOptions: {
|
|
1693
|
+
persistAuthorization: true,
|
|
1694
|
+
displayRequestDuration: true
|
|
1695
|
+
}
|
|
1696
|
+
})
|
|
1697
|
+
);
|
|
1698
|
+
};
|
|
1699
|
+
|
|
1700
|
+
// src/server/validator.ts
|
|
1701
|
+
import Ajv from "ajv";
|
|
1702
|
+
import addFormats from "ajv-formats";
|
|
1703
|
+
function createAjvInstance(config = {}) {
|
|
1704
|
+
const ajv = new Ajv({
|
|
1705
|
+
allErrors: config.allErrors ?? true,
|
|
1706
|
+
coerceTypes: config.coerceTypes ?? false,
|
|
1707
|
+
removeAdditional: config.removeAdditional ?? true,
|
|
1708
|
+
useDefaults: config.useDefaults ?? true,
|
|
1709
|
+
strict: false,
|
|
1710
|
+
allowUnionTypes: true,
|
|
1711
|
+
...config.rawAjvOptions
|
|
1712
|
+
});
|
|
1713
|
+
if (config.enableFormats !== false) {
|
|
1714
|
+
addFormats(ajv);
|
|
1715
|
+
ajv.addFormat("objectid", /^[a-fA-F0-9]{24}$/);
|
|
1716
|
+
}
|
|
1717
|
+
return ajv;
|
|
1718
|
+
}
|
|
1719
|
+
function formatAjvErrors(errors) {
|
|
1720
|
+
if (!errors) return [];
|
|
1721
|
+
return errors.map((err) => ({
|
|
1722
|
+
field: err.instancePath ? err.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root",
|
|
1723
|
+
rule: err.keyword,
|
|
1724
|
+
message: err.message ?? "Invalid value",
|
|
1725
|
+
params: err.params
|
|
1726
|
+
}));
|
|
1727
|
+
}
|
|
1728
|
+
function compileSchemaValidator(globalAjv, schema, overrideConfig) {
|
|
1729
|
+
if (overrideConfig) {
|
|
1730
|
+
return createAjvInstance(overrideConfig).compile(schema);
|
|
1731
|
+
}
|
|
1732
|
+
return globalAjv.compile(schema);
|
|
1733
|
+
}
|
|
1734
|
+
var clonePlainPayload = (payload) => {
|
|
1735
|
+
if (!isPlainObject(payload)) {
|
|
1736
|
+
return Array.isArray(payload) ? payload.map(clonePlainPayload) : payload;
|
|
1737
|
+
}
|
|
1738
|
+
const copy = {};
|
|
1739
|
+
for (const [key, value] of Object.entries(payload)) {
|
|
1740
|
+
copy[key] = clonePlainPayload(value);
|
|
1741
|
+
}
|
|
1742
|
+
return copy;
|
|
1743
|
+
};
|
|
1744
|
+
function validatePayload(validateFn, payload) {
|
|
1745
|
+
const target = clonePlainPayload(payload);
|
|
1746
|
+
const isValid = validateFn(target);
|
|
1747
|
+
if (!isValid) {
|
|
1748
|
+
throw new CallError(
|
|
1749
|
+
"invalid-argument",
|
|
1750
|
+
"Input parameters failed schema validation.",
|
|
1751
|
+
formatAjvErrors(validateFn.errors)
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
return target;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
// src/server/onCall.ts
|
|
1758
|
+
function onCall(optionsOrHandler, maybeHandler) {
|
|
1759
|
+
if (typeof optionsOrHandler === "function") {
|
|
1760
|
+
return {
|
|
1761
|
+
__isMongoCallable: true,
|
|
1762
|
+
options: {},
|
|
1763
|
+
handler: optionsOrHandler
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
return {
|
|
1767
|
+
__isMongoCallable: true,
|
|
1768
|
+
options: optionsOrHandler,
|
|
1769
|
+
handler: maybeHandler
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
var toOriginArray = (corsOrigin) => {
|
|
1773
|
+
if (Array.isArray(corsOrigin)) return corsOrigin;
|
|
1774
|
+
if (typeof corsOrigin === "string") {
|
|
1775
|
+
return corsOrigin.split(",").map((item) => item.trim()).filter(Boolean);
|
|
1776
|
+
}
|
|
1777
|
+
return [];
|
|
1778
|
+
};
|
|
1779
|
+
var resolveCorsOptions = (corsOrigin, isProd, credentials) => {
|
|
1780
|
+
if (corsOrigin === false) return null;
|
|
1781
|
+
if (corsOrigin === void 0) {
|
|
1782
|
+
return isProd ? null : { origin: true, credentials };
|
|
1783
|
+
}
|
|
1784
|
+
if (corsOrigin === true) {
|
|
1785
|
+
return { origin: true, credentials };
|
|
1786
|
+
}
|
|
1787
|
+
const origins = toOriginArray(corsOrigin);
|
|
1788
|
+
if (origins.length === 0) return null;
|
|
1789
|
+
return {
|
|
1790
|
+
origin: (origin, callback) => {
|
|
1791
|
+
if (!origin || origins.includes(origin)) {
|
|
1792
|
+
callback(null, true);
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
callback(new CallError("permission-denied", "Origin not allowed."));
|
|
1796
|
+
},
|
|
1797
|
+
credentials
|
|
1798
|
+
};
|
|
1799
|
+
};
|
|
1800
|
+
var isJsonParseError = (err) => typeof err === "object" && err !== null && "type" in err && err.type === "entity.parse.failed";
|
|
1801
|
+
var createCallApp = (functions, config = {}) => {
|
|
1802
|
+
const isProd = process.env.NODE_ENV === "production";
|
|
1803
|
+
const app = express();
|
|
1804
|
+
app.disable("x-powered-by");
|
|
1805
|
+
if (config.trustProxy !== void 0) {
|
|
1806
|
+
app.set("trust proxy", config.trustProxy);
|
|
1807
|
+
}
|
|
1808
|
+
const rawSecret = config.jwtOptions?.secret || config.jwtSecret || process.env.JWT_SECRET;
|
|
1809
|
+
const secretKey = rawSecret ? assertStrongJwtSecret(rawSecret) : null;
|
|
1810
|
+
const secretString = rawSecret ?? "";
|
|
1811
|
+
const swaggerEnabled = config.swagger?.enabled ?? !isProd;
|
|
1812
|
+
if (config.helmet !== false) {
|
|
1813
|
+
const helmetOptions = typeof config.helmet === "object" && config.helmet !== null ? config.helmet : { contentSecurityPolicy: swaggerEnabled ? false : void 0 };
|
|
1814
|
+
app.use(helmet(helmetOptions));
|
|
1815
|
+
}
|
|
1816
|
+
const cookie = config.cookies ?? {};
|
|
1817
|
+
const cookieEnabled = cookie.enabled ?? false;
|
|
1818
|
+
const sessionCookieName = cookie.sessionCookieName ?? "session";
|
|
1819
|
+
const corsOptions = resolveCorsOptions(config.corsOrigin, isProd, cookieEnabled);
|
|
1820
|
+
if (corsOptions) {
|
|
1821
|
+
app.use(cors(corsOptions));
|
|
1822
|
+
}
|
|
1823
|
+
if (config.rateLimit !== false) {
|
|
1824
|
+
app.use(createRateLimiter(config.rateLimit ?? { windowMs: 6e4, max: 120 }));
|
|
1825
|
+
}
|
|
1826
|
+
app.use(express.json({ limit: config.bodyLimit ?? "1mb" }));
|
|
1827
|
+
app.use((err, _req, res, next) => {
|
|
1828
|
+
if (isJsonParseError(err)) {
|
|
1829
|
+
res.status(400).json({
|
|
1830
|
+
error: {
|
|
1831
|
+
code: "invalid-argument",
|
|
1832
|
+
message: "Request body does not contain valid JSON."
|
|
1833
|
+
}
|
|
1834
|
+
});
|
|
1835
|
+
return;
|
|
1836
|
+
}
|
|
1837
|
+
next(err);
|
|
1838
|
+
});
|
|
1839
|
+
app.use(cookieParser());
|
|
1840
|
+
const dbProvider = config.dbProvider ?? (() => getDatabase(config.mongoUri, config.dbName));
|
|
1841
|
+
const store = config.store ?? createLazyUserStore(dbProvider, {
|
|
1842
|
+
users: config.usersCollection,
|
|
1843
|
+
roles: config.rolesCollection
|
|
1844
|
+
});
|
|
1845
|
+
const jwtOptions = config.jwtOptions ?? {};
|
|
1846
|
+
const authMiddleware = createAuthMiddleware({
|
|
1847
|
+
store,
|
|
1848
|
+
secret: secretString,
|
|
1849
|
+
algorithms: jwtOptions.algorithms,
|
|
1850
|
+
issuer: jwtOptions.issuer,
|
|
1851
|
+
audience: jwtOptions.audience,
|
|
1852
|
+
cookieName: sessionCookieName,
|
|
1853
|
+
cookieEnabled
|
|
1854
|
+
});
|
|
1855
|
+
const csrfMiddleware = createCsrfMiddleware({
|
|
1856
|
+
corsOrigins: toOriginArray(config.corsOrigin),
|
|
1857
|
+
sessionCookieName,
|
|
1858
|
+
csrfCookieName: cookie.csrfCookieName ?? "csrf",
|
|
1859
|
+
csrfHeaderName: cookie.csrfHeaderName ?? "x-csrf-token"
|
|
1860
|
+
});
|
|
1861
|
+
const apiBasePath = config.apiBasePath ?? "";
|
|
1862
|
+
if (config.auth?.enabled !== false && secretKey) {
|
|
1863
|
+
const authRouter = createAuthRouter({
|
|
1864
|
+
store,
|
|
1865
|
+
config,
|
|
1866
|
+
authenticate: authMiddleware,
|
|
1867
|
+
csrf: csrfMiddleware,
|
|
1868
|
+
authLimiter: createRateLimiter(
|
|
1869
|
+
config.auth?.loginRateLimit ?? { windowMs: 15 * 60 * 1e3, max: 40 }
|
|
1870
|
+
)
|
|
1871
|
+
});
|
|
1872
|
+
app.use(`${apiBasePath}/auth`, authRouter);
|
|
1873
|
+
}
|
|
1874
|
+
app.get(`${apiBasePath}/health`, async (_req, res) => {
|
|
1875
|
+
try {
|
|
1876
|
+
const db = await dbProvider();
|
|
1877
|
+
const ok = await pingDatabase(db);
|
|
1878
|
+
if (!ok) {
|
|
1879
|
+
res.status(503).json({ status: "degraded", database: "disconnected" });
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
res.json({ status: "ok", database: "connected" });
|
|
1883
|
+
} catch {
|
|
1884
|
+
res.status(503).json({ status: "degraded", database: "disconnected" });
|
|
1885
|
+
}
|
|
1886
|
+
});
|
|
1887
|
+
setupSwaggerUI(app, functions, config.swagger);
|
|
1888
|
+
const globalAjv = createAjvInstance(config.validator);
|
|
1889
|
+
const compiledValidators = /* @__PURE__ */ new Map();
|
|
1890
|
+
const functionLimiters = /* @__PURE__ */ new Map();
|
|
1891
|
+
for (const [fnName, def] of Object.entries(functions)) {
|
|
1892
|
+
if (!Object.hasOwn(functions, fnName) || !def?.__isMongoCallable) continue;
|
|
1893
|
+
if (def.options.paramsSchema) {
|
|
1894
|
+
compiledValidators.set(
|
|
1895
|
+
fnName,
|
|
1896
|
+
compileSchemaValidator(globalAjv, def.options.paramsSchema, def.options.validatorOptions)
|
|
1897
|
+
);
|
|
1898
|
+
}
|
|
1899
|
+
if (def.options.rateLimit) {
|
|
1900
|
+
functionLimiters.set(fnName, createRateLimiter(def.options.rateLimit));
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
app.post(`${apiBasePath}/:fnName`, async (req, res) => {
|
|
1904
|
+
const rawParam = req.params.fnName;
|
|
1905
|
+
const fnName = Array.isArray(rawParam) ? rawParam[0] : rawParam;
|
|
1906
|
+
if (!fnName || !Object.hasOwn(functions, fnName)) {
|
|
1907
|
+
res.status(404).json({
|
|
1908
|
+
error: { code: "not-found", message: `Function "${fnName}" does not exist.` }
|
|
1909
|
+
});
|
|
1910
|
+
return;
|
|
1911
|
+
}
|
|
1912
|
+
const callable = functions[fnName];
|
|
1913
|
+
if (!callable || !callable.__isMongoCallable) {
|
|
1914
|
+
res.status(404).json({
|
|
1915
|
+
error: { code: "not-found", message: `Function "${fnName}" does not exist.` }
|
|
1916
|
+
});
|
|
1917
|
+
return;
|
|
1918
|
+
}
|
|
1919
|
+
const fnLimiter = functionLimiters.get(fnName);
|
|
1920
|
+
if (fnLimiter) {
|
|
1921
|
+
await new Promise((resolve) => {
|
|
1922
|
+
fnLimiter(req, res, () => resolve());
|
|
1923
|
+
});
|
|
1924
|
+
if (res.headersSent) return;
|
|
1925
|
+
}
|
|
1926
|
+
try {
|
|
1927
|
+
const options = callable.options;
|
|
1928
|
+
const caller = await authenticateRequest(req, {
|
|
1929
|
+
store,
|
|
1930
|
+
secret: secretString,
|
|
1931
|
+
algorithms: jwtOptions.algorithms,
|
|
1932
|
+
issuer: jwtOptions.issuer,
|
|
1933
|
+
audience: jwtOptions.audience,
|
|
1934
|
+
cookieName: sessionCookieName,
|
|
1935
|
+
cookieEnabled
|
|
1936
|
+
});
|
|
1937
|
+
const protectedByRole = Boolean(options.roles?.length);
|
|
1938
|
+
const requiresPasswordRotation = (options.requireAuth || protectedByRole) && options.allowPasswordRotationGate !== true;
|
|
1939
|
+
if (caller && caller.mustChangePassword && requiresPasswordRotation) {
|
|
1940
|
+
throw new CallError(
|
|
1941
|
+
"failed-precondition",
|
|
1942
|
+
"Password rotation is required before accessing this function."
|
|
1943
|
+
);
|
|
1944
|
+
}
|
|
1945
|
+
if (options.requireAuth && !caller) {
|
|
1946
|
+
throw new CallError("unauthenticated", "This function requires authentication.");
|
|
1947
|
+
}
|
|
1948
|
+
let access = null;
|
|
1949
|
+
let authContext = null;
|
|
1950
|
+
if (caller) {
|
|
1951
|
+
access = await resolveCallerRole(store, caller);
|
|
1952
|
+
authContext = {
|
|
1953
|
+
uid: caller.uid,
|
|
1954
|
+
userDocId: caller.userDocId,
|
|
1955
|
+
email: caller.email ?? void 0,
|
|
1956
|
+
emailVerified: caller.emailVerified,
|
|
1957
|
+
displayName: caller.displayName ?? void 0,
|
|
1958
|
+
role: access.role,
|
|
1959
|
+
readOnly: access.readOnly,
|
|
1960
|
+
authMethod: "classic",
|
|
1961
|
+
claims: caller.tokenClaims,
|
|
1962
|
+
user: caller.userData
|
|
1963
|
+
};
|
|
1964
|
+
}
|
|
1965
|
+
if (options.roles && options.roles.length > 0) {
|
|
1966
|
+
if (!caller || !access) {
|
|
1967
|
+
throw new CallError("unauthenticated", "This function requires authentication.");
|
|
1968
|
+
}
|
|
1969
|
+
assertAllowedRole(access, options.roles, {
|
|
1970
|
+
superadminBypass: options.superadminBypass,
|
|
1971
|
+
writeAccess: options.writeAccess
|
|
1972
|
+
});
|
|
1973
|
+
} else if (options.writeAccess && access) {
|
|
1974
|
+
if (access.readOnly && !(options.superadminBypass !== false && access.role === "superadmin")) {
|
|
1975
|
+
throw new CallError(
|
|
1976
|
+
"permission-denied",
|
|
1977
|
+
`Role "${access.role}" has read-only access.`
|
|
1978
|
+
);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
let payload = req.body?.data ?? {};
|
|
1982
|
+
const sanitizeMode = options.noSqlSanitize ?? config.noSqlSanitize ?? "reject";
|
|
1983
|
+
payload = sanitizeNoSqlPayload(payload, sanitizeMode);
|
|
1984
|
+
const validateFn = compiledValidators.get(fnName);
|
|
1985
|
+
if (validateFn) {
|
|
1986
|
+
payload = validatePayload(validateFn, payload);
|
|
1987
|
+
}
|
|
1988
|
+
const db = await dbProvider();
|
|
1989
|
+
const result = await callable.handler(payload, {
|
|
1990
|
+
db,
|
|
1991
|
+
auth: authContext,
|
|
1992
|
+
rawHeaders: req.headers
|
|
1993
|
+
});
|
|
1994
|
+
res.status(200).json({ result });
|
|
1995
|
+
} catch (err) {
|
|
1996
|
+
if (isCallError(err)) {
|
|
1997
|
+
res.status(err.statusCode).json(toCallErrorBody(err));
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
console.error(`[mongo-call:${fnName}] Internal error:`, err);
|
|
2001
|
+
res.status(500).json({
|
|
2002
|
+
error: { code: "internal", message: "Internal server error." }
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
});
|
|
2006
|
+
app.use((req, res) => {
|
|
2007
|
+
res.status(404).json({
|
|
2008
|
+
error: { code: "not-found", message: `Route "${req.path}" does not exist.` }
|
|
2009
|
+
});
|
|
2010
|
+
});
|
|
2011
|
+
app.use((err, _req, res, _next) => {
|
|
2012
|
+
if (isCallError(err)) {
|
|
2013
|
+
res.status(err.statusCode).json(toCallErrorBody(err));
|
|
2014
|
+
return;
|
|
2015
|
+
}
|
|
2016
|
+
console.error("[mongo-call] Unhandled error:", err);
|
|
2017
|
+
res.status(500).json({
|
|
2018
|
+
error: { code: "internal", message: "Internal server error." }
|
|
2019
|
+
});
|
|
2020
|
+
});
|
|
2021
|
+
return app;
|
|
2022
|
+
};
|
|
2023
|
+
var isServerConfig = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2024
|
+
var startCallServer = async (functions, portOrConfig, config = {}) => {
|
|
2025
|
+
loadEnv();
|
|
2026
|
+
const explicit = isServerConfig(portOrConfig) ? portOrConfig : config;
|
|
2027
|
+
const loadEnvConfig = () => {
|
|
2028
|
+
try {
|
|
2029
|
+
return loadServerConfig();
|
|
2030
|
+
} catch (err) {
|
|
2031
|
+
if (explicit.mongoUri) return {};
|
|
2032
|
+
throw err;
|
|
2033
|
+
}
|
|
2034
|
+
};
|
|
2035
|
+
const merged = { ...loadEnvConfig(), ...explicit };
|
|
2036
|
+
const resolvedPort = isServerConfig(portOrConfig) ? portOrConfig.port ?? 4e3 : typeof portOrConfig === "number" ? portOrConfig : config.port ?? 4e3;
|
|
2037
|
+
const dbProvider = () => getDatabase(merged.mongoUri, merged.dbName);
|
|
2038
|
+
const store = merged.store ?? createLazyUserStore(dbProvider, {
|
|
2039
|
+
users: merged.usersCollection,
|
|
2040
|
+
roles: merged.rolesCollection
|
|
2041
|
+
});
|
|
2042
|
+
await getDatabase(merged.mongoUri, merged.dbName);
|
|
2043
|
+
const app = createCallApp(functions, { ...merged, dbProvider, store });
|
|
2044
|
+
const server = app.listen(resolvedPort, () => {
|
|
2045
|
+
console.log(`mongo-call server listening on http://localhost:${resolvedPort}`);
|
|
2046
|
+
const swaggerEnabled = merged.swagger?.enabled ?? process.env.NODE_ENV !== "production";
|
|
2047
|
+
if (swaggerEnabled) {
|
|
2048
|
+
console.log(
|
|
2049
|
+
`Swagger UI available at http://localhost:${resolvedPort}${merged.swagger?.path ?? "/docs"}`
|
|
2050
|
+
);
|
|
2051
|
+
}
|
|
2052
|
+
});
|
|
2053
|
+
const shutdown = async () => {
|
|
2054
|
+
server.close();
|
|
2055
|
+
await closeDatabase();
|
|
2056
|
+
process.exit(0);
|
|
2057
|
+
};
|
|
2058
|
+
process.on("SIGINT", () => void shutdown());
|
|
2059
|
+
process.on("SIGTERM", () => void shutdown());
|
|
2060
|
+
return server;
|
|
2061
|
+
};
|
|
2062
|
+
|
|
2063
|
+
// src/server/index.ts
|
|
2064
|
+
import { ObjectId as ObjectId2 } from "mongodb";
|
|
2065
|
+
import { SignJWT as SignJWT2 } from "jose";
|
|
2066
|
+
export {
|
|
2067
|
+
CallError,
|
|
2068
|
+
InMemoryUserStore,
|
|
2069
|
+
MongoUserStore,
|
|
2070
|
+
ObjectId2 as ObjectId,
|
|
2071
|
+
SignJWT2 as SignJWT,
|
|
2072
|
+
assertAllowedRole,
|
|
2073
|
+
assertPasswordComplexity,
|
|
2074
|
+
closeDatabase,
|
|
2075
|
+
createAjvInstance,
|
|
2076
|
+
createCallApp,
|
|
2077
|
+
createLazyUserStore,
|
|
2078
|
+
ensureMongoIndexes,
|
|
2079
|
+
getDatabase,
|
|
2080
|
+
hashPassword,
|
|
2081
|
+
isCallError,
|
|
2082
|
+
loadEnv,
|
|
2083
|
+
loadServerConfig,
|
|
2084
|
+
onCall,
|
|
2085
|
+
pingDatabase,
|
|
2086
|
+
resolveCallerRole,
|
|
2087
|
+
sanitizeNoSqlPayload,
|
|
2088
|
+
signSessionToken,
|
|
2089
|
+
startCallServer,
|
|
2090
|
+
toObjectId,
|
|
2091
|
+
validatePayload,
|
|
2092
|
+
verifyPassword,
|
|
2093
|
+
verifySessionToken
|
|
2094
|
+
};
|