forked from bokwoon95/notebrew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notebrew.go
1590 lines (1492 loc) · 46.2 KB
/
notebrew.go
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
package notebrew
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"embed"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"html/template"
"io"
"io/fs"
"log/slog"
"mime"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/bokwoon95/notebrew/sq"
"github.com/bokwoon95/notebrew/stacktrace"
"github.com/caddyserver/certmagic"
"github.com/libdns/libdns"
"github.com/oschwald/maxminddb-golang"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/text"
"go.uber.org/zap"
"golang.org/x/crypto/blake2b"
)
// Notebrew represents a notebrew instance.
type Notebrew struct {
// FS is the file system associated with the notebrew instance.
FS FS
// DB is the DB associated with the notebrew instance.
DB *sql.DB
// Dialect is Dialect of the database. Only sqlite, postgres and mysql
// databases are supported.
Dialect string
// ErrorCode translates a database error into an dialect-specific error
// code. If the error is not a database error or if no underlying
// implementation is provided, ErrorCode should return an empty string.
ErrorCode func(error) string
// CMSDomain is the domain that the notebrew is using to serve the CMS.
// Examples: localhost:6444, notebrew.com
CMSDomain string
// CMSDomainHTTPS indicates whether the CMS domain is currently being
// served over HTTPS.
CMSDomainHTTPS bool
// ContentDomain is the domain that the notebrew instance is using to serve
// the static generated content. Examples: localhost:6444, nbrew.net.
ContentDomain string
// ContentDomainHTTPS indicates whether the content domain is currently
// being served over HTTPS.
ContentDomainHTTPS bool
// CDNDomain is the domain of the CDN that notebrew is using to host its
// images. Examples: cdn.nbrew.net, nbrewcdn.net.
CDNDomain string
// ImgCmd is the command (must reside in $PATH) used to preprocess images
// for the web before they are saved to the FS. Images in the notes folder
// are never prerpocessed and are uploaded as-is. This serves as an a
// escape hatch for users who wish to upload their images without any image
// preprocessing, as they can upload images to the notes folder first
// before moving it elsewhere.
//
// ImgCmd should take in arguments in the form of `<ImgCmd> $INPUT_PATH
// $OUTPUT_PATH`, where $INPUT_PATH is the input path to the raw image and
// $OUTPUT_PATH is output path where ImgCmd should save the preprocessed
// image.
ImgCmd string
// (Required) Port is port that notebrew is listening on.
Port int
// IP4 is the IPv4 address of the current machine, if notebrew is currently
// serving either port 80 (HTTP) or 443 (HTTPS).
IP4 netip.Addr
// IP6 is the IPv6 address of the current machine, if notebrew is currently
// serving either port 80 (HTTP) or 443 (HTTPS).
IP6 netip.Addr
// Domains is the list of domains that need to point at notebrew for it to
// work. Does not include user-created domains.
Domains []string
// ManagingDomains is the list of domains that the current instance of
// notebrew is managing SSL certificates for.
ManagingDomains []string
// Captcha configuration.
CaptchaConfig struct {
// Captcha widget's script src. e.g. https://js.hcaptcha.com/1/api.js,
// https://challenges.cloudflare.com/turnstile/v0/api.js
WidgetScriptSrc template.URL
// Captcha widget's container div class. e.g. h-captcha, cf-turnstile
WidgetClass string
// Captcha verification URL to make POST requests to. e.g.
// https://api.hcaptcha.com/siteverify,
// https://challenges.cloudflare.com/turnstile/v0/siteverify
VerificationURL string
// Captcha response token name. e.g. h-captcha-response,
// cf-turnstile-response
ResponseTokenName string
// Captcha site key.
SiteKey string
// Captcha secret key.
SecretKey string
// CSP contains the Content-Security-Policy directive names and values
// required for the captcha widget to work.
CSP map[string]string
}
// Mailer is used to send out transactional emails e.g. password reset
// emails.
Mailer *Mailer
// The default value for the SMTP MAIL FROM instruction.
MailFrom string
// The default value for the SMTP Reply-To header.
ReplyTo string
// Proxy configuration.
ProxyConfig struct {
// RealIPHeaders contains trusted IP addresses to HTTP headers that
// they are known to populate the real client IP with. e.g. X-Real-IP,
// True-Client-IP.
RealIPHeaders map[netip.Addr]string
// Contains the set of trusted proxy IP addresses. This is used when
// resolving the real client IP from the X-Forwarded-For HTTP header
// chain from right (most trusted) to left (most accurate).
ProxyIPs map[netip.Addr]struct{}
}
// DNS provider (required for using wildcard certificates with
// LetsEncrypt).
DNSProvider interface {
libdns.RecordAppender
libdns.RecordDeleter
libdns.RecordGetter
libdns.RecordSetter
}
// CertStorage is the magic (certmagic) that automatically provisions SSL
// certificates for notebrew.
CertStorage certmagic.Storage
// CertLogger is the logger used for a certmagic.Config.
CertLogger *zap.Logger
// ContentSecurityPolicy is the Content-Security-Policy HTTP header set for
// every HTML response served on the CMS domain.
ContentSecurityPolicy string
// Logger is used for reporting errors that cannot be handled and are
// thrown away.
Logger *slog.Logger
// MaxMindDBReader is the maxmind database reader used to reolve IP
// addresses to their countries using a maxmind GeoIP database.
MaxMindDBReader *maxminddb.Reader
// baseCtx is the base context of the notebrew instance.
baseCtx context.Context
// baseCtxCancel cancels the base context.
baseCtxCancel func()
// baseCtxWaitGroup tracks the number of background jobs spawned by the
// notebrew instance. Each background job should take in the base context,
// and should should initiate shutdown when the base context is canceled.
baseCtxWaitGroup sync.WaitGroup
}
// New returns a new instance of Notebrew. Each field within it still needs to
// be manually configured.
func New() *Notebrew {
populateExts()
baseCtx, baseCtxCancel := context.WithCancel(context.Background())
nbrew := &Notebrew{
baseCtx: baseCtx,
baseCtxCancel: baseCtxCancel,
}
return nbrew
}
// Close shuts down the notebrew instance as well as any background jobs it may
// have spawned.
func (nbrew *Notebrew) Close() error {
nbrew.baseCtxCancel()
defer nbrew.baseCtxWaitGroup.Wait()
if nbrew.DB != nil {
if nbrew.Dialect == "sqlite" {
nbrew.DB.Exec("PRAGMA optimize")
}
}
databaseFS, ok := &DatabaseFS{}, false
switch v := nbrew.FS.(type) {
case interface{ As(any) bool }:
ok = v.As(&databaseFS)
}
if ok {
if databaseFS.Dialect == "sqlite" {
databaseFS.DB.Exec("PRAGMA optimize")
}
}
return nil
}
// User represents a user in the users table.
type User struct {
// UserID uniquely identifies a user. It cannot be changed.
UserID ID
// Username uniquely identifies a user. It can be changed.
Username string
// Email uniquely identifies a user. It can be changed.
Email string
// TimezoneOffsetSeconds represents a user's preferred timezone offset in
// seconds.
TimezoneOffsetSeconds int
// Is not empty, DisableReason is the reason why the user's account is
// marked as disabled.
DisableReason string
// SiteLimit is the limit on the number of sites the user can create.
SiteLimit int64
// StorageLimit is the limit on the amount of storage the user can use.
StorageLimit int64
// UserFlags are various properties on a user that may be enabled or
// disabled e.g. UploadImages.
UserFlags map[string]bool
}
type contextKey struct{}
// LoggerKey is the key used by notebrew for setting and getting a logger from
// the request context.
var LoggerKey = &contextKey{}
// GetLogger is a syntactic sugar operation for getting a request-specific
// logger from the context, or else it returns the default logger.
func (nbrew *Notebrew) GetLogger(ctx context.Context) *slog.Logger {
if logger, ok := ctx.Value(LoggerKey).(*slog.Logger); ok {
return logger
}
return nbrew.Logger
}
// SetFlashSession writes a value into the user's flash session.
func (nbrew *Notebrew) SetFlashSession(w http.ResponseWriter, r *http.Request, value any) error {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
encoder := json.NewEncoder(buf)
encoder.SetEscapeHTML(false)
err := encoder.Encode(&value)
if err != nil {
return stacktrace.New(err)
}
cookie := &http.Cookie{
Path: "/",
Name: "flash",
Secure: r.TLS != nil,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
if developerMode {
os.Stderr.WriteString(buf.String())
}
if nbrew.DB == nil {
cookie.Value = base64.URLEncoding.EncodeToString(buf.Bytes())
} else {
var flashTokenBytes [8 + 16]byte
binary.BigEndian.PutUint64(flashTokenBytes[:8], uint64(time.Now().Unix()))
_, err := rand.Read(flashTokenBytes[8:])
if err != nil {
return stacktrace.New(err)
}
var flashTokenHash [8 + blake2b.Size256]byte
checksum := blake2b.Sum256(flashTokenBytes[8:])
copy(flashTokenHash[:8], flashTokenBytes[:8])
copy(flashTokenHash[8:], checksum[:])
_, err = sq.Exec(r.Context(), nbrew.DB, sq.Query{
Dialect: nbrew.Dialect,
Format: "INSERT INTO flash (flash_token_hash, data) VALUES ({flashTokenHash}, {data})",
Values: []any{
sq.BytesParam("flashTokenHash", flashTokenHash[:]),
sq.StringParam("data", strings.TrimSpace(buf.String())),
},
})
if err != nil {
return stacktrace.New(err)
}
cookie.Value = strings.TrimLeft(hex.EncodeToString(flashTokenBytes[:]), "0")
}
http.SetCookie(w, cookie)
return nil
}
// GetFlashSession retrieves a value from the user's flash session, unmarshals
// it into the valuePtr and then deletes the session. It returns a boolean
// result indicating if a flash session was retrieved.
func (nbrew *Notebrew) GetFlashSession(w http.ResponseWriter, r *http.Request, valuePtr any) (ok bool, err error) {
cookie, _ := r.Cookie("flash")
if cookie == nil {
return false, nil
}
http.SetCookie(w, &http.Cookie{
Path: "/",
Name: "flash",
Value: "0",
MaxAge: -1,
Secure: r.TLS != nil,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
var data []byte
if nbrew.DB == nil {
data, err = base64.URLEncoding.DecodeString(cookie.Value)
if err != nil {
return false, nil
}
} else {
flashToken, err := hex.DecodeString(fmt.Sprintf("%048s", cookie.Value))
if err != nil {
return false, nil
}
creationTime := time.Unix(int64(binary.BigEndian.Uint64(flashToken[:8])), 0).UTC()
if time.Now().Sub(creationTime) > 5*time.Minute {
return false, nil
}
var flashTokenHash [8 + blake2b.Size256]byte
checksum := blake2b.Sum256(flashToken[8:])
copy(flashTokenHash[:8], flashToken[:8])
copy(flashTokenHash[8:], checksum[:])
switch nbrew.Dialect {
case "sqlite", "postgres":
data, err = sq.FetchOne(r.Context(), nbrew.DB, sq.Query{
Dialect: nbrew.Dialect,
Format: "DELETE FROM flash WHERE flash_token_hash = {flashTokenHash} RETURNING {*}",
Values: []any{
sq.BytesParam("flashTokenHash", flashTokenHash[:]),
},
}, func(row *sq.Row) []byte {
return row.Bytes(nil, "data")
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, stacktrace.New(err)
}
default:
data, err = sq.FetchOne(r.Context(), nbrew.DB, sq.Query{
Dialect: nbrew.Dialect,
Format: "SELECT {*} FROM flash WHERE flash_token_hash = {flashTokenHash}",
Values: []any{
sq.BytesParam("flashTokenHash", flashTokenHash[:]),
},
}, func(row *sq.Row) []byte {
return row.Bytes(nil, "data")
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, stacktrace.New(err)
}
_, err = sq.Exec(r.Context(), nbrew.DB, sq.Query{
Dialect: nbrew.Dialect,
Format: "DELETE FROM flash WHERE flash_token_hash = {flashTokenHash}",
Values: []any{
sq.BytesParam("flashTokenHash", flashTokenHash[:]),
},
})
if err != nil {
return false, stacktrace.New(err)
}
}
}
decoder := json.NewDecoder(bytes.NewReader(data))
err = decoder.Decode(valuePtr)
if err != nil {
return true, stacktrace.New(err)
}
return true, nil
}
// urlReplacer escapes special characters in a URL for http.Redirect.
var urlReplacer = strings.NewReplacer("#", "%23", "%", "%25")
// Crockford Base32 encoding.
var base32Encoding = base32.NewEncoding("0123456789abcdefghjkmnpqrstvwxyz").WithPadding(base32.NoPadding)
// markdownTextOnly takes in a markdown snippet and extracts the text only,
// removing any markup.
func markdownTextOnly(parser parser.Parser, src []byte) string {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
var node ast.Node
nodes := []ast.Node{
parser.Parse(text.NewReader(src)),
}
for len(nodes) > 0 {
node, nodes = nodes[len(nodes)-1], nodes[:len(nodes)-1]
switch node := node.(type) {
case nil:
continue
case *ast.Image, *ast.CodeBlock, *ast.FencedCodeBlock, *ast.HTMLBlock:
nodes = append(nodes, node.NextSibling())
case *ast.Text:
buf.Write(node.Text(src))
nodes = append(nodes, node.NextSibling(), node.FirstChild())
default:
nodes = append(nodes, node.NextSibling(), node.FirstChild())
}
}
// Manually escape backslashes (goldmark may be able to do this,
// investigate).
var b strings.Builder
b.Grow(buf.Len())
output := buf.Bytes()
// Jump to the location of each backslash found in the output.
for i := bytes.IndexByte(output, '\\'); i >= 0; i = bytes.IndexByte(output, '\\') {
b.Write(output[:i])
char, width := utf8.DecodeRune(output[i+1:])
if char != utf8.RuneError {
b.WriteRune(char)
}
output = output[i+1+width:]
}
b.Write(output)
return b.String()
}
// isURLUnsafe is a rune-to-bool mapping indicating if a rune is unsafe for
// URLs.
var isURLUnsafe = [...]bool{
' ': true, '!': true, '"': true, '#': true, '$': true, '%': true, '&': true, '\'': true,
'(': true, ')': true, '*': true, '+': true, ',': true, '/': true, ':': true, ';': true,
'<': true, '>': true, '=': true, '?': true, '[': true, ']': true, '\\': true, '^': true,
'`': true, '{': true, '}': true, '|': true, '~': true,
}
// urlSafe sanitizes a string to make it url-safe by removing any url-unsafe
// characters.
func urlSafe(s string) string {
s = strings.TrimSpace(s)
var count int
var b strings.Builder
b.Grow(len(s))
for _, char := range s {
if count >= 80 {
break
}
if char == ' ' {
b.WriteRune('-')
count++
continue
}
if char == '-' || (char >= '0' && char <= '9') || (char >= 'a' && char <= 'z') {
b.WriteRune(char)
count++
continue
}
if char >= 'A' && char <= 'Z' {
b.WriteRune(unicode.ToLower(char))
count++
continue
}
n := int(char)
if n < len(isURLUnsafe) && isURLUnsafe[n] {
continue
}
b.WriteRune(char)
count++
}
return strings.Trim(b.String(), ".")
}
// filenameReplacementChars is a map of filename-unsafe runes to their
// filename-safe replacements. Reference: https://stackoverflow.com/a/31976060.
var filenameReplacementChars = [...]rune{
'<': '<', // U+FF1C, FULLWIDTH LESS-THAN SIGN
'>': '>', // U+FF1E, FULLWIDTH GREATER-THAN SIGN
':': '꞉', // U+A789, MODIFIER LETTER COLON
'"': '″', // U+2033, DOUBLE PRIME
'/': '/', // U+FF0F, FULLWIDTH SOLIDUS
'\\': '\', // U+FF3C, FULLWIDTH REVERSE SOLIDUS
'|': '│', // U+2502, BOX DRAWINGS LIGHT VERTICAL
'?': '?', // U+FF1F, FULLWIDTH QUESTION MARK
'*': '∗', // U+2217, ASTERISK OPERATOR
// NOTE: Hex is technically not filename-unsafe, but is does not get
// properly escaped in URLs because it gets mistaken as the fragment
// identifier so we need to replace it too.
'#': '#', // U+FF03, FULLWIDTH NUMBER SIGN
}
// filenameSafe makes a string safe for use in filenames by replacing any
// filename-unsafe characters to their filename-safe equivalents.
func filenameSafe(s string) string {
s = strings.TrimSpace(s)
var b strings.Builder
b.Grow(len(s))
for _, char := range s {
if char >= 0 && char <= 31 {
continue
}
n := int(char)
if n >= len(filenameReplacementChars) {
b.WriteRune(char)
continue
}
replacementChar := filenameReplacementChars[n]
if replacementChar == 0 {
b.WriteRune(char)
continue
}
b.WriteRune(replacementChar)
}
return strings.Trim(b.String(), ".")
}
var hashPool = sync.Pool{
New: func() any {
hash, err := blake2b.New256(nil)
if err != nil {
panic(err)
}
return hash
},
}
var readerPool = sync.Pool{
New: func() any {
return bufio.NewReaderSize(nil, 512)
},
}
// ExecuteTemplate renders a given template with the given data into the
// ResponseWriter, but it first buffers the HTML output so that it can detect
// if any template errors occurred, and if so return 500 Internal Server Error
// instead. Additionally, it does on-the-fly gzipping of the HTML response as
// well as calculating the ETag so that the HTML may be cached by the client.
func (nbrew *Notebrew) ExecuteTemplate(w http.ResponseWriter, r *http.Request, tmpl *template.Template, data any) {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
hasher := hashPool.Get().(hash.Hash)
defer func() {
hasher.Reset()
hashPool.Put(hasher)
}()
multiWriter := io.MultiWriter(buf, hasher)
gzipWriter := gzipWriterPool.Get().(*gzip.Writer)
gzipWriter.Reset(multiWriter)
defer func() {
gzipWriter.Reset(io.Discard)
gzipWriterPool.Put(gzipWriter)
}()
err := tmpl.Execute(gzipWriter, data)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
fmt.Printf(fmt.Sprintf("%#v", data))
nbrew.InternalServerError(w, r, err)
return
}
err = gzipWriter.Close()
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
var b [blake2b.Size256]byte
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("ETag", `"`+hex.EncodeToString(hasher.Sum(b[:0]))+`"`)
http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(buf.Bytes()))
}
// ContentBaseURL returns the content site's base URL (starting with http:// or
// https://) for a given site prefix.
func (nbrew *Notebrew) ContentBaseURL(sitePrefix string) string {
if strings.Contains(sitePrefix, ".") {
return "https://" + sitePrefix
}
if nbrew.CMSDomain == "localhost" || strings.HasPrefix(nbrew.CMSDomain, "localhost:") {
if sitePrefix != "" {
return "http://" + strings.TrimPrefix(sitePrefix, "@") + "." + nbrew.CMSDomain
}
return "http://" + nbrew.CMSDomain
}
if sitePrefix != "" {
return "https://" + strings.TrimPrefix(sitePrefix, "@") + "." + nbrew.ContentDomain
}
return "https://" + nbrew.ContentDomain
}
// GetReferer is like (*http.Request).Referer() except it returns an empty
// string if the referer is the same as the current page's URL so that the user
// doesn't keep pressing back to the same page.
func (nbrew *Notebrew) GetReferer(r *http.Request) string {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer
//
// "The Referer header can contain an origin, path, and querystring, and
// may not contain URL fragments (i.e. #section) or username:password
// information."
referer := r.Referer()
uri := *r.URL
if r.TLS == nil {
uri.Scheme = "http"
} else {
uri.Scheme = "https"
}
uri.Host = r.Host
uri.Fragment = ""
uri.User = nil
if referer == uri.String() {
return ""
}
return referer
}
// errorTemplate is the template used for all error responses i.e.
// InternalServerError, NotFound, NotAuthorized, etc. It is parsed once at
// package initialization time so any changes to the error template require
// recompiling the notebrew binary.
var errorTemplate = template.Must(template.
New("error.html").
Funcs(map[string]any{
"safeHTML": func(v any) template.HTML {
if str, ok := v.(string); ok {
return template.HTML(str)
}
return ""
},
}).
ParseFS(RuntimeFS, "embed/error.html"),
)
// HumanReadableFileSize returns a human readable file size of an int64 size in
// bytes.
func HumanReadableFileSize(size int64) string {
// https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/
if size < 0 {
return ""
}
const unit = 1000
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "kMGTPE"[exp])
}
// BadRequest indicates that something was wrong with the request data.
func (nbrew *Notebrew) BadRequest(w http.ResponseWriter, r *http.Request, serverErr error) {
var message string
var maxBytesErr *http.MaxBytesError
if errors.As(serverErr, &maxBytesErr) {
message = "payload is too big (max " + HumanReadableFileSize(maxBytesErr.Limit) + ")"
} else {
contentType, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
if contentType == "application/json" {
if serverErr == io.EOF {
message = "missing JSON body"
} else if serverErr == io.ErrUnexpectedEOF {
message = "malformed JSON"
} else {
message = serverErr.Error()
}
} else {
message = serverErr.Error()
}
}
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
if r.Method == "HEAD" {
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(map[string]any{
"error": "BadRequest",
"message": message,
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
err := errorTemplate.Execute(buf, map[string]any{
"Title": `400 bad request`,
"Headline": "400 bad request",
"Byline": message,
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
http.Error(w, "BadRequest: "+message, http.StatusBadRequest)
return
}
w.Header().Set("Content-Security-Policy", nbrew.ContentSecurityPolicy)
w.WriteHeader(http.StatusBadRequest)
if r.Method == "HEAD" {
return
}
buf.WriteTo(w)
}
// NotAuthenticated indicates that the user is not logged in.
func (nbrew *Notebrew) NotAuthenticated(w http.ResponseWriter, r *http.Request) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusUnauthorized)
if r.Method == "HEAD" {
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(map[string]any{
"error": "NotAuthenticated",
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
var query string
if r.Method == "GET" {
if r.URL.RawQuery != "" {
query = "?redirect=" + url.QueryEscape(r.URL.Path+"?"+r.URL.RawQuery)
} else {
query = "?redirect=" + url.QueryEscape(r.URL.Path)
}
}
err := errorTemplate.Execute(buf, map[string]any{
"Title": "401 unauthorized",
"Headline": "401 unauthorized",
"Byline": fmt.Sprintf("You are not authenticated, please <a href='/users/login/%s'>log in</a>.", query),
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
http.Error(w, "NotAuthenticated", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Security-Policy", nbrew.ContentSecurityPolicy)
w.WriteHeader(http.StatusUnauthorized)
if r.Method == "HEAD" {
return
}
buf.WriteTo(w)
}
// NotAuthorized indicates that the user is logged in, but is not authorized to
// view the current page or perform the current action.
func (nbrew *Notebrew) NotAuthorized(w http.ResponseWriter, r *http.Request) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusForbidden)
if r.Method == "HEAD" {
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(map[string]any{
"error": "NotAuthorized",
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
var byline string
if r.Method == "GET" || r.Method == "HEAD" {
byline = "You do not have permission to view this page (try logging in to a different account)."
} else {
byline = "You do not have permission to perform that action (try logging in to a different account)."
}
err := errorTemplate.Execute(buf, map[string]any{
"Referer": nbrew.GetReferer(r),
"Title": "403 forbidden",
"Headline": "403 forbidden",
"Byline": byline,
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
http.Error(w, "NotAuthorized", http.StatusForbidden)
return
}
w.Header().Set("Content-Security-Policy", nbrew.ContentSecurityPolicy)
w.WriteHeader(http.StatusForbidden)
if r.Method == "HEAD" {
return
}
buf.WriteTo(w)
}
// NotFound indicates that a URL does not exist.
func (nbrew *Notebrew) NotFound(w http.ResponseWriter, r *http.Request) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
if r.Method == "HEAD" {
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(map[string]any{
"error": "NotFound",
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
err := errorTemplate.Execute(buf, map[string]any{
"Referer": nbrew.GetReferer(r),
"Title": "404 not found",
"Headline": "404 not found",
"Byline": "The page you are looking for does not exist.",
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
http.Error(w, "NotFound", http.StatusNotFound)
return
}
w.Header().Set("Content-Security-Policy", nbrew.ContentSecurityPolicy)
w.WriteHeader(http.StatusNotFound)
if r.Method == "HEAD" {
return
}
buf.WriteTo(w)
}
// MethodNotAllowed indicates that the request method is not allowed.
func (nbrew *Notebrew) MethodNotAllowed(w http.ResponseWriter, r *http.Request) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
if r.Method == "HEAD" {
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(map[string]any{
"error": "MethodNotAllowed",
"method": r.Method,
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
if buf.Cap() <= maxPoolableBufferCapacity {
buf.Reset()
bufPool.Put(buf)
}
}()
err := errorTemplate.Execute(buf, map[string]any{
"Referer": nbrew.GetReferer(r),
"Title": "405 method not allowed",
"Headline": "405 method not allowed: " + r.Method,
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
http.Error(w, "NotFound", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Security-Policy", nbrew.ContentSecurityPolicy)
w.WriteHeader(http.StatusMethodNotAllowed)
if r.Method == "HEAD" {
return
}
buf.WriteTo(w)
}
// UnsupportedContentType indicates that the request did not send a supported
// Content-Type.
func (nbrew *Notebrew) UnsupportedContentType(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
var message string
if contentType == "" {
message = "missing Content-Type"
} else {
message = "unsupported Content-Type: " + contentType
}
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusUnsupportedMediaType)
if r.Method == "HEAD" {
return
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(map[string]any{
"error": "UnsupportedMediaType",
"message": message,
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return