This repository has been archived by the owner on Jul 15, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
1713 lines (1447 loc) · 70.5 KB
/
index.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
////////////////////////////////////////////////////////////////////////////////
//
// Site.js
//
// Develop, test, and deploy your secure static or dynamic personal web site
// with zero configuration.
//
// Includes and has automatic support for the Hugo static site generator
// (https://gohugo.io). Just add your source to a folder called .hugo (to mount
// onto a path other than the root, name the folder with the path you want
// e.g., .hugo-docs will be mounted on https://<your.site>/docs).
//
// Copyright ⓒ 2019-2020 Aral Balkan. Licensed under AGPLv3 or later.
// Shared with ♥ by the Small Technology Foundation.
//
// Like this? Fund us!
// https://small-tech.org/fund-us
//
////////////////////////////////////////////////////////////////////////////////
const fs = require('fs-extra')
const path = require('path')
const os = require('os')
const EventEmitter = require('events')
const childProcess = require('child_process')
const http = require('http')
const https = require('@small-tech/https')
const expressWebSocket = require('@small-tech/express-ws')
const Hugo = require('@small-tech/node-hugo')
const instant = require('@small-tech/instant')
const crossPlatformHostname = require('@small-tech/cross-platform-hostname')
const getRoutes = require('@small-tech/web-routes-from-files')
const JSDB = require('@small-tech/jsdb')
const Graceful = require('node-graceful')
const express = require('express')
const bodyParser = require('body-parser')
const helmet = require('helmet')
const { createProxyMiddleware } = require('http-proxy-middleware')
const enableDestroy = require('server-destroy')
const moment = require('moment')
const morgan = require('morgan')
const chokidar = require('chokidar')
const decache = require('decache')
const prepareRequest = require('bent')
const clr = require('./lib/clr')
const cli = require('./bin/lib/cli')
const Stats = require('./lib/Stats')
const asyncForEach = require('./lib/async-foreach')
const errors = require('./lib/errors')
const Util = require('./lib/Util')
class Site {
//
// Class.
//
static #appNameAndVersionAlreadyLogged = false
static #manifest = null
static get HUGO_LOGO () {
return `${clr('🅷', 'magenta')} ${clr('🆄', 'blue')} ${clr('🅶', 'green')} ${clr('🅾', 'yellow')} `
}
//
// Manifest helpers. The manifest file is created by the build script and includes metadata such as the
// binary version (in calendar version format YYYYMMDDHHmmss), the package version (in semantic version format),
// the source version (the git hash of the commit that corresponds to the source code the binary was built from), and
// the release channel (alpha, beta, or release).
//
static RELEASE_CHANNEL = {
alpha : 'alpha',
beta : 'beta',
release: 'release',
npm: 'npm'
}
static readAndCacheManifest () {
try {
this.#manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'manifest.json'), 'utf-8'))
} catch (error) {
// When running under Node (not wrapped as a binary), there will be no manifest file. So mock one.
const options = {shell: os.platform() === 'win32' ? 'powershell' : '/bin/bash', env: process.env}
let sourceVersion
try {
const [silenceOutput1, silenceOutput2] = os.platform() === 'win32' ? ['', ''] : ['> /dev/null', '2>&1']
const command = `pushd ${__dirname} ${silenceOutput1}; git log -1 --oneline ${silenceOutput2}`
sourceVersion = childProcess.execSync(command, options).toString().match(/^[0-9a-fA-F]{7}/)[0]
} catch (error) {
// We are not running from source.
sourceVersion = 'npm'
}
// Note: we switch to __dirname because we need to if Site.js is running as a daemon from source.
this.#manifest = {
releaseChannel: 'npm',
// Note: the time is a guess based on the minutes at:
// http://undocs.org/en/A/PV.183 ;)
binaryVersion: '19481210233000',
packageVersion: (require(path.join(__dirname, 'package.json'))).version,
sourceVersion,
hugoVersion: (new Hugo()).version,
platform: {linux: 'linux', win32: 'windows', 'darwin': 'macOS'}[os.platform()],
architecture: os.arch()
}
}
}
static getFromManifest (key) {
if (this.#manifest === null) {
this.readAndCacheManifest()
}
return this.#manifest[key]
}
static get releaseChannel () { return this.getFromManifest('releaseChannel') }
static get binaryVersion () { return this.getFromManifest('binaryVersion') }
static get packageVersion () { return this.getFromManifest('packageVersion') }
static get sourceVersion () { return this.getFromManifest('sourceVersion') }
static get hugoVersion () { return this.getFromManifest('hugoVersion') }
static get platform () { return this.getFromManifest('platform') }
static get architecture () { return this.getFromManifest('architecture') }
static binaryVersionToHumanReadableDateString (binaryVersion) {
// Is this the dummy version that signals a development build?
if (binaryVersion === '19481210233000') {
return 'n/a (not running from binary release)'
}
const m = moment(binaryVersion, 'YYYYMMDDHHmmss')
return `${m.format('MMMM Do, YYYY')} at ${m.format('HH:mm:ss')}`
}
static get humanReadableBinaryVersion () {
if (this.#manifest === null) {
this.readAndCacheManifest()
}
return this.binaryVersionToHumanReadableDateString(this.#manifest.binaryVersion)
}
static get releaseChannelFormattedForConsole () {
const siteJSBlue = line => `\u001b[38;173;216;230;0m${line}\u001b[0m\n`
switch(this.releaseChannel) {
// Spells ALPHA in large red block letters.
case this.RELEASE_CHANNEL.alpha:
return [
` ${clr(' █████ ██ ██████ ██ ██ █████', 'red')}\n`,
` ${clr('██ ██ ██ ██ ██ ██ ██ ██ ██', 'red')}\n`,
` ${clr('███████ ██ ██████ ███████ ███████', 'red')}\n`,
` ${clr('██ ██ ██ ██ ██ ██ ██ ██', 'red')}\n`,
` ${clr('██ ██ ███████ ██ ██ ██ ██ ██', 'red')}\n`,
'\n'
]
// Spells BETA in large yellow block letters.
case this.RELEASE_CHANNEL.beta:
return [
` ${clr('██████ ███████ ████████ █████', 'yellow')}\n`,
` ${clr('██ ██ ██ ██ ██ ██', 'yellow')}\n`,
` ${clr('██████ █████ ██ ███████', 'yellow')}\n`,
` ${clr('██ ██ ██ ██ ██ ██', 'yellow')}\n`,
` ${clr('██████ ███████ ██ ██ ██', 'yellow')}\n`,
'\n'
]
default:
return [
siteJSBlue('███████ ██ ████████ ███████ ██ ███████'),
` ${siteJSBlue('██ ██ ██ ██ ██ ██ ')}`,
` ${siteJSBlue('███████ ██ ██ █████ ██ ███████')}`,
` ${siteJSBlue(' ██ ██ ██ ██ ██ ██ ██')}`,
` ${siteJSBlue('███████ ██ ██ ███████ ██ █████ ███████')}`,
'\n'
]
}
}
// Returns the cross-platform hostname (os.hostname() on Linux and macOS, special handling on Windows to return the
// full computer name, which can be a domain name and thus the equivalent of hostname on Linux and macOS).
static get hostname () { return this._hostname ? this._hostname : crossPlatformHostname }
static set hostname (domain) { this._hostname = domain }
// This is the directory that settings and other persistent data is stored for Site.js.
static get settingsDirectory () { return path.join(Util.unprivilegedHomeDirectory(), '.small-tech.org', 'site.js') }
// Logs a nicely-formatted version string based on
// the version set in the package.json file to console.
// (Only once per Site lifetime.)
// (Synchronous.)
static logAppNameAndVersion (compact = false) {
if (process.env.QUIET) {
return
}
if (!Site.#appNameAndVersionAlreadyLogged && !process.argv.includes('--dont-log-app-name-and-version')) {
let prefix1 = compact ? ' 🌱 ' : ' 🌱 '
let prefix2 = ' '
this.readAndCacheManifest()
let message = [
this.releaseChannel === this.RELEASE_CHANNEL.release || this.binaryVersion === '19481210233000' /* (dev) */ ? `\n${prefix1}` : `\n${prefix1}Site.js\n\n`
].concat(this.releaseChannelFormattedForConsole).concat([
`${prefix2}Created ${clr(this.humanReadableBinaryVersion, 'green')}\n`,
'\n',
`${prefix2}Version ${clr(`${this.binaryVersion}-${this.packageVersion}-${this.sourceVersion}-${this.platform}/${this.architecture}`, 'green')}\n`,
`${prefix2}Node.js ${clr(`${process.version.replace('v', '')}`, 'green')}\n`,
`${prefix2}Hugo ${clr(`${this.hugoVersion}`, 'green')}\n`,
'\n',
`${prefix2}Base ${clr(`https://sitejs.org/nexe/${process.platform}-${process.arch}-${process.version.replace('v', '')}`, 'cyan')}\n`,
`${prefix2}Source ${clr(`https://source.small-tech.org/site.js/app/-/tree/${this.sourceVersion}`, 'cyan')}\n\n`,
`${prefix2}╔═══════════════════════════════════════════╗\n`,
`${prefix2}║ Like this? Fund us! ║\n`,
`${prefix2}║ ║\n`,
`${prefix2}║ We’re a tiny, independent not-for-profit. ║\n`,
`${prefix2}║ https://small-tech.org/fund-us ║\n`,
`${prefix2}╚═══════════════════════════════════════════╝\n`,
])
if (compact) {
message = message.map(l => l.replace(/^ /, ''))
}
message = message.join('')
console.log(message)
Site.#appNameAndVersionAlreadyLogged = true
}
}
// Default error pages.
static default404ErrorPage(missingPath) {
return `<!doctype html><html lang="en" style="font-family: sans-serif; background-color: #eae7e1"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Error 404: Not found</title></head><body style="display: grid; align-items: center; justify-content: center; height: 100vh; vertical-align: top; margin: 0;"><main><h1 style="font-size: 16vw; color: black; text-align:center; line-height: 0.25">4🤭4</h1><p style="font-size: 4vw; text-align: center; padding-left: 2vw; padding-right: 2vw;"><span>Could not find</span> <span style="color: grey;">${missingPath}</span></p></main></body></html>`
}
static default500ErrorPage(errorMessage) {
return `<!doctype html><html lang="en" style="font-family: sans-serif; background-color: #eae7e1"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Error 500: Internal Server Error</title></head><body style="display: grid; align-items: center; justify-content: center; height: 100vh; vertical-align: top; margin: 0;"><main><h1 style="font-size: 16vw; color: black; text-align:center; line-height: 0.25">5🔥😱</h1><p style="font-size: 4vw; text-align: center; padding-left: 2vw; padding-right: 2vw;"><span>Internal Server Error</span><br><br><span style="color: grey;">${errorMessage}</span></p></main></body></html>`
}
//
// Instance.
//
// Creates a Site instance. Customise it by passing an options object with the
// following properties (all optional):
//
// • domain: (string) the main domain to serve (defaults to the hostname)
// • path: (string) the path to serve (defaults to the current working directory).
// • port: (integer) the port to bind to (between 0 - 49,151; the default is 443).
// • global: (boolean) if true, automatically provision an use Let’s Encrypt TLS certificates.
// • proxyPort: (number) if provided, a proxy server will be created for the port (and path will be ignored)
// • aliases: (string) comma-separated list of domains that we should get TLS certs
// for and serve.
//
// Note: if you want to run the site on a port < 1024 on Linux, ensure that privileged ports are disabled.
// ===== e.g., use require('lib/ensure').disablePrivilegedPorts()
//
// For details, see: https://source.small-tech.org/site.js/app/-/issues/169
constructor (options) {
// Introduce ourselves.
Site.logAppNameAndVersion()
Util.refuseToRunAsRoot()
this.eventEmitter = new EventEmitter()
// Ensure that the settings directory exists and create it if it doesn’t.
fs.ensureDirSync(Site.settingsDirectory)
// The options parameter object and all supported properties on the options parameter
// object are optional. Check and populate the defaults.
if (options === undefined) options = {}
if (typeof options.domain === 'string') {
Site.hostname = options.domain
}
const _pathToServe = typeof options.path === 'string' ? options.path : '.'
// It is a common mistake to start the server in a .dynamic folder (or subfolder)
// or a .hugo folder or subfolder. In these cases, try to recover and do the right thing.
const {pathToServe, absolutePathToServe} = Util.magicallyRewritePathToServeIfNecessary(options.path, _pathToServe)
this.pathToServe = pathToServe
this.absolutePathToServe = absolutePathToServe
this.databasePath = path.join(this.absolutePathToServe, '.db')
this.port = typeof options.port === 'number' ? options.port : 443
this.global = typeof options.global === 'boolean' ? options.global : false
this.aliases = Array.isArray(options.aliases) ? options.aliases : []
this.syncHost = options.syncHost
this.skipDomainReachabilityCheck = options.skipDomainReachabilityCheck
this.accessLogErrorsOnly = options.accessLogErrorsOnly
this.accessLogDisable = options.accessLogDisable
if (this.skipDomainReachabilityCheck) {
this.log(` ⚠ ${clr('❨site.js❩ Domain reachability pre-flight check is disabled.', 'yellow')}`)
}
if (this.accessLogErrorsOnly && !this.accessLogDisable) {
this.log(` ⚠ ${clr('❨site.js❩ Access log is only showing errors.', 'yellow')}`)
}
if (this.accessLogDisable) {
this.log(` ⚠ ${clr('❨site.js❩ Access log is disabled (not even errors will be shown).', 'yellow')}`)
}
// Substitute shorthand www alias for full domain.
this.aliases = this.aliases.map(alias => alias === 'www' ? `www.${Site.hostname}` : alias)
// Has a proxy server been requested? If so, we flag it and save the port
// we were asked to proxy. In this case, pathToServe is ignored/unused.
this.isProxyServer = false
this.proxyPort = null
if (typeof options.proxyPort === 'number') {
this.isProxyServer = true
this.proxyPort = options.proxyPort
}
// Also save a copy of the options.
this.options = options
//
// Create the Express app. We will configure it later.
//
this.stats = this.initialiseStatistics()
this.app = express()
// Add a reference to the to Site.js instance to the app.
this.app.Site = Site
this.app.site = this
// Create the HTTPS server.
this.createServer()
}
// Conditionally log to console.
log(...args) {
if (process.env.QUIET) {
return
}
console.log(...args)
}
// The app configuration is handled in an asynchronous method
// as there is a chance that we will have to wait for a Hugo
// build to complete.
async configureApp () {
this.startAppConfiguration()
if (this.isProxyServer) {
this.configureProxyRoutes()
} else {
await this.configureAppRoutes()
}
this.endAppConfiguration()
}
// Middleware common to both regular servers and proxy servers
// that go at the start of the app configuration.
startAppConfiguration() {
// Express.js security with HTTP headers.
this.app.use(helmet({
frameguard: !this.options.allowEmbeds
}))
// Opt out of Google Chrome tracking everything you do.
// Note: if you’re reading this, stop using Google Chrome.
// It is ridiculous for web servers to essentially have to ask
// “please do not violate the privacy of the people who are viewing
// this site” with every request.
// For more info, see: https://plausible.io/blog/google-floc
this.app.use((request, response, next) => {
response.set('Permissions-Policy', 'interest-cohort=()')
next()
})
// Add any custom middleware from a .middleware folder
// supplied by the person (if any).
this.appAddCustomMiddleware()
// Statistics middleware (captures anonymous, ephemeral statistics).
this.app.use(this.stats.middleware)
// Logging.
this.app.use(morgan((tokens, req, res) => {
const status = tokens.status(req, res) || '?'
const isError = status.startsWith('4') || status.startsWith('5')
if (process.env.QUIET || this.accessLogDisable || (this.accessLogErrorsOnly && !isError)) {
return
}
let hasWarning = false
let hasError = false
let method = tokens.method(req, res)
if (method === 'GET') method = '↓ GET'
if (method === 'POST') method = '↑ POST'
let durationWarning = ''
let duration = parseFloat(tokens['response-time'](req, res)).toFixed(1)
if (duration > 500) { durationWarning = ' !'}
if (duration > 1000) { durationWarning = ' !!'}
if (durationWarning !== '') {
hasWarning = true
}
duration = `${duration} ms${clr(durationWarning, 'yellow')}`
if (duration === 'NaN ms') {
//
// I’ve only encountered this once (in response to what seems to
// be a client-side issue with Firefox on Linux possibly related to
// server-sent events:
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1077089)
//
duration = ' - !'
hasError = true
}
let sizeWarning = ''
let size = (tokens.res(req, res, 'content-length')/1024).toFixed(1)
if (size > 500) { sizeWarning = ' !' }
if (size > 1000) { sizeWarning = ' !!'}
if (sizeWarning !== '') {
hasWarning = true
}
size = `${size} kb${clr(sizeWarning, 'yellow')}`
if (size === 'NaN kb') { size = ' - ' }
let url = tokens.url(req, res)
if (url.endsWith('.png') || url.endsWith('.jpg') || url.endsWith('.jpeg') || url.endsWith('.svg') || url.endsWith('.gif')) {
url = `🌌 ${url}`
} else if (url.endsWith('.ico')) {
url = `💠 ${url}`
}
else if (url.endsWith('.css')) {
url = `🎨 ${url}`
} else if (url.includes('.css?v=')) {
url = `✨ Live reload (CSS) ${url}`
} else if (url === '/instant/client/bundle.js') {
url = `⚡ Live reload script load`
} else if (url.endsWith('js')) {
url = `⚡ ${url}`
} else if (url === '/instant/events') {
url = `✨ Live reload`
} else {
url = `📄 ${url}`
}
const statusToTextColour = {
'304': 'cyan',
'200': 'green',
}
let textColour = statusToTextColour[status]
if (hasWarning) { textColour = 'yellow' }
if (hasError || isError) { textColour = 'red' }
const log = [
clr(method, textColour),
'\t',
clr(status, textColour),
'\t',
clr(duration, textColour),
'\t',
clr(size, textColour),
'\t',
clr(url, textColour),
].join(' ')
return ` 💞 ${log}`
}))
// Add domain aliases support (add 302 redirects for any domains
// defined as aliases so that the URL is rewritten). There is always
// at least one alias (the www. subdomain) for global servers.
if (this.global) {
const mainHostname = Site.hostname
this.app.use((request, response, next) => {
const requestedHost = request.header('host')
if (requestedHost === mainHostname) {
next()
} else {
this.log(` 👉 ❨site.js❩ Redirecting alias ${requestedHost} to main hostname ${mainHostname}.`)
response.redirect(`https://${mainHostname}${request.path}`)
}
})
}
// Inject an html() method into the response object as a handy utility
// for both setting the type of the response to HTML and ending it with
// the passed content. Let’s save some keystrokes. Over time, they can
// add up to whole lifetimes.
this.app.use((request, response, next) => {
(() => {
const self = response
response.html = content => {
self.type('html')
self.end(content)
}
})()
next()
})
// Statistics view (displays anonymous, ephemeral statistics)
this.app.get(this.stats.route, this.stats.view)
}
// Auto detect and support hugo source directories if they exist.
async addHugoSupport() {
if (this.syncHost !== undefined) {
// If about to sync to a remote host, delete the .generated folder so that a full
// generation can happen as we’re about to deploy.
const generatedContentPath = path.join(this.absolutePathToServe, '.generated')
fs.removeSync(generatedContentPath)
}
// Hugo source folder names must begin with either
// .hugo or .hugo--. Anything after the first double-dash
// specifies a custom mount path (double dashes are converted
// to forward slashes when determining the mount path).
const hugoSourceFolderPrefixRegExp = /^.hugo(--)?/
const files = fs.readdirSync(this.absolutePathToServe)
for (const file of files) {
if (file.match(hugoSourceFolderPrefixRegExp)) {
const hugoSourceDirectory = path.join(this.absolutePathToServe, file)
let mountPath = '/'
// Check for custom mount path naming convention.
if (hugoSourceDirectory.includes('--')) {
// Double dashes are translated into forward slashes.
const fragments = hugoSourceDirectory.split('--')
// Discard the first '.hugo' bit.
fragments.shift()
const _mountPath = fragments.reduce((accumulator, currentValue) => {
return accumulator += `/${currentValue}`
}, /* initial value = */ '')
mountPath = _mountPath
}
if (fs.existsSync(hugoSourceDirectory)) {
const serverDetails = clr(`${file}${path.sep}`, 'green') + clr(' → ', 'cyan') + clr(`https://${this.prettyLocation()}${mountPath}`, 'green')
this.log(` 🎠 ❨site.js❩ Starting Hugo server (${serverDetails})`)
if (this.hugo === null || this.hugo === undefined) {
this.hugo = new Hugo(path.join(Site.settingsDirectory, 'node-hugo'))
}
const sourcePath = path.join(this.pathToServe, file)
const destinationPath = `../.generated${mountPath}`
const localBaseURL = `https://localhost${this.port === 443 ? '' : `:${this.port}`}${mountPath}`
const globalBaseURL = `https://${Site.hostname}${mountPath}`
let baseURL = this.global ? globalBaseURL : localBaseURL
// If a syncHost is provided (because we are about to sync), that overrides the calculated base
// URL as we are generating the content not for localhost or the current machine’s hostname but
// for the remote machine’s host name.
let buildDrafts = true
if (this.syncHost !== undefined) {
baseURL = `https://${this.syncHost}`
// Also, if syncing to a remote host, do NOT build drafts as we do not want to publish drafts.
buildDrafts = false
}
// Start the server and await the end of the build process.
let hugoServerProcess, hugoBuildOutput
try {
const response = await this.hugo.serve(sourcePath, destinationPath, baseURL, buildDrafts)
hugoServerProcess = response.hugoServerProcess
hugoBuildOutput = response.hugoBuildOutput
} catch (error) {
let errorMessage = error
if (errorMessage.includes('--appendPort=false not supported when in multihost mode')) {
errorMessage = 'Hugo’s Multilingual Multihost mode is not supported in Site.js.'
}
this.log(`\n ❌ ${clr('❨site.js❩ Error:', 'red')} Could not start Hugo server. ${errorMessage}\n`)
process.exit(1)
}
// At this point, the build process is complete and the .generated folder should exist.
// Listen for standard output and error output on the server instance.
hugoServerProcess.stdout.on('data', (data) => {
const lines = data.toString('utf-8').split('\n')
lines.forEach(line => this.log(`${Site.HUGO_LOGO} ${line}`))
})
hugoServerProcess.stderr.on('data', (data) => {
const lines = data.toString('utf-8').split('\n')
lines.forEach(line => {
this.log(`${Site.HUGO_LOGO} [ERROR] ${line}`)
if (line.includes('panic: runtime error: index out of range [1] with length 1')) {
this.log('\n 📎 ❨site.js❩ Looks like you configured Multilingual Multihost mode in Hugo. This is not supported.\n')
}
})
})
// Save a reference to all hugo server processes so we can
// close them later and perform other cleanup.
if (this.hugoServerProcesses === null || this.hugoServerProcesses === undefined) {
this.hugoServerProcesses = []
}
this.hugoServerProcesses.push(hugoServerProcess)
// Print the output received so far.
hugoBuildOutput.split('\n').forEach(line => {
this.log(`${Site.HUGO_LOGO} ${line}`)
})
}
}
}
}
// Middleware and routes that are unique to regular sites
// (not used on proxy servers).
async configureAppRoutes () {
let statusOfPathToServe
try {
statusOfPathToServe = fs.statSync(this.absolutePathToServe)
} catch (error) {
if (error.code === 'ENOENT') {
throw new errors.InvalidPathToServeError(`Path ${clr(this.pathToServe, 'yellow')} does not exist.`)
} else {
throw new errors.InvalidPathToServeError('Unexpected file system error', error)
}
}
if (statusOfPathToServe.isFile()) {
throw new errors.InvalidPathToServeError(`${clr(this.pathToServe, 'yellow')} is a file. Site.js can only serve directories.`)
}
// Async
await this.addHugoSupport()
// Continue configuring the rest of the app routes.
this.add4042302Support()
this.addCustomErrorPagesSupport()
// Add routes
this.appAddTest500ErrorPage()
this.appAddDynamicRoutes()
this.appAddStaticRoutes()
this.appAddWildcardRoutes()
this.appAddArchivalCascade()
}
// Middleware unique to proxy servers.
// TODO: Refactor: Break this method up. []
configureProxyRoutes () {
const proxyHttpUrl = `http://localhost:${this.proxyPort}`
const proxyWebSocketUrl = `ws://localhost:${this.proxyPort}`
let prettyLog = function (message) {
const match = /^\[HPM\] Proxy created: \/ -> (ws|http):\/\/localhost:(\d+)$/.exec(message)
if (match === null) {
// Regular messages.
this.log(` 🔁 ❨site.js❩ Proxy: ${message}`)
} else {
// Proxy created message. Log after improving it for clarity.
const [proxyType, proxyProtocol] = match[1] === 'ws' ? ['WebSocket', 'wss'] : ['HTTP', 'https']
const proxyPort = match[2]
this.log(` 🔁 ❨site.js❩ ${clr(`${proxyType} proxy`, 'green')} set up for port ${clr(proxyPort, 'cyan')} at ${clr(`${proxyProtocol}://localhost`, 'cyan')}.`)
}
}
prettyLog = prettyLog.bind(this)
const logProvider = function(provider) {
return { log: prettyLog, debug: prettyLog, info: prettyLog, warn: prettyLog, error: prettyLog }
}
const webSocketProxy = createProxyMiddleware({
target: proxyWebSocketUrl,
ws: true,
changeOrigin:false,
logProvider,
logLevel: 'info'
})
const httpsProxy = createProxyMiddleware({
target: proxyHttpUrl,
logProvider,
logLevel: 'info',
})
this.app.use(httpsProxy)
this.app.use(webSocketProxy)
this.httpsProxy = httpsProxy
this.webSocketProxy = webSocketProxy
}
// Creates a web socket server.
createWebSocketServer () {
expressWebSocket(this.app, this.server, { perMessageDeflate: false })
}
// Create the server. Use this first to create the server and add the routes later
// so that you can support asynchronous tasks (e.g., generating a Hugo site).
createServer () {
// Check for a valid port range
// (port above 49,151 are ephemeral ports. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Dynamic,_private_or_ephemeral_ports)
if (this.port < 0 || this.port > 49151) {
throw new Error('Error: specified port must be between 0 and 49,151 inclusive.')
}
// Create the server.
this.server = this._createServer({global: this.global}, this.app)
// Enable the ability to destroy the server (close all active connections).
enableDestroy(this.server)
this.server.on('close', async () => {
// Clear the auto update check interval.
if (this.autoUpdateCheckInterval !== undefined) {
clearInterval(this.autoUpdateCheckInterval)
this.log(' ⏰ ❨site.js❩ Cleared auto-update check interval.')
}
if (this.app.__fileWatcher !== undefined) {
try {
await this.app.__fileWatcher.close()
this.log (` 🚮 ❨site.js❩ Removed file watcher.`)
} catch (error) {
this.log(` ❌ ❨site.js❩ Could not remove file watcher: ${error}`)
}
}
// Ensure that the static route file watchers are removed.
if (this.app.__staticRoutes !== undefined) {
await new Promise((resolve, reject) => {
this.app.__staticRoutes.cleanUp(() => {
this.log(' 🚮 ❨site.js❩ Live reload file system watchers removed from static web routes on server close.')
resolve()
})
})
}
if (globalThis._db) {
this.log(' 🚮 ❨site.js❩ Closing database.')
await globalThis._db.close()
}
delete globalThis.db
this.log(' 🚮 ❨site.js❩ Housekeeping is done!')
this.eventEmitter.emit('housekeepingIsDone')
})
}
// Finish configuring the app. These are the routes that come at the end.
// (We need to add the WebSocket (WSS) routes after the server has been created).
endAppConfiguration () {
// Create the file watcher to watch for changes on dynamic and wildcard routes.
if (!this.isProxyServer) {
this.createFileWatcher()
this.createWebSocketServer()
}
// If we need to load dynamic routes from a routesJS file, do it now.
if (this.routesJsFile !== undefined) {
const routesJSFilePath = path.resolve(this.routesJsFile)
decache(routesJSFilePath)
require(routesJSFilePath)(this.app)
}
// If there are WebSocket routes, create a regular WebSocket server and
// add the WebSocket routes (if any) to the app.
if (this.wssRoutes !== undefined) {
this.wssRoutes.forEach(route => {
this.log(` 🐁 ❨site.js❩ Adding WebSocket (WSS) route: ${route.path}`)
decache(route.callback)
this.app.ws(route.path, require(route.callback))
})
}
// The error routes go at the very end.
//
// 404 (Not Found) support.
//
this.app.use((request, response, next) => {
// If a 4042302 (404 → 302) redirect has been requested, honour that.
// (See https://4042302.org/). Otherwise, if there is a custom 404 error page,
// serve that. (The template variable THE_PATH, if present on the page, will be
// replaced with the current request path before it is returned.)
if (this.has4042302) {
const forwardingURL = `${this._4042302}${request.url}`
this.log(` ♻ ❨site.js❩ 404 → 302: Forwarding to ${forwardingURL}`)
response.redirect(forwardingURL)
} else if (this.hasCustom404) {
// Enable basic template support for including the missing path.
const custom404WithPath = this.custom404.replace('THE_PATH', request.path)
// Enable relative links to work in custom error pages.
const custom404WithPathAndBase = custom404WithPath.replace('<head>', '<head>\n\t<base href="/404/">')
response.status(404).send(custom404WithPathAndBase)
} else {
// Send default 404 page.
response.status(404).send(Site.default404ErrorPage(request.path))
}
})
//
// 500 (Server error) support.
//
this.app.use((error, request, response, next) => {
// Strip the Error: prefix from the message.
const errorMessage = error.toString().replace('Error: ', '')
// If there is a custom 500 path, serve that. The template variable
// THE_ERROR, if present on the page, will be replaced with the error description.
if (this.hasCustom500) {
// Enable basic template support for including the error message.
const custom500WithErrorMessage = this.custom500.replace('THE_ERROR', errorMessage)
// Enable relative links to work in custom error pages.
const custom500WithErrorMessageAndBase = custom500WithErrorMessage.replace('<head>', '<head>\n\t<base href="/500/">')
response.status(500).send(custom500WithErrorMessageAndBase)
} else {
// Send default 500 page.
response.status(500).send(Site.default500ErrorPage(errorMessage))
}
})
}
initialiseStatistics () {
const statisticsRouteSettingFile = path.join(Site.settingsDirectory, 'statistics-route')
return new Stats(statisticsRouteSettingFile)
}
// Returns an https server instance configured with your locally-trusted TLS
// certificates by default. If you pass in {global: true} in the options object,
// globally-trusted TLS certificates are obtained from Let’s Encrypt.
//
// Note: if you pass in a key and cert in the options object, they will not be
// ===== used and will be overwritten.
_createServer (options = {}, requestListener = undefined) {
const requestsGlobalCertificateScope = options.global === true
if (requestsGlobalCertificateScope) {
this.log(' 🌍 ❨site.js❩ Using globally-trusted certificates.')
// Let’s be nice and not continue to pollute the options object
// with our custom property (global).
delete options.global
// Certificates are automatically obtained for the hostname and the www. subdomain of the hostname
// for the machine that we are running on.
let domains = [Site.hostname]
// If additional aliases have been specified, add those to the domains list.
domains = domains.concat(this.aliases)
options.domains = domains
// Display aliases we’re responding to.
if (this.aliases.length > 0) {
const listOfAliases = this.aliases.reduce((prev, current) => {
return `${prev}${current}, `
}, '').slice(0, -2)
this.log(` 👉 ❨site.js❩ Aliases: also responding for ${listOfAliases}.`)
} else {
this.log(` 👉 ❨site.js❩ No aliases. Only responding for ${Site.hostname}.`)
}
} else {
this.log(' 🚧 ❨site.js❩ Using locally-trusted certificates.')
}
// Specify custom certificate directory for Site.js.
options.settingsPath = path.join(Util.unprivilegedHomeDirectory(), '.small-tech.org', 'site.js', 'tls')
// Create and return the HTTPS server.
return https.createServer(options, requestListener)
}
// There is no use in starting a server if the domains it will be serving on are not reachable.
// If we do, this can lead to all sorts of pain later on. Much better to inform the person early on
// that there is a problem with the domain (possibly a typo or a DNS issue) and to go no further.
async ensureDomainsAreReachable () {
// Note: spacing around this emoji is correct. It requires less than the others.
this.log(' 🧚♀️ ❨site.js❩ Ensuring domains are reachable before starting global server.')
const reachabilityMessage = 'site.js-domain-is-reachable'
const preFlightCheckServer = http.createServer((request, response) => {
response.statusCode = 200
response.end(reachabilityMessage)
})
await new Promise((resolve, reject) => {
try {
preFlightCheckServer.listen(80, () => {
this.log(' ✨ ❨site.js❩ Pre-flight domain reachability check server started.')
resolve()
})
} catch (error) {
this.log(`\n ❌ ${clr('❨site.js❩ Error:', 'red')} Pre-flight domain reachability server could not be started.\n`)
process.exit(1)
}
})
const domainsToCheck = [Site.hostname].concat(this.aliases)
await asyncForEach(
domainsToCheck,
async domain => {
try {
this.log (` ✨ ❨site.js❩ Attempting to reach domain ${domain}…`)
const domainCheck = prepareRequest('GET', 'string', `http://${domain}`)
const response = await domainCheck()
if (response !== reachabilityMessage) {
// If this happens, there is most likely another site running at this domain.
// We cannot continue.
let responseToShow = response.length > 100 ? 'response is too long to show' : response
if (response.includes('html')) {
responseToShow = `${responseToShow.replace('is', 'looks like HTML and is')}`
}
this.log(`\n ❌ ${clr('❨site.js❩ Error:', 'red')} Got unexpected response from ${domain} (${responseToShow}).\n`)
process.exit(1)
}
this.log (` 💖 ❨site.js❩ ${domain} is reachable.`)
} catch (error) {
// The site is not reachable. We cannot continue.
this.log(`\n ❌ ${clr('❨site.js❩ Error:', 'red')} Domain ${domain} is not reachable. (${error.toString().replace(/Error.*?: /, '')})\n`)
process.exit(1)
}
}
)
await new Promise((resolve, reject) => {
preFlightCheckServer.close(() => {
resolve()
}, error => {
this.log(`\n ❌ ${clr('❨site.js❩ Error:', 'red')} Could not close the pre-flight domain reachability server.\n`)
process.exit(1)
})
})
this.log(' ✨ ❨site.js❩ Pre-flight domain reachability check server stopped.')
}
// Starts serving the site (or starts the proxy server).
// • callback: (function) the callback to call once the server is ready (defaults are provided).
//
// Can throw.
async serve (callback) {
// Before anything else, if this is a global server, let’s ensure that the domains we are trying to support
// are reachable. If it is not, we will be prevented from going any further.
// Note: this feature can be disabled by specifying the --skip-domain-reachability-check flag.
if (this.global) {
if (this.skipDomainReachabilityCheck !== true) {
await this.ensureDomainsAreReachable()
} else {
this.log('\n 🐇 ❨site.js❩ Skipping domain reachability check as requested.')
}
}
// If a JavaScript Database (JSDB) database exists for the current app, load it in right now (since this is a
// relatively slow process, we want it to happen at server start, not while the server is up and running and during
// a request.). If a database doesn’t already exist, we don’t want to pollute the project directory with a database
// directory unnecessarily so we create a global property accessor to instantiates a database instance on first
// attempt to access it.