forked from geturbackend/urBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.controller.js
More file actions
3085 lines (2612 loc) · 101 KB
/
Copy pathproject.controller.js
File metadata and controls
3085 lines (2612 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const mongoose = require("mongoose");
const net = require("net");
const dns = require("dns").promises;
const { Project } = require("@urbackend/common");
const { Developer } = require("@urbackend/common");
const { Log } = require("@urbackend/common");
const { getStorage } = require("@urbackend/common");
const { randomUUID } = require("crypto");
const {
createProjectSchema,
createCollectionSchema,
updateExternalConfigSchema,
updateAuthProvidersSchema,
sanitizeObjectId,
sanitizeNonEmptyString,
} = require("@urbackend/common");
const { generateApiKey, hashApiKey } = require("@urbackend/common");
const { z } = require("zod");
const { encrypt, decrypt } = require("@urbackend/common");
const { URL } = require("url");
const path = require("path");
const axios = require("axios");
const { getConnection } = require("@urbackend/common");
const { getCompiledModel } = require("@urbackend/common");
const { QueryEngine } = require("@urbackend/common");
const { storageRegistry } = require("@urbackend/common");
const { AppError, webhookQueue, enqueueCollectionCleanup, syncCollectionCleanup } = require("@urbackend/common");
const { resolveEffectivePlan } = require("@urbackend/common");
const {
deleteProjectByApiKeyCache,
setProjectById,
getProjectById,
deleteProjectById,
} = require("@urbackend/common");
const { isProjectStorageExternal, getBucket } = require("@urbackend/common");
const { getPresignedUploadUrl } = require("@urbackend/common");
const { verifyUploadedFile } = require("@urbackend/common");
const { getPublicIp } = require("@urbackend/common");
const { clearCompiledModel } = require("@urbackend/common");
const { createUniqueIndexes, ApiAnalytics, MailLog } = require("@urbackend/common");
const { getProjectAccessQuery, getProjectRole, Invitation } = require("@urbackend/common");
const { emitEvent } = require('../utils/emitEvent');
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const SAFETY_MAX_BYTES = 100 * 1024 * 1024;
const CONFIRM_UPLOAD_SIZE_TOLERANCE_BYTES = 64;
const validateUsersSchema = (schema) => {
if (!Array.isArray(schema)) return false;
const sanitizedSchema = sanitizeSchemaFields(schema);
const hasEmail = sanitizedSchema.find(
(f) =>
normalizeFieldKey(f.key).toLowerCase() === "email" &&
normalizeFieldType(f.type) === "string" &&
isRequiredField(f.required),
);
const hasPassword = sanitizedSchema.find(
(f) =>
normalizeFieldKey(f.key).toLowerCase() === "password" &&
normalizeFieldType(f.type) === "string" &&
isRequiredField(f.required),
);
return !!(hasEmail && hasPassword);
};
const normalizeFieldKey = (key) =>
String(key || "")
.replace(/\uFEFF/g, "")
.trim();
const normalizeFieldType = (type) =>
String(type || "")
.trim()
.toLowerCase();
const isRequiredField = (required) =>
required === true ||
required === 1 ||
String(required).trim().toLowerCase() === "true" ||
String(required).trim() === "1";
const toPlainObject = (value) => {
if (!value || typeof value !== "object") return value;
if (typeof value.toObject === "function") {
return value.toObject({ depopulate: true });
}
if (value._doc && typeof value._doc === "object") {
return { ...value._doc };
}
return value;
};
const sanitizeSchemaFields = (schema = []) => {
if (!Array.isArray(schema)) return [];
return schema
.map((rawField) => {
const field = toPlainObject(rawField);
if (!field || typeof field !== "object") return null;
const normalizedKey = normalizeFieldKey(field.key);
if (!normalizedKey) return null;
const next = { ...field, key: normalizedKey };
if (field.default !== undefined) {
next.default = field.default;
}
if (Array.isArray(field.fields)) {
next.fields = sanitizeSchemaFields(field.fields);
}
if (field.items && typeof field.items === "object") {
next.items = { ...field.items };
if (Array.isArray(field.items.fields)) {
next.items.fields = sanitizeSchemaFields(field.items.fields);
}
}
return next;
})
.filter(Boolean);
};
const getDefaultRlsForCollection = (collectionName, schema = []) => {
const normalizedName = String(collectionName || "").toLowerCase();
const keys = sanitizeSchemaFields(schema).map((f) => f.key);
let ownerField = "userId";
if (normalizedName === "users") {
ownerField = "_id";
} else if (keys.includes("userId")) {
ownerField = "userId";
} else if (keys.includes("ownerId")) {
ownerField = "ownerId";
}
return {
enabled: false,
mode: "public-read",
ownerField,
requireAuthForWrite: true,
};
};
const SOCIAL_PROVIDER_KEYS = ["github", "google"];
const sanitizeAuthProviders = (authProviders = {}) => {
return SOCIAL_PROVIDER_KEYS.reduce((acc, provider) => {
const config = authProviders?.[provider] || {};
const cs = config.clientSecret;
const hasClientSecret =
cs != null &&
typeof cs === "object" &&
Object.keys(cs).length > 0;
acc[provider] = {
enabled: !!config.enabled,
clientId: config.clientId || "",
hasClientSecret,
};
return acc;
}, {});
};
const sanitizeProjectResponse = (projectObj) => {
delete projectObj.publishableKey;
delete projectObj.secretKey;
delete projectObj.jwtSecret;
const resendConfig = projectObj.resendApiKey;
projectObj.hasResendApiKey =
resendConfig != null &&
typeof resendConfig === "object" &&
Object.keys(resendConfig).length > 0;
delete projectObj.resendApiKey;
projectObj.authProviders = sanitizeAuthProviders(projectObj.authProviders);
if (projectObj.collections && Array.isArray(projectObj.collections)) {
projectObj.collections = projectObj.collections.map((col) => {
if (col.name === "users" && col.model) {
return {
...col,
model: col.model.filter((m) => m.key !== "password"),
rls: col.rls || getDefaultRlsForCollection(col.name, col.model),
};
}
return {
...col,
rls: col.rls || getDefaultRlsForCollection(col.name, col.model),
};
});
}
return projectObj;
};
const parsePositiveSize = (size) => {
const numericSize = Number(size);
if (!Number.isFinite(numericSize) || numericSize <= 0) {
return null;
}
return numericSize;
};
const normalizeProjectPath = (projectId, inputPath) => {
if (typeof inputPath !== "string") {
return null;
}
let decodedPath = inputPath;
try {
decodedPath = decodeURIComponent(inputPath);
} catch {
return null;
}
const normalizedPath = path.posix.normalize(decodedPath).replace(/^\/+/, "");
const segments = normalizedPath.split("/").filter(Boolean);
if (segments.length < 2) {
return null;
}
if (segments[0] !== String(projectId)) {
return null;
}
if (segments.some((segment) => segment === "." || segment === "..")) {
return null;
}
return normalizedPath;
};
const bestEffortDeleteUploadedObject = async (project, filePath) => {
try {
const supabase = await getStorage(project);
const bucket = getBucket(project);
await supabase.storage.from(bucket).remove([filePath]);
} catch {
// ignore cleanup failures; the primary response should still be returned
}
};
module.exports.createProject = async (req, res) => {
const executeOperation = async (session) => {
const { name, description, siteUrl } = createProjectSchema.parse(req.body);
if (req.projectLimit !== undefined) {
const queryOpts = session ? { session } : {};
const currentCount = await Project.countDocuments(
{ owner: req.user._id },
queryOpts,
);
if (currentCount >= req.projectLimit) {
const error = new Error(`Project limit reached (${req.projectLimit}). Please upgrade your plan to create more projects.`);
error.status = 403;
throw error;
}
}
const rawPublishableKey = generateApiKey("pk_live_");
const hashedPublishableKey = hashApiKey(rawPublishableKey);
const rawSecretKey = generateApiKey("sk_live_");
const hashedSecretKey = hashApiKey(rawSecretKey);
const rawJwtSecret = generateApiKey("jwt_");
const newProject = new Project({
name,
description,
owner: req.user._id,
publishableKey: hashedPublishableKey,
secretKey: hashedSecretKey,
jwtSecret: rawJwtSecret,
siteUrl: siteUrl || "",
});
const saveOpts = session ? { session } : {};
await newProject.save(saveOpts);
const projectObj = newProject.toObject();
projectObj.publishableKey = rawPublishableKey;
projectObj.secretKey = rawSecretKey;
delete projectObj.jwtSecret;
projectObj.authProviders = sanitizeAuthProviders(projectObj.authProviders);
return { projectObj, newProject };
};
let session = null;
try {
session = await mongoose.startSession();
session.startTransaction();
const { projectObj, newProject } = await executeOperation(session);
await session.commitTransaction();
session.endSession();
emitEvent(req.user._id, 'project_created', { projectName: projectObj.name }, newProject._id);
return res.status(201).json(projectObj);
} catch (err) {
if (session) {
try { await session.abortTransaction(); } catch (e) {}
session.endSession();
}
if (err.message && (err.message.includes("Transaction numbers are only allowed") || err.message.includes("buffering timed out"))) {
try {
const { projectObj, newProject } = await executeOperation(null);
emitEvent(req.user._id, 'project_created', { projectName: projectObj.name }, newProject._id);
return res.status(201).json(projectObj);
} catch (retryErr) {
if (retryErr instanceof z.ZodError) return res.status(400).json({ error: retryErr.issues });
return res.status(retryErr.status || 500).json({ error: retryErr.message });
}
}
if (err instanceof z.ZodError) return res.status(400).json({ error: err.issues });
return res.status(err.status || 500).json({ error: err.message });
}
};
module.exports.getAllProject = async (req, res) => {
try {
const projects = await Project.find(getProjectAccessQuery(req.user._id))
.select("name description databaseUsed databaseLimit storageUsed storageLimit updatedAt isAuthEnabled collections owner members")
.lean();
const projectIds = projects.map(p => p._id);
const recentLogs = await Log.aggregate([
{ $match: { projectId: { $in: projectIds } } },
{ $sort: { timestamp: -1 } },
{
$group: {
_id: "$projectId",
logs: { $topN: { n: 100, sortBy: { timestamp: -1 }, output: { status: "$status" } } }
}
},
{
$project: {
errorCount: {
$size: {
$filter: { input: "$logs", as: "l", cond: { $gte: ["$$l.status", 400] } }
}
},
successCount: {
$size: {
$filter: { input: "$logs", as: "l", cond: { $lt: ["$$l.status", 400] } }
}
}
}
}
]);
const logsMap = recentLogs.reduce((acc, log) => {
acc[log._id.toString()] = log;
return acc;
}, {});
const enrichedProjects = projects.map(project => {
const stats = logsMap[project._id.toString()];
let health = 'healthy';
if (stats) {
const total = stats.errorCount + stats.successCount;
const errorRate = stats.errorCount / total;
if (errorRate > 0.2) health = 'warning';
}
return {
...project,
health,
collectionsCount: project.collections?.length || 0,
metrics: {
database: { used: project.databaseUsed, limit: project.databaseLimit },
storage: { used: project.storageUsed, limit: project.storageLimit }
}
};
});
res.status(200).json(enrichedProjects);
} catch (err) {
res.status(500).json({ error: err.message });
}
};
module.exports.getSingleProject = async (req, res) => {
try {
let projectObj = await getProjectById(req.params.projectId);
if (!projectObj) {
const project = await Project.findOne({
_id: req.params.projectId,
...getProjectAccessQuery(req.user._id),
}).select(
"-publishableKey -secretKey -jwtSecret " +
"+authProviders.github.clientSecret.encrypted " +
"+authProviders.github.clientSecret.iv " +
"+authProviders.github.clientSecret.tag " +
"+authProviders.google.clientSecret.encrypted " +
"+authProviders.google.clientSecret.iv " +
"+authProviders.google.clientSecret.tag " +
"+resendApiKey.encrypted " +
"+resendApiKey.iv " +
"+resendApiKey.tag",
);
if (!project) return res.status(404).json({ success: false, data: {}, message: "Project not found." });
projectObj = project.toObject();
await setProjectById(req.params.projectId, projectObj);
}
if (!getProjectRole(projectObj, req.user._id)) {
throw new AppError(403, "Access denied.");
}
res.json(sanitizeProjectResponse(projectObj));
} catch (err) {
res.status(500).json({ error: err.message });
}
};
module.exports.regenerateApiKey = async (req, res) => {
try {
const { keyType } = req.body;
if (keyType !== "publishable" && keyType !== "secret") {
return res
.status(400)
.json({ error: "Invalid keyType. Must be 'publishable' or 'secret'." });
}
const prefix = keyType === "publishable" ? "pk_live_" : "sk_live_";
const newApiKey = generateApiKey(prefix);
const hashed = hashApiKey(newApiKey);
const oldApiProj = await Project.findOne({
_id: req.params.projectId,
...getProjectAccessQuery(req.user._id),
}).select("publishableKey secretKey");
if (!oldApiProj)
return res.status(404).json({ error: "Project not found." });
await deleteProjectByApiKeyCache(oldApiProj.publishableKey);
await deleteProjectByApiKeyCache(oldApiProj.secretKey);
const updateField =
keyType === "publishable"
? { publishableKey: hashed }
: { secretKey: hashed };
const project = await Project.findOneAndUpdate(
{ _id: req.params.projectId, ...getProjectAccessQuery(req.user._id) },
{ $set: updateField },
{ new: true },
);
if (!project) return res.status(404).json({ error: "Project not found." });
const projectObj = project.toObject();
delete projectObj.publishableKey;
delete projectObj.secretKey;
delete projectObj.jwtSecret;
res.json({ apiKey: newApiKey, keyType, project: projectObj });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
const isNamespaceNotFoundError = (err) => {
return err && (err.code === 26 || /ns not found/i.test(err.message));
};
const dropCollectionIfExists = async (connection, collectionName) => {
try {
await connection.db.dropCollection(collectionName);
} catch (err) {
if (!isNamespaceNotFoundError(err)) {
throw err;
}
}
};
/**
* Convert a dotted-decimal IPv4 address string to a 32-bit unsigned integer.
* @param {string} ip - IPv4 address in dotted-decimal notation (e.g., '192.168.1.1')
* @returns {number} 32-bit unsigned integer representation of the IPv4 address
*/
function ipv4ToInt(ip) {
return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0;
}
/**
* Check if an IPv4 address falls within any restricted or reserved IP range.
* Blocks loopback (127.0.0.0/8), RFC-1918 private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16),
* link-local and cloud metadata (169.254.0.0/16), and unspecified (0.0.0.0/8) addresses to prevent SSRF attacks.
* @param {string} ip - IPv4 address to validate
* @returns {boolean} True if the IP is restricted, false otherwise
*/
function isRestrictedIPv4(ip) {
const n = ipv4ToInt(ip);
// Loopback 127.0.0.0/8
if (n >= ipv4ToInt("127.0.0.0") && n <= ipv4ToInt("127.255.255.255")) return true;
// RFC-1918: 10.0.0.0/8
if (n >= ipv4ToInt("10.0.0.0") && n <= ipv4ToInt("10.255.255.255")) return true;
// RFC-1918: 172.16.0.0/12
if (n >= ipv4ToInt("172.16.0.0") && n <= ipv4ToInt("172.31.255.255")) return true;
// RFC-1918: 192.168.0.0/16
if (n >= ipv4ToInt("192.168.0.0") && n <= ipv4ToInt("192.168.255.255")) return true;
// Link-local / cloud instance metadata (AWS, GCP, Azure): 169.254.0.0/16
if (n >= ipv4ToInt("169.254.0.0") && n <= ipv4ToInt("169.254.255.255")) return true;
// Unspecified: 0.0.0.0/8
if (n >= ipv4ToInt("0.0.0.0") && n <= ipv4ToInt("0.255.255.255")) return true;
return false;
}
/**
* Check if an IPv6 address falls within any restricted or reserved range.
* Blocks loopback (::1), unspecified (::), link-local (fe80::/10), IPv6 Unique Local Addresses (fc00::/7),
* and IPv4-mapped IPv6 addresses that resolve to restricted IPv4 ranges to prevent SSRF attacks.
* @param {string} ip - IPv6 address to validate
* @returns {boolean} True if the IP is restricted, false otherwise
*/
function isRestrictedIPv6(ip) {
const expanded = ip.replace(/^\[|\]$/g, "").toLowerCase();
// IPv6 loopback ::1
if (expanded === "::1" || expanded === "0:0:0:0:0:0:0:1") return true;
// IPv6 unspecified ::
if (expanded === "::" || expanded === "0:0:0:0:0:0:0:0") return true;
// IPv4-mapped IPv6 addresses (::ffff:x.x.x.x)
const mapped = expanded.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
if (mapped && isRestrictedIPv4(mapped[1])) return true;
// IPv6 link-local fe80::/10 (fe80: through febf:)
if (/^fe[89ab]/.test(expanded)) return true;
// IPv6 ULA (Unique Local Address) fc00::/7
if (expanded.startsWith("fc") || expanded.startsWith("fd")) return true;
return false;
}
/**
* Check if an IP address (either IPv4 or IPv6) is restricted or falls within a reserved range.
* Delegates to isRestrictedIPv4() or isRestrictedIPv6() based on the IP version.
* @param {string} ip - IP address to validate
* @returns {boolean} True if the IP is restricted, false otherwise
*/
function isRestrictedIP(ip) {
if (net.isIPv4(ip)) return isRestrictedIPv4(ip);
if (net.isIPv6(ip)) return isRestrictedIPv6(ip);
return false;
}
/**
* Validate a URI to ensure it does not target restricted hosts or IP ranges (SSRF prevention).
* Performs DNS resolution on hostnames to check both A and AAAA records against restricted ranges.
* Blocks loopback, RFC-1918 private ranges, cloud metadata endpoints, and other reserved IP ranges.
* @async
* @param {string} uri - The URI to validate
* @returns {Promise<boolean>} True if the URI is safe to connect to, false if it targets a restricted host
*/
const isSafeUri = async (uri) => {
try {
const parsed = new URL(uri);
const host = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
// Block well-known loopback and internal hostnames
const blockedHostnames = ["localhost", "metadata.google.internal"];
if (blockedHostnames.includes(host)) return false;
// Reject mongodb+srv:// URIs as they perform hidden SRV/TXT discovery
// We cannot safely validate all targets without resolving SRV records
if (uri.toLowerCase().includes("mongodb+srv://")) return false;
// If the host is a bare IPv4 or IPv6 address, check all restricted ranges
if (net.isIPv4(host) || net.isIPv6(host)) {
return !isRestrictedIP(host);
}
// For hostnames, perform DNS resolution to check both A and AAAA records
const [ipv4Result, ipv6Result] = await Promise.allSettled([
dns.resolve4(host),
dns.resolve6(host),
]);
const resolved = [
...(ipv4Result.status === "fulfilled" ? ipv4Result.value : []),
...(ipv6Result.status === "fulfilled" ? ipv6Result.value : []),
];
// If no addresses resolved, treat as unsafe
if (resolved.length === 0) return false;
// Check all resolved addresses for restricted ranges
if (resolved.some((addr) => isRestrictedIP(addr))) return false;
return true;
} catch (e) {
return false;
}
};
module.exports.updateExternalConfig = async (req, res) => {
try {
const { projectId } = req.params;
const validatedData = updateExternalConfigSchema.parse(req.body);
const { dbUri, storageUrl, storageKey, storageProvider } = validatedData;
const updateData = {};
if (dbUri) {
if (!(await isSafeUri(dbUri)))
return res.status(400).json({
success: false,
data: {},
message: "DB URI is pointing to a restricted host, internal network, or unsupported URI format.",
});
updateData["resources.db.config"] = encrypt(JSON.stringify({ dbUri }));
updateData["resources.db.isExternal"] = true;
console.log("Verifying connection to:", projectId);
try {
const tempConn = mongoose.createConnection(dbUri, {
serverSelectionTimeoutMS: 5000,
});
await tempConn.asPromise();
await tempConn.close();
} catch (connErr) {
console.error("Verification Connection Failed:", connErr.message);
let errorMsg = "Could not connect to the provided MongoDB URI.";
if (
connErr.message.includes("Server selection timed out") ||
connErr.message.includes("Could not connect")
) {
const serverIp = await getPublicIp();
errorMsg = `Access Denied: Please whitelist Server IP [${serverIp}] in MongoDB Atlas.`;
}
return res.status(400).json({ success: false, data: {}, message: errorMsg });
}
}
if (storageUrl && storageKey) {
const storageConfig = {
storageUrl,
storageKey,
storageProvider: storageProvider || "supabase",
};
updateData["resources.storage.config"] = encrypt(
JSON.stringify(storageConfig),
);
updateData["resources.storage.isExternal"] = true;
}
const project = await Project.findOneAndUpdate(
{ _id: projectId, ...getProjectAccessQuery(req.user._id) },
{ $set: updateData },
{ new: true },
);
if (!project)
return res.status(404).json({ success: false, data: {}, message: "Project not found or access denied." });
res.status(200).json({ success: true, data: {}, message: "External configuration updated successfully." });
} catch (err) {
if (err instanceof z.ZodError) {
return res.status(400).json({ success: false, data: {}, message: "Invalid request data." });
}
console.error("External Config Error:", err);
res.status(500).json({ success: false, data: {}, message: "Failed to update external configuration." });
}
};
module.exports.deleteExternalDbConfig = async (req, res) => {
try {
const parsedBody = z
.object({
projectId: z.string(),
})
.parse(req.body);
const { projectId } = parsedBody;
const project = await Project.findOne({
_id: { $eq: projectId },
...getProjectAccessQuery(req.user._id),
});
if (!project)
return res
.status(404)
.json({ error: "Project not found or access denied." });
project.resources.db.isExternal = false;
project.resources.db.config = null;
await project.save();
res
.status(200)
.json({ message: "External configuration deleted successfully." });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
module.exports.deleteExternalStorageConfig = async (req, res) => {
try {
const parsedBody = z
.object({
projectId: z.string(),
})
.parse(req.body);
const { projectId } = parsedBody;
const project = await Project.findOne({
_id: { $eq: projectId },
...getProjectAccessQuery(req.user._id),
});
if (!project)
return res
.status(404)
.json({ error: "Project not found or access denied." });
project.resources.storage.isExternal = false;
project.resources.storage.config = null;
await project.save();
await deleteProjectById(projectId);
await setProjectById(projectId, project.toObject());
res
.status(200)
.json({ message: "External configuration deleted successfully." });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
module.exports.createCollection = async (req, res) => {
const executeOperation = async (session) => {
const { projectId, collectionName, schema } = createCollectionSchema.parse(req.body);
const projectQuery = Project.findOne({
_id: projectId,
...getProjectAccessQuery(req.user._id),
});
if (session) projectQuery.session(session);
const project = await projectQuery;
if (!project) {
const error = new Error("Project not found");
error.status = 404;
throw error;
}
const exists = project.collections.find((c) => c.name === collectionName);
if (exists) {
const error = new Error("Collection already exists");
error.status = 400;
throw error;
}
if (req.collectionLimit !== undefined) {
if (project.collections.length >= req.collectionLimit) {
const error = new Error(`Collection limit reached (${req.collectionLimit}). Please upgrade your plan to create more collections.`);
error.status = 403;
throw error;
}
}
if (!project.jwtSecret) {
project.jwtSecret = generateApiKey("jwt_");
}
if (collectionName === "users") {
if (!validateUsersSchema(schema)) {
const error = new Error("The 'users' collection must have required 'email' and 'password' string fields.");
error.status = 422;
throw error;
}
}
const compiledCollectionName = project.resources.db.isExternal
? collectionName
: `${project._id}_${collectionName}`;
const newCollectionConfig = {
name: collectionName,
model: schema,
rls: getDefaultRlsForCollection(collectionName, schema),
};
project.collections.push(newCollectionConfig);
const saveOpts = session ? { session } : {};
await project.save(saveOpts);
const connection = await getConnection(projectId);
const collectionExistedBefore = await connection.db
.listCollections({ name: compiledCollectionName }, { nameOnly: true })
.hasNext();
const Model = getCompiledModel(
connection,
newCollectionConfig,
projectId,
project.resources.db.isExternal,
);
await createUniqueIndexes(Model, newCollectionConfig.model);
return { project, connection, compiledCollectionName, collectionExistedBefore, projectId, collectionName };
};
let session = null;
try {
session = await mongoose.startSession();
session.startTransaction();
const { project, projectId, collectionName } = await executeOperation(session);
await session.commitTransaction();
session.endSession();
await deleteProjectById(projectId);
await setProjectById(projectId, project.toObject());
await deleteProjectByApiKeyCache(project.publishableKey);
await deleteProjectByApiKeyCache(project.secretKey);
const projectObj = project.toObject();
delete projectObj.publishableKey;
delete projectObj.secretKey;
delete projectObj.jwtSecret;
emitEvent(req.user._id, 'collection_created', { collectionName, isUsersCollection: collectionName === 'users' }, projectId);
return res.status(201).json(projectObj);
} catch (err) {
if (session) {
try { await session.abortTransaction(); } catch (e) {}
session.endSession();
}
if (err.message && (err.message.includes("Transaction numbers are only allowed") || err.message.includes("buffering timed out"))) {
try {
const { project, projectId, collectionName } = await executeOperation(null);
await deleteProjectById(projectId);
await setProjectById(projectId, project.toObject());
await deleteProjectByApiKeyCache(project.publishableKey);
await deleteProjectByApiKeyCache(project.secretKey);
const projectObj = project.toObject();
delete projectObj.publishableKey;
delete projectObj.secretKey;
delete projectObj.jwtSecret;
emitEvent(req.user._id, 'collection_created', { collectionName, isUsersCollection: collectionName === 'users' }, projectId);
return res.status(201).json(projectObj);
} catch (retryErr) {
if (retryErr instanceof z.ZodError) return res.status(400).json({ error: retryErr.issues });
return res.status(retryErr.status || 400).json({ error: retryErr.message });
}
}
if (err instanceof z.ZodError) return res.status(400).json({ error: err.issues });
return res.status(err.status || 400).json({ error: err.message });
}
};
// GET DOC BY ID — FIXED: added limitFields(), populate(), cursor pagination, count support, structured response
module.exports.getData = async (req, res) => {
try {
const { projectId, collectionName } = req.params;
const project = await Project.findOne({ _id: projectId, ...getProjectAccessQuery(req.user._id) });
if (!project) return res.status(404).json({ success: false, data: {}, message: "Project not found." });
const collectionConfig = project.collections.find(c => c.name === collectionName);
if (!collectionConfig) {
return res.status(404).json({ success: false, data: {}, message: `Collection ${collectionName} not found.` });
}
const connection = await getConnection(projectId);
const model = getCompiledModel(
connection,
collectionConfig,
projectId,
project.resources.db.isExternal,
);
const baseQuery = model.find();
// Strip password from users collection
if (collectionName === 'users') {
baseQuery.select('-password');
}
// Handle ?count=true — return document count only
if (req.query.count === 'true') {
const countEngine = new QueryEngine(model.find(), req.query);
const count = await countEngine.filter().query.countDocuments();
return res.status(200).json({
success: true,
data: { count },
message: "Count fetched successfully.",
});
}
const features = new QueryEngine(baseQuery, req.query)
.filter()
.sort()
.limitFields() // fixes: ?fields= and ?meta=false now work
.populate(); // fixes: ?populate= and ?expand= now work
// Get total before paginating
const total = await features.count();
// Cursor-based pagination if ?cursor= is provided, otherwise offset-based
const useCursor = !!req.query.cursor;
if (useCursor) {
features.cursorPaginate();
} else {
features.paginate();
}
const data = await features.query.lean();
// Cursor: slice to limit and generate next cursor token
let items = data;
let nextCursor = null;
if (useCursor) {
const limit = Math.min(parseInt(req.query.limit, 10) || 100, 100);
features.generateNextCursor(data, limit);
items = data.slice(0, limit);
nextCursor = features.nextCursor;
}
const responseMeta = useCursor
? {
total,
cursor: req.query.cursor || null,
nextCursor,
limit: Math.max(1, Math.min(parseInt(req.query.limit, 10) || 100, 100)),
}
: {
total,
page: parseInt(req.query.page, 10) || 1,
limit: Math.max(1, Math.min(parseInt(req.query.limit, 10) || 100, 100)),
};
res.json({
success: true,
data: {
items,
...responseMeta,
},
message: "Data fetched successfully.",
});
} catch (err) {
if (err?.statusCode === 400 || err?.name === 'QueryFilterError') {
return res.status(400).json({ success: false, data: {}, message: err.message || "Invalid query filter." });
}
};
};
module.exports.deleteCollection = async (req, res) => {
try {
const { projectId, collectionName } = req.params;
const project = await Project.findOne({
_id: projectId,
...getProjectAccessQuery(req.user._id),
});
if (!project) {
return res
.status(404)
.json({ error: "Project not found or access denied." });
}
const collectionIndex = project.collections.findIndex(
(c) => c.name === collectionName,
);
if (collectionIndex === -1) {
return res.status(404).json({ error: "Collection not found." });
}
const isExternal = project.resources?.db?.isExternal;
const connection = await getConnection(projectId);
const finalCollectionName = isExternal
? collectionName
: `${project._id}_${collectionName}`;