This repository was archived by the owner on Jan 14, 2024. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathexpress.js
More file actions
833 lines (699 loc) 路 25.7 KB
/
Copy pathexpress.js
File metadata and controls
833 lines (699 loc) 路 25.7 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
require("dotenv").config();
const Sentry = require("@sentry/node");
const express = require("express");
const session = require("express-session");
const path = require('path');
const cron = require('node-cron');
const cors = require("cors");
const archiver = require('archiver');
const { generateConfig, getUserFiles, generateConfigWithActivation, activateDomain, LinkDiscord } = require("./functions.js");
const { generateLink, checkLinkExpiration } = require("./downloads.js");
const { getSocketJWT } = require("./auth.js");
const { sgMail } = require('@sendgrid/mail');
const app = express();
const { MongoClient } = require('mongodb');
const mongoose = require('mongoose');
const userSchema = require('./data'); // Import your Mongoose schema definition
const exportSchema = require('./exports'); //
const checkExports = require('./expiredExports'); //
const SMTPConfigSchema = new mongoose.Schema({
username: String,
HashedPassword: String,
},{ collection: "SMTP" });
// Create a mongoose model based on the schema
const SMTPConfig = mongoose.model('SMTP', SMTPConfigSchema);
// bcrypt
const bcrypt = require('bcrypt');
const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017/';
const dbName = process.env.DATABASE_NAME || 'your_database_name';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connect(uri + "hosting-config", { useNewUrlParser: true, useUnifiedTopology: true });
const User = mongoose.model("hostingdata");
Sentry.init({
dsn: "https://244a1ad4b427c80530cffbebc2c7b3a4@o4505716264599552.ingest.sentry.io/4505716341800960",
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({
tracing: true
}),
// enable Express.js middleware tracing
new Sentry.Integrations.Express({
app
}),
],
// Performance Monitoring
tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!,
});
// Trace incoming requests
app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());
app.set("view engine", "ejs");
const port = 3000;
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
cors: {
origin: "*",
},
});
app.use(
session({
secret: process.env.SESSION_SECRET || "secret",
resave: false,
saveUninitialized: true,
cookie: { secure: false },
})
);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use((req, res, next) => {
if (req.url.includes("config.json"))
return res.status(404).send("nice try ;)");
// If 'config.json' is not in the requested URL, move to the next middleware
next();
});
app.use(cors())
const fs = require("fs");
const { getJWT } = require("./jwt");
const req = require("express/lib/request.js");
//api routes
app.get("/api/getall", async (req, res) => {
try {
// get a list of all domains from the db
const domains = await User.find({}).exec();
// filter only the domain no other data
const domainList = domains.map((domain) => domain.domain);
// return the list
return res.json({ domains: domainList });
} catch (error) {
console.error(error);
return res.status(500).json({ error: "Internal server error" });
}
});
app.post("/api/upload", async (req, res) => {
try {
let domain = req.query.domain;
let jwt = req.query.jwt;
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username != user.user.login)
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
//check if directory content/host exists
if (!fs.existsSync(`content/${domain}`))
return res.status(404).json({ error: "Domain dosnt' exist" });
//check if file is in request
if (!req.files) return res.status(400).json({ error: "No file uploaded" });
// save file to disk
} catch (err) {
console.log(err);
return res.status(500).json({ error: err });
}
});
app.get('/api/protected/:domain/:linkId', checkLinkExpiration, (req, res) => {
// Serve a file (you might need to adjust the file path)
res.render('archive', { domain: req.params.domain + ".is-a.dev", download: req.params.linkId });
});
app.get('/api/download', async (req, res) => {
// get user input
let domain = req.query.domain;
domain = domain.split(".is-a.dev")[0];
const jwt = req.query.jwt;
// check if user is authenticated
const user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
// check if user is owner of the domain
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username != user.user.login)
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
if (!fs.existsSync(`content/${domain}`))
return res.status(404).json({ error: "Domain dosnt' exist" });
const folderToZip = path.join(__dirname, `/content/${domain}/`);
const zipFileName = `${domain}.zip`;
// Create a writable stream for the zip file
const output = fs.createWriteStream(zipFileName);
// Create an archiver instance
const archive = archiver('zip', {
zlib: { level: 9 } // Set compression level
});
// Pipe the output stream to the archive
archive.pipe(output);
// Append the entire folder to the archive
archive.directory(folderToZip, false);
// Finalize the archive
archive.finalize();
// Set response headers to indicate a downloadable file
res.attachment(zipFileName);
// Pipe the zip file to the response
output.on('close', () => {
res.status(200).sendFile(zipFileName, { root: __dirname });
});
});
app.get("/api/discord", async (req, res) => {
let domain = req.query.domain;
domain = domain.split(".is-a.dev")[0];
let jwt = req.query.jwt;
let contents = req.query.dh;
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
if (!domain) return res.status(400).send("No domain provided");
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
LinkDiscord(domain, contents)
return res.json({ success: true });
});
app.get("/api/SMTP", async (req, res) => {
let domain = req.query.domain;
let jwt = req.query.jwt;
let password = req.query.password;
domain = domain.split(".is-a.dev")[0];
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
if (!domain) return res.status(400).send("No domain provided");
if (!password) return res.status(400).send("No password provided");
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
// Hash the new password
const hashedPassword = await bcrypt.hash(password, 10);
let smtp = await SMTPConfig.findOne({ username: domain })
if (!smtp) {
await SMTPConfig.create({ username: domain, HashedPassword: hashedPassword });
} else {
await SMTPConfig.findOneAndUpdate({ username: domain }, { HashedPassword: hashedPassword });
}
return res.json({ success: true });
});
app.get("/api/panel", async (req, res) => {
let jwt = req.query.jwt;
let domain = req.query.domain;
let user = getJWT(jwt);
let profilepic = `https://avatars.githubusercontent.com/${user.user.login}`
if (!user) return res.status(403).send("Invalid JWT");
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
const domainData = await User.findOne({ domain }).exec();
let EMAIL = '';
if (domainData.EMAIL == undefined) {
EMAIL = "";
} else {
// if domainData.EMAIL is true then set EMAIL to checked
if (domainData.EMAIL == true) {
EMAIL = "checked";
}
else {
EMAIL = "";
}
}
domain = domain + ".is-a.dev"
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
return res.render("panel", { username: user.user.login, profilepic: profilepic, domain: domain, SMTP: EMAIL, jwt: jwt });
});
app.get("/api/domain", async (req, res) => {
try {
let domain = req.query.domain;
let jwt = req.query.jwt;
let user = getJWT(jwt);
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (!fs.existsSync(`content/${domain}`))
return res.status(404).json({ error: "Domain does not exist" });
return res.json({ success: true });
} catch (err) {
console.log(err);
return res.status(500).json({ error: err });
}
});
app.get("/api/user/activate", async (req, res) => {
let domain = req.headers.host;
let jwt = req.query.jwt;
domain = domain.split(":")[0];
domain = domain.split(".is-a.dev")[0];
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
if (!domain) return res.status(400).send("No domain provided");
// check if user owns domain
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: "We could not verify you own this subdomain. If your pr was merged less then an hour ago then try again in 30 minutes." });
activateDomain(domain, async (err, result) => {
if (err) {
console.error('Error:', err);
return;
}
if (result) {
return res.redirect(`https://${domain}.is-a.dev/`);
} else {
return res.status(500).json({ error: "Contact William for assistance" });
}
});
});
app.get("/api/data/exports", async (req, res) => {
let uuid = req.query.uuid;
if (!uuid) return res.status(400).send("No uuid provided");
// check if uuid exists in database
let data = await exportSchema.findOne({ _id: uuid });
if (!data) return res.status(404).send("UUID not found");
// check if uuid is expired
if (data.expiryDate < Date.now()) return res.status(410).send("Export has expired");
// check if file exists
if (!fs.existsSync(`exports/${data.fileName}`)) return res.status(404).send("File not found");
// serve file
return res.sendFile(__dirname + `/exports/${data.fileName}`);
}
);
app.get("/api/staff/delete", async (req, res) => {
let token = req.query.token;
if (!token) return res.status(400).send("No token provided");
if (token !== process.env.STAFF_TOKEN) return res.status(403).send("Invalid token");
let domain = req.query.domain;
const folderToZip = path.join(__dirname, `/content/${domain}/`);
const zipFileName = path.join(__dirname, `/exports/${domain}.zip`);
// Create a writable stream for the zip file
const output = fs.createWriteStream(zipFileName);
// Create an archiver instance
const archive = archiver('zip', {
zlib: { level: 9 } // Set compression level
});
// Pipe the output stream to the archive
archive.pipe(output);
// Append the entire folder to the archive
archive.directory(folderToZip, false);
// Finalize the archive
archive.finalize();
// create a uuid
const uuid = require('uuid').v4();
let expiryDate = Date.now() + 1000 * 60 * 60 * 24 * 7;
// add uuid to database
const newExport = new exportSchema({
_id: uuid,
domain: domain,
expiryDate: expiryDate,
fileName: `${domain}.zip`,
avaliable: true,
});
await newExport.save();
// delete domain
await User.findOneAndDelete({ domain });
// delete directory
fs.rmSync(`content/${domain}`, { recursive: true });
return res.json({ success: true, export: `https://hosts.is-a.dev/api/data/exports?uuid=${uuid}`, expiryDate: expiryDate });
}
);
app.get("/api/domain/delete", async (req, res) => {
let domain = req.query.domain;
let jwt = req.query.jwt;
if (!jwt) return res.status(400).send("No JWT provided");
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
if (!domain) return res.status(400).send("No domain provided");
// check if user owns domain
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: "We could not verify you own this subdomain. If your pr was merged less then an hour ago then try again in 30 minutes." });
//export
const folderToZip = path.join(__dirname, `/content/${domain}/`);
const zipFileName = path.join(__dirname, `/exports/${domain}.zip`);
// Create a writable stream for the zip file
const output = fs.createWriteStream(zipFileName);
// Create an archiver instance
const archive = archiver('zip', {
zlib: { level: 9 } // Set compression level
});
// Pipe the output stream to the archive
archive.pipe(output);
// Append the entire folder to the archive
archive.directory(folderToZip, false);
// Finalize the archive
archive.finalize();
// create a uuid
const uuid = require('uuid').v4();
// add uuid to database
const newExport = new exportSchema({
_id: uuid,
domain: domain,
expiryDate: Date.now() + 1000 * 60 * 60 * 24 * 7,
fileName: `${domain}.zip`,
avaliable: true,
});
await newExport.save();
// delete domain
await User.findOneAndDelete({ domain });
// delete directory
fs.rmSync(`content/${domain}`, { recursive: true });
return res.json({ success: true, export: `https://hosts.is-a.dev/api/data/exports?uuid=${uuid}` });
}
);
app.get("/api/activate", async (req, res) => {
let domain = req.query.domain;
let NOTIFY = req.query.NOTIFY_TOKEN;
// if notify token dosnt match process.env.NOTIFY_TOKEN return 403
if (NOTIFY !== process.env.NOTIFY_TOKEN) return res.status(403).send("Invalid token");
//let activation_code = req.query.activation_code;
activateDomain(domain, async (err, result) => {
if (err) {
console.error('Error:', err);
return;
}
if (result) {
return res.json({ success: true });
} else {
return res.status(500).json({ error: "Invalid activation code" });
}
});
});
app.get("/api/preregister", async (req, res) => {
try {
let domain = req.query.domain;
let jwt = req.query.jwt;
let pr = req.query.pr;
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
let email = user.emails.find((email) => email.primary)
if (data.error) return res.status(500).send(data.error);
if (data.info) {
//check if directory content/host exists
if (fs.existsSync(`content/${domain}`))
return res.status(400).json({ error: "Domain already exists" });
//duplicate skeleton
fs.mkdirSync(`content/${domain}`);
let files = fs.readdirSync("skeleton");
for (let file of files) {
fs.copyFileSync(`skeleton/${file}`, `content/${domain}/${file}`);
}
let response = generateConfigWithActivation(domain, email.email);
let activation_code = "notUsed";
console.log(activation_code + " " + email.email + " " + domain);
await fetch(`https://notify-api.is-a.dev/api/preregister?domain=${domain}&pr=${pr}&activation_code=${activation_code}&token=${process.env.NOTIFY_TOKEN}`)
return res.json({ success: true });
}
if (data.owner?.username != user.user.login)
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
} catch (err) {
console.log(err);
return res.status(500).json({ error: err });
}
});
app.get('/api/domain/set-password', async (req, res) => {
try {
let domain = req.query.domain;
domain = domain.split(".is-a.dev")[0];
let jwt = req.query.jwt;
let user = getJWT(jwt);
if (!user) return res.status(403).send('Invalid JWT');
// Fetch data from API to authenticate the user
let data = await fetch(process.env.API_URL + '/domains/' + domain + '/get');
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: 'You are not the owner of this domain' });
let password = req.query.password;
// Hash the new password
const hashedPassword = await bcrypt.hash(password, 10);
// Update the user's password in the database
const User = mongoose.model('hostingdata'); // Replace with your Mongoose model name
const updatedUser = await User.findOneAndUpdate(
{ domain },
{ HashedPassword: hashedPassword },
{ new: true } // Return the updated user document
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
return res.status(200).json({ message: 'Password updated successfully' });
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'Internal server error' });
}
});
app.get("/api/register", async (req, res) => {
try {
let domain = req.query.domain;
let jwt = req.query.jwt;
let user = getJWT(jwt);
if (!user) return res.status(403).send("Invalid JWT");
let data = await fetch(process.env.API_URL + "/domains/" + domain + "/get");
data = await data.json();
if (data.error) return res.status(500).send(data.error);
if (data.owner?.username.toLowerCase() != user.user.login.toLowerCase())
return res
.status(403)
.json({ error: "You are not the owner of this domain" });
//check if directory content/host exists
if (fs.existsSync(`content/${domain}`))
return res.status(400).json({ error: "Domain already exists" });
//duplicate skeleton
fs.mkdirSync(`content/${domain}`);
let files = fs.readdirSync("skeleton");
for (let file of files) {
fs.copyFileSync(`skeleton/${file}`, `content/${domain}/${file}`);
}
let response = generateConfig(domain);
return res.json({ success: true, pass: 'NOT ready' });
} catch (err) {
console.log(err);
return res.status(500).json({ error: err });
}
});
app.get(".isadev", async (req, res) => {
try {
//Check if the domain exists
if (!fs.existsSync(`content/${domain}`))
return res.status(404).json({
error: "Domain not found",
});
//Load config
let config = fs.readFileSync(__dirname + `/content/${domain}/config.json`);
config = JSON.parse(config);
res.json({
isadev: true,
});
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Internal server error" });
}
});
app.get("/debug-sentry", function mainHandler(req, res) {
throw new Error("My first Sentry error!");
});
app.get("*", async (req, res) => {
try {
// Domain variable
let domain = req.headers.host;
domain = domain.split(":")[0];
domain = domain.split(".is-a.dev")[0];
// Connect to MongoDB and find user data
const User = mongoose.model("hostingdata"); // Replace with your Mongoose model name
const user = await User.findOne({ domain }).exec();
if (!user) {
return res.status(404).sendFile(__dirname + "/404.html");
}
let file = req.url;
// Remove query string
if (file.includes("?")) file = file.split("?")[0];
// Password protection
if (user.HashPagePassword && !bcrypt.compareSync(req.query.password, user.HashPagePassword)) {
return res.sendFile(__dirname + "/login.html");
}
if (user.ACTIVATED !== true) {
return res.sendFile(__dirname + "/activation.html");
}
// Get file
if (file.includes("..")) {
return res.status(403).sendFile(__dirname + "/403.html");
}
if (file.startsWith("/")) {
file = file.substring(1);
}
// Check if file exists
let path = `content/${domain}/${file}`;
// If path is a directory, add index.html
if (fs.lstatSync(path).isDirectory()) {
path += "/index.html";
}
if (!fs.existsSync(path)) {
// If custom 404 exists, send it, else send default
if (fs.existsSync(`content/${domain}/404.html`)) {
return res.status(404).sendFile(`content/${domain}/404.html`);
}
return res.status(404).sendFile(__dirname + "/404.html");
}
// Serve file
return res.sendFile(__dirname + "/" + path);
} catch (err) {
console.log(err);
return res.status(500).sendFile(__dirname + "/500.html");
}
});
app.post("*", (req, res) => {
try {
let domain = req.headers.host;
domain = domain.split(":")[0];
domain = domain.split(".is-a.dev")[0];
//check if directory content/host exists
if (!fs.existsSync(`content/${domain}`))
return res.status(404).sendFile(__dirname + "/404.html");
let config = fs.readFileSync(__dirname + `/content/${domain}/config.json`);
config = JSON.parse(config);
if (config.password !== undefined && req.body.password != config.password)
return res.sendFile(__dirname + "/login.html");
if (typeof req.session.authenticated == "undefined")
req.session.authenticated = [];
req.session.authenticated.push(domain);
//redirect to same url with get
return res.redirect(req.url);
} catch (err) {
console.log(err);
return res.status(500).sendFile(__dirname + "/500.html");
}
});
// The error handler must be registered before any other error middleware and after all controllers
app.use(Sentry.Handlers.errorHandler());
//WS
io.on("connection", async (socket) => {
socket.on("authenticate", async (data) => {
try {
let user = getSocketJWT(data);
if (!user) return socket.emit("authenticated", false);
socket.emit("authenticated", true);
socket.user = user.user;
console.log(process.env.API_URL + "/domains/list/" + user.user.login);
socket.domains = await fetch(
process.env.API_URL + "/domains/list/" + user.user.login
);
socket.domains = await socket.domains.json();
socket.domains = socket.domains.domains;
socket.emit("domains", socket.domains);
} catch (err) {
console.log(err);
socket.emit("authenticated", false);
}
});
socket.on("getFiles", () => {
if (!socket.domain) return socket.emit("getFiles", []);
return socket.emit("files", getUserFiles(socket.domain));
});
socket.on("selectDomain", (domain) => {
domain = domain.toLowerCase();
domain = domain.split(".is-a.dev")[0];
try {
console.log(socket.domains);
let exists = false;
socket.domains.forEach((element) => {
if (element.domain == `${domain}.is-a.dev`) exists = true;
});
if (!exists) return socket.emit("refresh");
if (socket.domain) socket.leave(socket.domain);
socket.join(domain);
socket.domain = domain;
let files = getUserFiles(domain);
if (files.length == 0) return socket.emit("selectDomain", false);
socket.emit("files", files);
} catch (err) {
socket.emit("selectDomain", false);
}
});
socket.on("getFile", (file) => {
try {
if (!socket.domain) return socket.emit("refresh");
let files = getUserFiles(socket.domain);
let exists = false;
files.forEach((element) => {
if (element.file == file) exists = true;
});
if (!exists) return socket.emit("file", {});
let send = {
domain: socket.domain,
};
//if directory, send files as items, and set type to directory
if (fs.lstatSync(`content/${socket.domain}/${file}`).isDirectory()) {
send.type = "directory";
send.items = [];
fs.readdirSync(`content/${socket.domain}/${file}`).forEach((item) => {
send.items.push({
name: item,
type: fs
.lstatSync(`content/${socket.domain}/${file}/${item}`)
.isDirectory()
? "directory"
: "file",
});
});
} else {
send.type = "file";
send.content = fs.readFileSync(`content/${socket.domain}/${file}`).toString();
}
socket.emit("file", send);
} catch (err) {
console.log(err);
socket.emit("file", "");
}
});
socket.on("saveFile", (data) => {
try {
if (!socket.domain) return socket.emit("refresh");
let files = getUserFiles(socket.domain);
let exists = false;
files.forEach((element) => {
if (element.file == data.file) exists = true;
});
if (!exists) return socket.emit("refresh");
fs.writeFileSync(`content/${socket.domain}/${data.file}`, data.content);
socket.emit("saveFile", true);
} catch (err) {
console.log(err);
socket.emit("saveFile", false);
}
});
});
server.listen(3000, () => {
cron.schedule('0 * * * *', async () => {
try {
checkExports();
}
catch (error) {
console.error('Error removing expired links:', error);
}
}, {
scheduled: true,
timezone: "Europe/London"
});
console.log("listening on *:3000");
});