-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathScrollHub.js
2324 lines (1958 loc) · 80.8 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 dns = require("dns").promises
const path = require("path")
const util = require("util")
const crypto = require("crypto")
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")
// 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 { ScriptRunner } = require("./ScriptRunner.js")
const packageJson = require("./package.json")
const scrollFs = new ScrollFileSystem()
// This
const { TrafficMonitor } = require("./TrafficMonitor.js")
const { CronRunner } = require("./CronRunner.js")
const { FolderIndex } = require("./FolderIndex.js")
const { Agents } = require("./Agents.js")
const exists = async filePath => {
const fileExists = await fsp
.access(filePath)
.then(() => true)
.catch(() => false)
return fileExists
}
const isGreaterOrEqualVersion = (version1, version2) => {
// console.log(isGreaterOrEqualVersion("0.5.1", "0.5.0")); // true
// console.log(isGreaterOrEqualVersion("0.5.0", "0.5.0")); // true
// console.log(isGreaterOrEqualVersion("0.4.9", "0.5.0")); // false
// console.log(isGreaterOrEqualVersion("1.0.0", "0.9.9")); // true
const [major1, minor1, patch1] = version1.split(".").map(Number)
const [major2, minor2, patch2] = version2.split(".").map(Number)
if (major1 !== major2) return major1 >= major2
if (minor1 !== minor2) return minor1 >= minor2
return patch1 >= patch2
}
const ScrollToHtml = async scrollCode => {
const page = new ScrollFile(scrollCode)
await page.fuse()
return page.scrollProgram.asHtml
}
const generateFileName = async (basePath, strategy, content) => {
let name = "untitled.scroll"
switch (strategy) {
case "timestamp":
name = Date.now() + ".scroll"
break
case "autoincrement":
// Find the highest numbered file and increment
if (!(await exists(basePath))) {
name = `1.scroll`
break
}
const files = await fsp.readdir(basePath)
const scrollFiles = files.filter(file => file.endsWith(".scroll"))
const numbers = scrollFiles
.map(file => {
const match = file.match(/^(\d+)\.scroll$/)
return match ? parseInt(match[1], 10) : 0
})
.filter(num => num > 0)
const nextNumber = numbers.length > 0 ? Math.max(...numbers) + 1 : 1
name = `${nextNumber}.scroll`
break
case "hash":
// Generate a hash from the content or a random string
const hash = crypto
.createHash("md5")
.update(content || crypto.randomBytes(16))
.digest("hex")
.slice(0, 10)
name = `${hash}.scroll`
break
case "random":
// Generate a random string
const randomStr = crypto.randomBytes(8).toString("hex")
name = `${randomStr}.scroll`
break
case "datetime":
// Use formatted date and time
const now = new Date()
const formattedDateTime = now.toISOString().replace(/[:\.]/g, "-").slice(0, 19)
name = `${formattedDateTime}.scroll`
break
}
const fullPath = path.join(basePath, name)
const fileExists = await exists(fullPath)
// Recursive check to ensure unique filename
if (fileExists) throw new Error(`File ${fullPath} exists`)
return fullPath
}
const requestsFile = folderName => `title Traffic Data
metaTags
homeButton
buildHtml
theme gazette
printTitle
container
Real time view
/globe.html?folderName=${folderName}
scrollButton 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 => {
// Split path into components and filter out empty parts and parent directory attempts
const parts = name.split("/").filter(part => {
// Remove empty parts and any parts containing ".."
return part && !part.includes("..")
})
// Sanitize each remaining path component
const sanitizedParts = parts.map(part => part.replace(/[^a-zA-Z0-9._\-]/g, ""))
// If we end up with no valid parts, return empty string
if (sanitizedParts.length === 0) return ""
// Rejoin with forward slashes
return sanitizedParts.join("/")
}
const sampleConfig = `// Sample config options below. Uncomment and fill out to use.
// wildcard *.example.com /etc/letsencrypt/live/example.com/fullchain.pem /etc/letsencrypt/live/example.com/privkey.pem
// claude [anthropic api key]
// deepseek [deepseek api key]`
// todo: improve Scroll to clean this up
const sampleCreate = `div
class promptSettings
select
id aiModelSelect
option Claude
value claude
option Deepseek
value deepseek
option DSReasoner
value deepseekreasoner
select
id tldSelect
option Scroll.pub
value scroll.pub
option Powerhouse.wiki
value powerhouse.wiki
option FrameHub.pro
value framehub.pro`
class ScrollHub {
constructor(dir = path.join(os.homedir(), "folders")) {
this.app = express()
const app = this.app
this.port = 80
this.maxUploadSize = 100 * 1000 * 1024
this.requestsServed = 0
this.startCpuUsage = process.cpuUsage()
this.lastCpuUsage = this.startCpuUsage
this.lastCpuCheck = Date.now()
this.hostname = os.hostname()
this.wildCardCerts = []
this.rootFolder = dir
const hubFolder = path.join(dir, ".hub")
this.hubFolder = hubFolder
this.configPath = path.join(hubFolder, `config.scroll`)
this.publicFolder = path.join(hubFolder, "public")
this.trashFolder = path.join(hubFolder, "trash")
this.globalLogFile = path.join(hubFolder, ".global.log.txt")
this.slowLogFile = path.join(hubFolder, ".slow.txt")
this.storyLogFile = path.join(hubFolder, ".writes.txt")
this.folderCache = {}
this.sseClients = new Set()
this.folderIndex = new FolderIndex(this)
this.trafficMonitor = new TrafficMonitor(this.globalLogFile, this.hubFolder)
this.version = packageJson.version
}
async getServerPublicIpsFromDNS() {
try {
const resolver = new dns.Resolver()
resolver.setServers(["8.8.8.8"])
return await resolver.resolve4(this.hostname)
} catch (err) {
console.error(err)
return []
}
}
async startAll() {
const { rootFolder } = this
const lastFolder = rootFolder.split("/").pop()
process.title = process.title + ` ScrollHub ${lastFolder}`
this.startTime = Date.now()
await this.ensureInstalled()
this.config = Particle.fromDisk(this.configPath)
this.serverIps = Object.values(os.networkInterfaces())
.flat()
.map(iface => iface.address)
.filter(ip => !ip.includes("::")) // Filter IPv6
const publicIps = await this.getServerPublicIpsFromDNS()
console.log("Public IPs from DNS: " + JSON.stringify(publicIps))
this.serverIps = this.serverIps.concat(publicIps)
this.ensureTemplatesInstalled()
this.warmFolderCache()
this.initVandalProtection()
this.enableCompression()
this.enableCors()
this.enableFormParsing()
this.enableFileUploads()
this.initAnalytics()
this.addStory({ ip: "admin" }, `started ScrollHub v${this.version}`)
console.log(`ScrollHub version: ${this.version}`)
console.log(`Serving all folders in: ${this.rootFolder}`)
console.log(`Saving runtime data in: ${this.hubFolder}`)
console.log(`Max memory: ${v8.getHeapStatistics().heap_size_limit / 1024 / 1024} MB`)
this.initFileRoutes()
this.initAIRoutes()
this.initGitRoutes()
this.initHistoryRoutes()
this.initZipRoutes()
this.initCommandRoutes()
this.initSSERoute()
this.initCloneRoute()
this.initScriptRunner()
this.enableStaticFileServing()
this.servers = []
if (!this.isLocalHost) this.servers.push(this.startHttpsServer())
this.servers.push(this.startHttpServer())
this.init404Routes()
this.cronRunner = new CronRunner(this).start()
return this
}
initCloneRoute() {
const { folderCache, app } = this
app.get("/clone", (req, res) => {
const folderName = this.getFolderName(req)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
const html = `<!DOCTYPE html>
<html>
<head>
<title>Clone ${folderName}</title>
<style>
body { margin: 0; }
iframe { width: 100%; height: 100vh; border: none; }
.clone-btn {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 100;
padding: 30px 60px;
background: #0066cc;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 24px;
font-weight: bold;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
transition: all 0.2s;
}
.clone-btn:hover {
background: #0052a3;
transform: translate(-50%, -50%) scale(1.05);
}
</style>
</head>
<body>
<button class="clone-btn" onclick="cloneSite()">Clone this site</button>
<iframe src="/${folderName}"></iframe>
<script>
function cloneSite() {
fetch('/cloneFolder.htm', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'folderName=${folderName}&redirect=false'
})
.then(res => res.text())
.then(name => window.location.href = '/edit.html?folderName=' + name);
}
</script>
</body>
</html>`
res.send(html)
})
}
initScriptRunner() {
this.scriptRunner = new ScriptRunner(this)
this.scriptRunner.init()
}
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.trafficMonitor.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())
}
getBaseUrlForFolder(folderName, hostname, protocol, isLocalHost) {
// if localhost, no custom domains
if (isLocalHost) return `/${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
}
enableCors() {
this.app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Handle preflight requests
if (req.method === "OPTIONS") {
return res.status(200).end()
}
next()
})
}
enableFormParsing() {
this.app.use(express.json())
this.app.use(express.urlencoded({ extended: true }))
}
enableFileUploads() {
this.app.use(fileUpload({ limits: { fileSize: this.maxUploadSize } }))
}
async sendFolderNotFound(res, hostname) {
const message = `title Folder Not Found
css
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
line-height: 1.6;
}
h1 { color: #333; }
.message { color: #666; }
.suggestion { margin-top: 20px; color: #0066cc; }
# Folder Not Found
The folder "${hostname}" does not exist on this ScrollHub instance.
link https://github.com/breck7/ScrollHub ScrollHub
class message
If you'd like to create this folder, visit our main site to get started.
link https://${this.hostname} our main site
class suggestion`
// Use 400 (Bad Request) for unknown hostname
const html = await ScrollToHtml(message)
res.status(400).send(html)
return
}
enableStaticFileServing() {
const { app, folderCache, rootFolder } = this
const isRootHost = req => {
const hostname = req.hostname?.toLowerCase()
// If its the main hostname, serve the folders directly
if (hostname === this.hostname || hostname === "localhost") return true
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/
if (ipv4Regex.test(hostname))
// treat direct IP requests as host requests
return true
return false
}
app.use((req, res, next) => {
const hostname = req.hostname?.toLowerCase()
// If no hostname, continue to next middleware
if (!hostname) return next()
// If hostname is the main server hostname, continue to next middleware
if (isRootHost(req)) return next()
// If the hostname requested isnt root host and doesn't exist in folderCache, return 400
if (!folderCache[hostname]) return this.sendFolderNotFound(res, hostname)
// If domain exists, serve from its folder
const folderPath = path.join(rootFolder, hostname)
express.static(folderPath, { dotfiles: "allow" })(req, res, next)
})
app.use((req, res, next) => {
// On the root host, all folders are served like: rootDomain/folder/
if (isRootHost(req)) return express.static(rootFolder, { dotfiles: "allow" })(req, res, next)
next()
})
// Serve the process's public folder
app.use(express.static(this.publicFolder, { dotfiles: "allow" }))
}
init404Routes() {
const { app, rootFolder, publicFolder } = 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(publicFolder, "404.html"))
})
})
}
isSummarizing = {}
async buildRequestsSummary(folder = "") {
const { rootFolder, folderCache, hubFolder } = 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(this.publicFolder)
const trafficMonitor = new TrafficMonitor(logFile, hubFolder)
await trafficMonitor.processLogFile()
const content = folder ? trafficMonitor.csv : trafficMonitor.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")
const file = new ScrollFile(undefined, reqFile, new ScrollFileSystem())
await file.fuse()
await file.scrollProgram.buildAll()
} else await this.buildPublicFolder()
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((req, res, next) => {
req.startTime = performance.now()
res.on("finish", () => {
this.logRequest(req, res)
this.requestsServed++
})
next()
})
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.")
const base = this.getBaseUrlForFolder(folderName, req.hostname, req.protocol + ":", this.isLocalHost)
return res.redirect(base + "/.requests.html")
}
await this.buildRequestsSummary()
res.send(`Done.`)
})
app.get("/hostname.htm", (req, res) => res.send(req.hostname))
}
reqToLog(req, res) {
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)
const responseTime = ((performance.now() - req.startTime) / 1000).toFixed(1)
return `${method === "GET" ? "read" : "write"} ${folderName || hostname} ${protocol}://${hostname}${url} ${Date.now()} ${ip} ${responseTime} ${res.statusCode} ${userAgent}\n`
}
async logRequest(req, res) {
const { folderCache, globalLogFile, slowLogFile } = this
const ip = req.ip || req.connection.remoteAddress
const folderName = this.getFolderName(req)
const logEntry = this.reqToLog(req, res)
fs.appendFile(globalLogFile, logEntry, err => {
if (err) console.error("Failed to log request:", err)
})
if (performance.now() - req.startTime > 1000) {
fs.appendFile(slowLogFile, logEntry, err => {
if (err) console.error("Failed to log slow 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)
}
}
}
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, folderIndex } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
app.get("/revisions.htm/:folderName", async (req, res) => {
const folderName = 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("/commits.htm", async (req, res) => {
const folderName = this.getFolderName(req)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
await folderIndex.sendCommits(folderName, req.query.count || 10, res)
})
app.get("/commits.json", async (req, res) => {
const folderName = this.getFolderName(req)
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
const commits = await folderIndex.getCommits(folderName, req.query.count || 10)
res.send(JSON.stringify(commits, undefined, 2))
})
app.get("/fileHistory.htm", async (req, res) => {
const folderName = this.getFolderName(req)
const filePath = req.query.filePath
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
if (!filePath) return res.status(400).send("File path is required")
await folderIndex.sendFileHistory(folderName, filePath, req.query.count || 100, res)
})
app.post("/revert.htm/:folderName", checkWritePermissions, async (req, res) => {
const folderName = 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
await execAsync(`git checkout ${targetHash} . && git add . && git commit ${this.getCommitAuthor(req)} -m "Reverted to ${targetHash}" --allow-empty`, { cwd: folderPath })
this.addStory(req, `reverted ${folderName}`)
await this.buildFolder(folderName)
res.redirect("/commits.htm?folderName=" + 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, "<")}`)
}
})
}
getCommitAuthor(req) {
let author = ""
if (req.body.author?.match(/^[^<>]+\s<[^<>@\s]+@[^<>@\s]+>$/)) author = req.body.author
else {
const clientIp = req.ip || req.connection.remoteAddress
const hostname = req.hostname?.toLowerCase()
const author = `${clientIp} <${clientIp}@${hostname}>`
}
return `--author="${author}"`
}
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
}
async exists(filePath) {
return await exists(filePath)
}
async getFileList(folderName) {
const { folderCache, rootFolder } = this
const folderPath = path.join(rootFolder, folderName)
const cachedEntry = folderCache[folderName]
// Get all unique directories containing tracked files
const directoriesSet = new Set()
Object.keys(cachedEntry.files).forEach(file => directoriesSet.add(path.join(folderPath, path.dirname(file))))
const files = cachedEntry.files
for (let dir of directoriesSet) {
const fileNames = (await fsp.readdir(dir, { withFileTypes: true })).filter(dirent => dirent.isFile() && dirent.name !== ".git" && dirent.name !== ".DS_Store").map(dirent => dirent.name)
fileNames.forEach(file => {
const relativePath = path.join(dir, file).replace(folderPath, "").substr(1)
if (!files[relativePath])
files[relativePath] = {
versioned: false
}
})
}
return files
}
async handleCreateFolder(newFolderName, req, res) {
try {
const result = await this.createFolder(newFolderName)
if (result.errorMessage) return this.handleCreateError(req, res, result)
const { folderName } = result
this.addStory(req, `created ${folderName}`)
res.redirect(`/edit.html?folderName=${folderName}&command=showWelcomeMessageCommand`)
} catch (error) {
console.error(error)
res.status(500).send("Sorry, an error occurred while creating the folder:", error)
}
}
initAIRoutes() {
const { app, folderCache } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
const agents = new Agents(this)
app.post("/createFromPrompt.htm", checkWritePermissions, async (req, res) => {
try {
const prompt = req.body.prompt
const agent = (req.body.agent || "claude").toLowerCase()
const template = req.body.template
const welcomeMessage = req.body.welcomeMessage || "scrollhub"
const domainSuffix = req.body.tld || "scroll.pub"
if (!prompt) return res.status(400).send("Prompt is required")
// Generate website content from prompt
const response = await agents.createFolderNameAndFilesFromPrompt(prompt, this.folderCache, agent, template, domainSuffix)
const { folderName, files } = response.parsedResponse
files["prompt.json"] = JSON.stringify(response.completion, null, 2)
// Create the folder with generated files
await this.createFolderFromFiles(folderName, files)
try {
await this.buildFolder(folderName)
} catch (err) {
console.error(err)
}
// Add to story and redirect
this.addStory(req, `created ${folderName} from prompt using ${agent}`)
res.redirect(`/edit.html?folderName=${folderName}&command=showWelcomeMessageCommand&welcomeMessage=${welcomeMessage}`)
} catch (error) {
console.error("Error creating from prompt:", error)
res.status(500).send("Failed to create website from prompt: " + error.message)
}
})
}
async doesHaveSslCert(folderName) {
// by default assume root server has ssl certs
if (!folderName.includes(".")) return true
// Now we see if the custom domain has one
const certPath = this.makeCertPath(folderName)
const hasSslCert = await exists(certPath)
return hasSslCert ? hasSslCert : this.getMatchingWildcardCert(folderName)
}
makeCertPath(folderName) {
return path.join(this.rootFolder, folderName, `.${folderName}.crt`)
}
initStampRoute() {
const { app, rootFolder, folderCache } = this
// Text file extensions - only include actual text formats
const textExtensions = new Set("scroll parsers txt html htm rb php md perl py mjs css json csv tsv psv ssv js".split(" "))
const isTextFile = filepath => {
const ext = path.extname(filepath).toLowerCase().slice(1)
return textExtensions.has(ext)
}
async function makeStamp(dir) {
let stamp = "stamp\n"
const handleFile = async (indentation, relativePath, itemPath) => {
if (!isTextFile(itemPath)) return
stamp += `${indentation}${relativePath}\n`
const content = await fsp.readFile(itemPath, "utf8")
stamp += `${indentation} ${content.replace(/\n/g, `\n${indentation} `)}\n`
}
let gitTrackedFiles
async function processDirectory(currentPath, depth) {
const items = await fsp.readdir(currentPath)
for (const item of items) {
const itemPath = path.join(currentPath, item)
const relativePath = path.relative(dir, itemPath)
if (!gitTrackedFiles.has(relativePath)) continue
const stats = await fsp.stat(itemPath)
const indentation = " ".repeat(depth)
if (stats.isDirectory()) {
stamp += `${indentation}${relativePath}/\n`
await processDirectory(itemPath, depth + 1)
} else if (stats.isFile()) {
await handleFile(indentation, relativePath, itemPath)
}
}
}
const stats = await fsp.stat(dir)
if (stats.isDirectory()) {
// Get list of git-tracked files
const { stdout } = await execAsync("git ls-files", { cwd: dir })
gitTrackedFiles = new Set(stdout.split("\n").filter(Boolean))
await processDirectory(dir, 1)
} else {
await handleFile(" ", dir, dir)
}
return stamp.trim()
}
app.get("/stamp", async (req, res) => {
const folderName = this.getFolderName(req)
const { rootFolder, folderCache } = this
// Check if folder exists
if (!folderCache[folderName]) return res.status(404).send("Folder not found")
const folderPath = path.join(rootFolder, folderName)
try {
// Generate the stamp
const stamp = await makeStamp(folderPath)
// Set content type and send response
res.setHeader("Content-Type", "text/plain; charset=utf-8")
res.send(stamp)
} catch (error) {
console.error("Error generating stamp:", error)
res.status(500).send(`Error generating stamp: ${error.toString().replace(/</g, "<")}`)
}
})
}
initFileRoutes() {
const { app, rootFolder, folderCache } = this
const checkWritePermissions = this.checkWritePermissions.bind(this)
app.post("/createFolder.htm", checkWritePermissions, async (req, res) => this.handleCreateFolder(req.body.folderName, req, res))
app.post("/cloneFolder.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(req, 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}&command=showWelcomeMessageCommand`)
} 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 = this.getFolderName(req)
const folderEntry = folderCache[folderName]
if (!folderEntry) return res.status(404).send(`Folder '${folderName}' not found`)
res.setHeader("Content-Type", "text/json")
const files = await this.getFileList(folderName)
if (folderEntry.hasSslCert === undefined) folderEntry.hasSslCert = await this.doesHaveSslCert(folderName)
const { hasSslCert, ips } = folderEntry
const { serverIps } = this
res.send(JSON.stringify({ files, hasSslCert, ips, serverIps }, undefined, 2))
})
app.get("/ls.csv", async (req, res) => {
const folderName = this.getFolderName(req)
const folderEntry = folderCache[folderName]
if (!folderEntry) return res.status(404).send(`Folder '${folderName}' not found`)
res.setHeader("Content-Type", "text/plain")
const files = await this.getFileList(folderName)
res.send(new Particle(files).asCsv)
})
this.initStampRoute()