forked from breck7/ScrollHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScrollHub.js
1604 lines (1348 loc) · 56.2 KB
/
ScrollHub.js
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
// STDLib
const { exec, execSync, spawn } = require("child_process")
const fs = require("fs")
const v8 = require("v8")
const fsp = require("fs").promises
const os = require("os")
const path = require("path")
const util = require("util")
const execAsync = util.promisify(exec)
// Web server
const express = require("express")
const compression = require("compression")
const https = require("https")
const http = require("http")
const fileUpload = require("express-fileupload")
const AnsiToHtml = require("ansi-to-html")
// Git server
const httpBackend = require("git-http-backend")
// PPS
const { Particle } = require("scrollsdk/products/Particle.js")
const { ScrollFile, ScrollFileSystem } = require("scroll-cli/scroll.js")
const { CloneCli } = require("scroll-cli/clone.js")
const packageJson = require("./package.json")
const scrollFs = new ScrollFileSystem()
// This
const { Dashboard } = require("./dashboard.js")
const exists = async filePath => {
const fileExists = await fsp
.access(filePath)
.then(() => true)
.catch(() => false)
return fileExists
}
const getBaseUrlForFolder = (folderName, hostname, protocol) => {
const isLocalHost = hostname.includes("local")
// if localhost, no custom domains
if (isLocalHost) return "http://localhost/" + folderName
if (!folderName.includes(".")) return protocol + "//" + hostname + "/" + folderName
// now it might be a custom domain, serve it as if it is
// of course, sometimes it would not be
return protocol + "//" + folderName
}
const requestsFile = folderName => `title Traffic Data
metaTags
homeButton
buildHtml
theme gazette
printTitle
container
Real time view
/globe.html?folderName=${folderName}
button Refresh
link /summarizeRequests.htm?folderName=${folderName}
post
// Anything
requests.csv
<br><br><span style="width: 200px; display:inline-block; color: blue;">Readers</span><span style="color:green;">Writers</span><br><br>
sparkline
y Readers
color blue
width 200
height 200
sparkline
y Writers
color green
width 200
height 200
printTable
tableSearch
scrollVersionLink
`
express.static.mime.define({ "text/plain": ["scroll", "parsers"] })
express.static.mime.define({ "text/plain": ["ssv", "psv", "tsv", "csv"] })
const parseUserAgent = userAgent => {
if (!userAgent) return "Unknown"
// Extract browser and OS
const browser = userAgent.match(/(Chrome|Safari|Firefox|Edge|Opera|MSIE|Trident)[\/\s](\d+)/i)
const os = userAgent.match(/(Mac OS X|Windows NT|Linux|Android|iOS)[\/\s]?(\d+[\._\d]*)?/i)
let result = []
if (browser) result.push(browser[1] + (browser[2] ? "." + browser[2] : ""))
if (os) result.push(os[1].replace(/ /g, "") + (os[2] ? "." + os[2].replace(/_/g, ".") : ""))
return result.join(" ") || "Other"
}
const isUrl = str => str.startsWith("http://") || str.startsWith("https://")
// todo: clean this up. add all test cases
const sanitizeFolderName = name => {
name = name.replace(/\.git$/, "")
// if given a url, return the last part
// given http://hub.com/foo returns foo
// given http://hub.com/foo.git returns foo
if (isUrl(name)) {
try {
const url = new URL(name)
const { hostname, pathname } = url
// given http://hub.com/ return hub.com
name = pathname.split("/").pop()
if (!name) return hostname
return name.toLowerCase().replace(/[^a-z0-9._]/g, "")
} catch (err) {
console.error(err)
}
}
name = name.split("/").pop()
return name.toLowerCase().replace(/[^a-z0-9._]/g, "")
}
const sanitizeFileName = name => name.replace(/[^a-zA-Z0-9._]/g, "")
class ScrollHub {
constructor() {
this.app = express()
const app = this.app
this.port = 80
this.maxUploadSize = 100 * 1000 * 1024
this.hostname = os.hostname()
this.rootFolder = path.join(os.homedir(), "folders")
this.templatesFolder = path.join(__dirname, "templates")
this.trashFolder = path.join(__dirname, "trash")
this.certsFolder = path.join(__dirname, "certs")
this.folderCache = {}
this.sseClients = new Set()
this.globalLogFile = path.join(__dirname, "log.txt")
this.storyLogFile = path.join(__dirname, "writes.txt")
this.dashboard = new Dashboard(this.globalLogFile)
}
startAll() {
this.startTime = Date.now()
this.ensureInstalled()
this.ensureTemplatesInstalled()
this.warmFolderCache()
this.initVandalProtection()
this.enableCompression()
this.enableCors()
this.enableFormParsing()
this.enableFileUploads()
this.initAnalytics()
this.addStory({ ip: "admin" }, `started ScrollHub v${packageJson.version}`)
console.log(`ScrollHub version: ${packageJson.version}`)
console.log(`Max memory: ${v8.getHeapStatistics().heap_size_limit / 1024 / 1024} MB`)
this.initFileRoutes()
this.initGitRoutes()
this.initHistoryRoutes()
this.initZipRoutes()
this.initCommandRoutes()
this.initSSERoute()
this.enableStaticFileServing()
this.servers = [this.startHttpsServer(), this.startHttpServer()]
this.init404Routes()
return this
}
initSSERoute() {
const { app, globalLogFile } = this
app.get("/requests.htm", (req, res) => {
const folderName = req.query?.folderName
req.headers["accept-encoding"] = "identity"
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive"
})
// Send initial ping
res.write(": ping\n\n")
const id = Date.now()
const client = {
id,
res,
folderName
}
this.sseClients.add(client)
req.on("close", () => this.sseClients.delete(client))
})
}
async broadCastMessage(folderName, log, ip) {
if (!this.sseClients.size) return
const geo = await this.dashboard.ipToGeo(ip === "::1" ? "98.150.188.43" : ip)
const name = (geo.regionName + "/" + geo.country).replace(/ /g, "")
log = [log.trim(), name, geo.lat, geo.lon].join(" ")
this.sseClients.forEach(client => {
if (!client.folderName || client.folderName === folderName) client.res.write(`data: ${JSON.stringify({ log })}\n\n`)
})
}
enableCompression() {
this.app.use(compression())
}
enableCors() {
this.app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*")
next()
})
}
enableFormParsing() {
this.app.use(express.urlencoded({ extended: true }))
}
enableFileUploads() {
this.app.use(fileUpload({ limits: { fileSize: this.maxUploadSize } }))
}
enableStaticFileServing() {
const { app, folderCache, rootFolder } = this
// New middleware to route domains to the matching folder
app.use((req, res, next) => {
const hostname = req.hostname?.toLowerCase()
if (!hostname || !folderCache[hostname]) return next()
const folderPath = path.join(rootFolder, hostname)
express.static(folderPath)(req, res, next)
})
// Serve the folders directory from the root URL
app.use("/", express.static(rootFolder))
// Serve the root directory statically
app.use(express.static(__dirname))
}
init404Routes() {
const { app, rootFolder } = this
//The 404 Route (ALWAYS Keep this as the last route)
app.get("*", async (req, res) => {
const folderName = this.getFolderName(req)
const folderPath = path.join(rootFolder, folderName)
const notFoundPage = path.join(folderPath, "404.html")
await fsp
.access(notFoundPage)
.then(() => {
res.status(404).sendFile(notFoundPage)
})
.catch(() => {
res.status(404).sendFile(path.join(__dirname, "404.html"))
})
})
}
isSummarizing = {}
async buildRequestsSummary(folder = "") {
const { rootFolder, folderCache } = this
if (this.isSummarizing[folder]) return
this.isSummarizing[folder] = true
if (folder && !folderCache[folder]) return
const logFile = folder ? this.getFolderLogFile(folder) : this.globalLogFile
const outputPath = folder ? path.join(rootFolder, folder) : path.join(__dirname)
const dashboard = new Dashboard(logFile)
await dashboard.processLogFile()
const content = folder ? dashboard.csv : dashboard.csvTotal
await fsp.writeFile(path.join(outputPath, "requests.csv"), content, "utf8")
if (folder) {
const reqFile = path.join(outputPath, "requests.scroll")
await fsp.writeFile(reqFile, requestsFile(folder), "utf8")
await new ScrollFile(undefined, reqFile, new ScrollFileSystem()).buildAll()
} else await this.buildScrollHubPages()
this.isSummarizing[folder] = false
}
initAnalytics() {
const checkWritePermissions = this.checkWritePermissions.bind(this)
if (!fs.existsSync(this.storyLogFile)) fs.writeFileSync(this.storyLogFile, "", "utf8")
const { app, folderCache } = this
app.use(this.logRequest.bind(this))
app.use("/summarizeRequests.htm", checkWritePermissions, async (req, res) => {
const folderName = this.getFolderName(req)
if (folderName) {
await this.buildRequestsSummary(folderName)
if (req.body.particle) return res.send("Done.")
return res.redirect(folderName + "/requests.html")
}
await this.buildRequestsSummary()
res.send(`Done.`)
})
app.get("/hostname.htm", (req, res) => res.send(req.hostname))
}
async logRequest(req, res, next) {
const { rootFolder, folderCache, globalLogFile } = this
const { hostname, method, url, protocol } = req
const ip = req.ip || req.connection.remoteAddress
const userAgent = parseUserAgent(req.get("User-Agent") || "Unknown")
const folderName = this.getFolderName(req)
// todo: log after request? save status response, etc? flag bots?
const logEntry = `${method === "GET" ? "read" : "write"} ${folderName || hostname} ${protocol}://${hostname}${url} ${Date.now()} ${ip} ${userAgent}\n`
fs.appendFile(globalLogFile, logEntry, err => {
if (err) console.error("Failed to log request:", err)
})
this.broadCastMessage(folderName, logEntry, ip)
if (folderName && folderCache[folderName]) {
const folderLogFile = this.getFolderLogFile(folderName)
try {
await fsp.appendFile(folderLogFile, logEntry)
} catch (err) {
console.error(`Failed to log request to folder log (${folderLogFile}):`, err)
}
}
next()
}
getFolderLogFile(folderName) {
const { rootFolder } = this
const folderPath = path.join(rootFolder, folderName)
return path.join(folderPath, "log.txt")
}
initGitRoutes() {
const { app, rootFolder } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
app.get("/:repo.git/*", (req, res) => {
const repo = req.params.repo
const repoPath = path.join(rootFolder, repo)
req.url = "/" + req.url.split("/").slice(2).join("/")
const handlers = httpBackend(req.url, (err, service) => {
if (err) return res.end(err + "\n")
res.setHeader("content-type", service.type)
const ps = spawn(service.cmd, service.args.concat(repoPath))
ps.stdout.pipe(service.createStream()).pipe(ps.stdin)
})
req.pipe(handlers).pipe(res)
})
app.post("/:repo.git/*", checkWritePermissions, async (req, res) => {
const repo = req.params.repo
const repoPath = path.join(rootFolder, repo)
req.url = "/" + req.url.split("/").slice(2).join("/")
const handlers = httpBackend(req.url, (err, service) => {
if (err) return res.end(err + "\n")
res.setHeader("content-type", service.type)
const ps = spawn(service.cmd, service.args.concat(repoPath))
ps.stdout.pipe(service.createStream()).pipe(ps.stdin)
// Handle Git pushes asynchronously and build the scroll
ps.on("close", async code => {
if (code === 0 && service.action === "push") {
const folderName = repoPath.split("/").pop()
await this.buildFolder(folderName)
this.addStory(req, `pushed ${repo}`)
this.updateFolderAndBuildList(repo)
}
})
})
req.pipe(handlers).pipe(res)
})
}
initHistoryRoutes() {
const { app, rootFolder, folderCache } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
app.get("/history.htm/:folderName", async (req, res) => {
const folderName = sanitizeFolderName(req.params.folderName)
const folderPath = path.join(rootFolder, folderName)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
try {
// Get the git log asynchronously and format it as CSV
const { stdout: gitLog } = await execAsync(`git log --pretty=format:"%h,%an,%ad,%at,%s" --date=short`, { cwd: folderPath })
res.setHeader("Content-Type", "text/plain; charset=utf-8")
const header = "commit,author,date,timestamp,message\n"
res.send(header + gitLog)
} catch (error) {
console.error(error)
res.status(500).send("An error occurred while fetching the git log")
}
})
app.get("/diff.htm/:folderName", async (req, res) => {
const folderName = sanitizeFolderName(req.params.folderName)
const folderPath = path.join(rootFolder, folderName)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
const count = req.query.count || 10
try {
// Check if there are any commits
const gitRevListProcess = spawn("git", ["rev-list", "--count", "HEAD"], { cwd: folderPath })
let commitCountData = ""
gitRevListProcess.stdout.on("data", data => {
commitCountData += data.toString()
})
gitRevListProcess.stderr.on("data", data => {
console.error(`git rev-list stderr: ${data}`)
})
gitRevListProcess.on("close", code => {
if (code !== 0) {
res.status(500).send("An error occurred while checking commit count")
return
}
const numCommits = parseInt(commitCountData.trim(), 10)
if (numCommits === 0) {
res.status(200).send("No commits available.")
return
}
// Now spawn git log process
const gitLogProcess = spawn("git", ["log", "-p", `-${count}`, "--color=always"], { cwd: folderPath })
const convert = new AnsiToHtml({ escapeXML: true })
res.setHeader("Content-Type", "text/html; charset=utf-8")
res.write(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Last 10 Commits for ${folderName}</title>
<style>
body { font-family: monospace; white-space: pre-wrap; word-wrap: break-word; padding: 5px; }
h2 { color: #333; }
.commit { border-bottom: 1px solid #ccc; padding-bottom: 20px; margin-bottom: 20px; }
.commit-message { font-weight: bold; color: #005cc5; }
input[type="submit"] { font-size: 0.8em; padding: 2px 5px; margin-left: 10px; }
</style>
</head>
<body>
`)
let buffer = ""
gitLogProcess.stdout.on("data", data => {
buffer += data.toString()
// Process complete lines
let lines = buffer.split("\n")
buffer = lines.pop() // Keep incomplete line in buffer
lines = lines.map(line => {
// Convert ANSI to HTML
line = convert.toHtml(line)
// Replace commit hashes with forms
line = line.replace(/(commit\s)([0-9a-f]{40})/, (match, prefix, hash) => {
return `${"-".repeat(60)}<br>
${prefix}${hash}<br>
<form method="POST" action="/revert.htm/${folderName}" style="display:inline;">
<input type="hidden" name="hash" value="${hash}">
<input type="submit" value="Restore this version" onclick="return confirm('Restore this version?');">
</form>`
})
return line
})
res.write(lines.join("\n") + "\n")
})
gitLogProcess.stderr.on("data", data => {
console.error(`git log stderr: ${data}`)
})
gitLogProcess.on("close", code => {
if (code !== 0) {
console.error(`git log process exited with code ${code}`)
res.status(500).end("An error occurred while fetching the git log")
} else {
// Process any remaining buffered data
if (buffer.length > 0) {
buffer = convert.toHtml(buffer)
buffer = buffer.replace(/(commit\s)([0-9a-f]{40})/, (match, prefix, hash) => {
return `${"-".repeat(60)}<br>
${prefix}${hash}<br>
<form method="POST" action="/revert.htm/${folderName}" style="display:inline;">
<input type="hidden" name="hash" value="${hash}">
<input type="submit" value="Restore this version" onclick="return confirm('Restore this version?');">
</form>`
})
res.write(buffer)
}
res.end("</body></html>")
}
})
})
} catch (error) {
console.error(error)
res.status(500).send("An error occurred while fetching the git log")
}
})
app.post("/revert.htm/:folderName", checkWritePermissions, async (req, res) => {
const folderName = sanitizeFolderName(req.params.folderName)
const targetHash = req.body.hash
const folderPath = path.join(rootFolder, folderName)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
if (!targetHash || !/^[0-9a-f]{40}$/i.test(targetHash)) return res.status(400).send("Invalid target hash provided")
try {
// Perform the revert
const clientIp = req.ip || req.connection.remoteAddress
const hostname = req.hostname?.toLowerCase()
await execAsync(`git checkout ${targetHash} . && git add . && git commit --author="${clientIp} <${clientIp}@${hostname}>" -m "Reverted to ${targetHash}" --allow-empty`, { cwd: folderPath })
this.addStory(req, `reverted ${folderName}`)
await this.buildFolder(folderName)
res.redirect("/diff.htm/" + folderName)
this.updateFolderAndBuildList(folderName)
} catch (error) {
console.error(error)
res.status(500).send(`An error occurred while reverting the repository:\n ${error.toString().replace(/</g, "<")}`)
}
})
}
getCloneName(folderName) {
const { folderCache } = this
const isSubdomain = folderName.includes(".")
// If its a domain name, add a subdomain
let newName = folderName
while (folderCache[newName]) {
// todo: would need to adjust if popular
const rand = Math.random().toString(16).slice(2, 7)
newName = isSubdomain ? `clone${rand}.` + folderName : folderName + rand
}
return newName
}
initFileRoutes() {
const { app, rootFolder, folderCache } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
app.get("/e/:folderName", async (req, res) => {
res.redirect("/edit.html?folderName=" + req.params.folderName)
})
app.post("/create.htm", checkWritePermissions, async (req, res) => {
try {
const result = await this.createFolder(req.body.folderName)
if (result.errorMessage) return this.handleCreateError(res, result)
const { folderName } = result
this.addStory(req, `created ${folderName}`)
res.redirect(`/edit.html?folderName=${folderName}`)
} catch (error) {
console.error(error)
res.status(500).send("Sorry, an error occurred while creating the folder:", error)
}
})
app.post("/clone.htm", checkWritePermissions, async (req, res) => {
try {
const sourceFolderName = req.body.folderName || (req.body.particle ? new Particle(req.body.particle).get("folderName") : "")
if (!sourceFolderName) return res.status(500).send("No folder name provided")
const cloneName = this.getCloneName(sourceFolderName)
const result = await this.createFolder(sourceFolderName + " " + cloneName)
if (result.errorMessage) return this.handleCreateError(res, result)
const { folderName } = result
this.addStory(req, `cloned ${sourceFolderName} to ${cloneName}`)
if (req.body.redirect === "false") return res.send(cloneName)
res.redirect(`/edit.html?folderName=${cloneName}`)
} catch (error) {
console.error(error)
res.status(500).send("Sorry, an error occurred while cloning the folder:", error)
}
})
app.get("/ls.json", async (req, res) => {
const folderName = sanitizeFolderName(req.query.folderName)
const folderPath = path.join(rootFolder, folderName)
const cachedEntry = folderCache[folderName]
if (!cachedEntry) return res.status(404).send(`Folder '${folderName}' not found`)
const fileNames = (await fsp.readdir(folderPath, { withFileTypes: true })).filter(dirent => dirent.isFile() && dirent.name !== ".git" && dirent.name !== ".DS_Store").map(dirent => dirent.name)
const files = {}
fileNames.forEach(file => {
files[file] = {
versioned: cachedEntry.tracked.has(file)
}
})
res.setHeader("Content-Type", "text/json")
res.send(JSON.stringify(files))
})
app.get("/read.htm", async (req, res) => {
const filePath = path.join(rootFolder, decodeURIComponent(req.query.filePath))
try {
const fileExists = await exists(filePath)
if (!fileExists) return res.status(404).send(`File '${filePath}' not found`)
const content = await fsp.readFile(filePath, "utf8")
res.setHeader("Content-Type", "text/plain")
res.send(content)
} catch (error) {
console.error(error)
res.status(500).send(`An error occurred while reading '${filepath}'.`)
}
})
app.post("/write.htm", checkWritePermissions, (req, res) => this.writeAndCommitTextFile(req, res, req.body.filePath, req.body.content))
// Add a route for file uploads
app.post("/upload.htm", checkWritePermissions, async (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) return res.status(400).send("No files were uploaded.")
const file = req.files.file
const folderName = req.body.folderName
const folderPath = path.join(rootFolder, sanitizeFolderName(folderName))
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
// Check file extension
const fileExtension = path.extname(file.name).toLowerCase().slice(1)
if (file.size > this.maxUploadSize) return res.status(400).send("File size exceeds the maximum limit of 1MB.")
// Save file to disk
const fileName = sanitizeFileName(path.basename(file.name, path.extname(file.name))) + "." + fileExtension
const filePath = path.join(folderPath, fileName)
try {
// Use async `mv` with `await`
await file.mv(filePath)
// Run git and scroll commands asynchronously
await execAsync(`git add -f ${fileName}; git commit -m 'Added ${fileName}'`, { cwd: folderPath })
await this.buildFolder(folderName)
this.addStory(req, `uploaded ${fileName} to ${folderName}`)
res.send("File uploaded successfully")
this.updateFolderAndBuildList(folderName)
} catch (err) {
console.error(err)
res.status(500).send("An error occurred while uploading or processing the file.")
}
})
// In the initFileRoutes method, add this new route:
app.post("/createFromZip.htm", checkWritePermissions, async (req, res) => {
if (!req.files || !req.files.zipFile) return res.status(400).send("No zip file was uploaded.")
const zipFile = req.files.zipFile
const suggestedName = req.body.folderName || path.basename(zipFile.name, ".zip").toLowerCase()
const folderName = sanitizeFolderName(suggestedName)
// Validate folder name
if (!this.isValidFolderName(folderName)) return res.status(400).send(`Invalid folder name "${folderName}". Folder names must start with a letter a-z, ` + `be more than 1 character, and not end in a common file extension.`)
// Check if folder already exists
if (this.folderCache[folderName]) return res.status(409).send(`A folder named "${folderName}" already exists`)
const folderPath = path.join(this.rootFolder, folderName)
const tempPath = path.join(os.tmpdir(), `scroll-${Date.now()}`)
try {
// Create temp directory
await fsp.mkdir(tempPath, { recursive: true })
// Write zip file to temp location
const tempZipPath = path.join(tempPath, "upload.zip")
await zipFile.mv(tempZipPath)
// Create the target folder
await fsp.mkdir(folderPath, { recursive: true })
// Unzip the file
await execAsync(`unzip "${tempZipPath}"`, { cwd: folderPath })
// Initialize git repository
if (!fs.existsSync(path.join(folderPath, ".git"))) await execAsync(`git init; git add .; git commit -m "Initial import from zip file"`, { cwd: folderPath })
// Build the folder
await this.buildFolder(folderName)
// Add to story and update caches
this.addStory(req, `created ${folderName} from zip file`)
this.updateFolderAndBuildList(folderName)
// Redirect to editor
res.send(folderName)
} catch (error) {
console.error(`Error creating folder from zip:`, error)
// Clean up on error
try {
await fsp.rm(folderPath, { recursive: true, force: true })
await fsp.rm(tempPath, { recursive: true, force: true })
} catch (cleanupError) {
console.error("Error during cleanup:", cleanupError)
}
res.status(500).send(`An error occurred while creating folder from zip: ${error.toString().replace(/</g, "<")}`)
} finally {
// Clean up temp directory
try {
await fsp.rm(tempPath, { recursive: true, force: true })
} catch (cleanupError) {
console.error("Error cleaning up temp directory:", cleanupError)
}
}
})
app.post("/echo.htm", checkWritePermissions, async (req, res) => {
res.setHeader("Content-Type", "text/plain")
res.send(req.body)
})
app.post("/insert.htm", checkWritePermissions, async (req, res) => {
const folderName = this.getFolderName(req)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
// Which file to insert data to
const fileName = sanitizeFileName(req.query.fileName)
// Where to redirect after success
const redirectUrl = sanitizeFileName(req.query.redirect)
const line = parseInt(req.query.line)
let particles = req.body.particles
if (!particles) return res.status(400).send("No particles provided")
if (!fileName) return res.status(400).send("No filename provided")
const folderPath = path.join(rootFolder, folderName)
const filePath = path.join(folderPath, fileName)
particles = "\n" + particles // add a new line before new particles
try {
// Default is append
if (req.query.line === undefined) {
await fsp.appendFile(filePath, particles)
} else {
await fsp.access(filePath)
let content = await fsp.readFile(filePath, "utf8")
let lines = content.split("\n")
lines.splice(line - 1, 0, particles)
content = lines.join("\n")
await fsp.writeFile(filePath, content, "utf8")
}
// Run git commands
const clientIp = req.ip || req.connection.remoteAddress
const hostname = req.hostname?.toLowerCase()
await execAsync(`git add "${fileName}"; git commit --author="${clientIp} <${clientIp}@${hostname}>" -m 'Inserted particles into ${fileName}'`, { cwd: folderPath })
await this.buildFolder(folderName)
this.addStory(req, `inserted particles into ${folderPath}/${fileName}`)
res.redirect(redirectUrl)
this.updateFolderAndBuildList(folderName)
} catch (error) {
if (error.code === "ENOENT") {
res.status(404).send("File not found")
} else {
console.error(error)
res.status(500).send(`An error occurred while inserting the particles:\n ${error.toString().replace(/</g, "<")}`)
}
}
})
app.post("/delete.htm", checkWritePermissions, async (req, res) => {
const filePath = path.join(rootFolder, decodeURIComponent(req.query.filePath))
const folderName = path.dirname(filePath).split(path.sep).pop()
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
try {
const fileExists = await exists(filePath)
if (!fileExists) return res.status(404).send("File not found")
const fileName = path.basename(filePath)
const folderPath = path.dirname(filePath)
await fsp.unlink(filePath)
await execAsync(`git rm ${fileName}; git commit -m 'Deleted ${fileName}'`, { cwd: folderPath })
await this.buildFolder(folderName)
res.send("File deleted successfully")
this.addStory(req, `deleted ${fileName} in ${folderName}`)
this.updateFolderAndBuildList(folderName)
} catch (error) {
console.error(error)
res.status(500).send(`An error occurred while deleting the file:\n ${error.toString().replace(/</g, "<")}`)
}
})
app.post("/trash.htm", checkWritePermissions, async (req, res) => {
const { trashFolder } = this
const folderName = sanitizeFolderName(req.body.folderName)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
const sourcePath = path.join(rootFolder, folderName)
const timestamp = Date.now()
const destinationPath = path.join(trashFolder, `${folderName}-${timestamp}`)
try {
// Move the folder to trash
await fsp.rename(sourcePath, destinationPath)
// Remove the folder from the cache
delete folderCache[folderName]
// Rebuild the list file
this.buildListFile()
this.addStory(req, `trashed ${folderName}`)
res.send("Folder moved to trash successfully")
} catch (error) {
console.error(error)
res.status(500).send(`An error occurred while moving the folder to trash:\n ${error.toString().replace(/</g, "<")}`)
}
})
app.post("/rename.htm", checkWritePermissions, async (req, res) => {
const folderName = sanitizeFolderName(req.body.folderName)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
const oldFileName = req.body.oldFileName
const newFileName = sanitizeFileName(req.body.newFileName)
const folderPath = path.join(rootFolder, folderName)
const oldFilePath = path.join(folderPath, oldFileName)
const newFilePath = path.join(folderPath, newFileName)
try {
// Check if the old file exists
await fsp.access(oldFilePath)
// Run git commands
const clientIp = req.ip || req.connection.remoteAddress
const hostname = req.hostname?.toLowerCase()
await execAsync(`git mv ${oldFileName} ${newFileName}; git commit --author="${clientIp} <${clientIp}@${hostname}>" -m 'Renamed ${oldFileName} to ${newFileName}'`, { cwd: folderPath })
await this.buildFolder(folderName)
this.addStory(req, `renamed ${oldFileName} to ${newFileName} in ${folderName}`)
res.send("File renamed successfully")
this.updateFolderAndBuildList(folderName)
} catch (error) {
console.error(error)
res.status(500).send(`An error occurred while renaming the file:\n ${error.toString().replace(/</g, "<")}`)
}
})
app.post("/mv.htm", checkWritePermissions, async (req, res) => {
const oldFolderName = sanitizeFolderName(req.body.oldFolderName)
const newFolderName = sanitizeFolderName(req.body.newFolderName)
// Validate old folder exists
if (!folderCache[oldFolderName]) return res.status(404).send("Source folder not found")
// Validate new folder name
if (!this.isValidFolderName(newFolderName)) return res.status(400).send(`Invalid folder name "${newFolderName}". Folder names must start with a letter a-z, be more than 1 character, and not end in a common file extension.`)
// Check if new folder name already exists
if (folderCache[newFolderName]) return res.status(409).send(`A folder named "${newFolderName}" already exists`)
const oldPath = path.join(rootFolder, oldFolderName)
const newPath = path.join(rootFolder, newFolderName)
try {
// Rename the folder
await fsp.rename(oldPath, newPath)
// Remove from cache
delete folderCache[oldFolderName]
// Update folder cache with new name
await this.updateFolder(newFolderName)
// Rebuild the list file
this.buildListFile()
this.addStory(req, `renamed folder ${oldFolderName} to ${newFolderName}`)
res.send("Folder renamed successfully")
} catch (error) {
console.error(error)
res.status(500).send(`An error occurred while renaming the folder:\n ${error.toString().replace(/</g, "<")}`)
// Try to revert if there was an error
try {
if (
await fsp
.access(newPath)
.then(() => true)
.catch(() => false)
) {
await fsp.rename(newPath, oldPath)
}
} catch (revertError) {
console.error("Error reverting failed rename:", revertError)
}
}
})
}
initCommandRoutes() {
const { app } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
app.get("/t/:folderName", checkWritePermissions, async (req, res) => {
await this.runCommand(req, res, "test")
})
app.get("/b/:folderName", checkWritePermissions, async (req, res) => {
await this.runCommand(req, res, "build")
})
app.get("/f/:folderName", checkWritePermissions, async (req, res) => {
await this.runCommand(req, res, "format")
})
}
async runCommand(req, res, command) {
const folderName = this.getFolderName(req)
const { rootFolder, folderCache } = this
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
try {
const folderPath = path.join(rootFolder, folderName)
const { stdout } = await execAsync(`scroll list | scroll ${command}`, { cwd: folderPath })
res.setHeader("Content-Type", "text/plain")
res.send(stdout.toString())
if (command !== "test") this.updateFolderAndBuildList(folderName)
} catch (error) {
console.error(`Error running '${command}' in '${folderName}':`, error)
res.status(500).send(`An error occurred while running '${command}' in '${folderName}'`)
}
}
initZipRoutes() {
const { app, folderCache } = this
app.get("/:folderName.zip", async (req, res) => {
const folderName = sanitizeFolderName(req.params.folderName)
const cacheEntry = folderCache[folderName]
if (!cacheEntry) return res.status(404).send("Folder not found")
// Check if the zip is in memory cache
let zipBuffer = cacheEntry.zip
if (!zipBuffer) {
try {
zipBuffer = await this.zipFolder(folderName)
if (!zipBuffer) return res.status(404).send("Folder not found or failed to zip")
} catch (err) {
console.error("Error zipping folder:", err)
return res.status(500).send("Error zipping folder")
}
}
// Set headers for zip file
res.setHeader("Content-Type", "application/zip")
res.setHeader("Content-Disposition", `attachment; filename=${folderName}.zip`)
res.send(zipBuffer)
})
}
async zipFolder(folderName) {
const { rootFolder, folderCache } = this
const folderPath = path.join(rootFolder, folderName)
const zipBuffer = await new Promise((resolve, reject) => {
const output = []
const zip = spawn("zip", ["-r", "-", "."], { cwd: folderPath })
zip.stdout.on("data", data => output.push(data))
zip.on("close", code => {
if (code === 0) resolve(Buffer.concat(output))
else reject(new Error("Error creating zip file"))