-
Notifications
You must be signed in to change notification settings - Fork 18
/
main.go
19097 lines (16636 loc) · 537 KB
/
main.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 main
import (
"bytes"
"cmp"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"database/sql"
"embed"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
"html"
"html/template"
"io"
"io/fs"
"log"
"math/big"
mathRand "math/rand"
"mime"
"net"
"net/http"
"net/mail"
"net/smtp"
"net/url"
"os"
"os/signal"
"path"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"syscall"
textTemplate "text/template"
"time"
"github.com/caddyserver/certmagic"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/mattn/go-sqlite3"
"github.com/mholt/acmez/acme"
"github.com/miekg/dns"
"golang.org/x/crypto/bcrypt"
"golang.org/x/mod/semver"
"gopkg.in/yaml.v3"
)
var BUILD = "dev"
var CA = certmagic.LetsEncryptStagingCA
var VERSION = "v0.3.0"
//go:embed schema.sql
var sqlSchema string
const SELF_SIGNED_CERT_NAME = "self-signed-cert.pem"
const SELF_SIGNED_KEY_NAME = "self-signed-key.pem"
func Migration1715019045AddSlugColumns(tx *sql.Tx) error {
requiresSlug := map[string]string{
"old__service": "service",
"old__monitor": "monitor",
"old__notification_channel": "notification_channel",
"old__mail_group": "mail_group",
}
for k, v := range requiresSlug {
err := copyNonSlugToSlugTable(tx, k, v)
if err != nil {
return fmt.Errorf("Migration1715019045AddSlugColumns.copyNonSlugToSlugTable"+k+": %w", err)
}
}
copy := map[string]string{
"old__alert_service": "alert_service",
"old__monitor_log": "monitor_log",
"old__monitor_log_last_checked": "monitor_log_last_checked",
"old__monitor_notification_channel": "monitor_notification_channel",
"old__alert_setting_smtp_notification": "alert_setting_smtp_notification",
"old__mail_group_member": "mail_group_member",
"old__mail_group_monitor": "mail_group_monitor",
}
for src, dst := range copy {
err := copyTable(tx, src, dst)
if err != nil {
return fmt.Errorf("Migration1715019045AddSlugColumns.copyTable"+src+": %w", err)
}
}
dropTablesQuery := ""
for k := range copy {
dropTablesQuery += "drop table " + k + "; "
}
for k := range requiresSlug {
dropTablesQuery += "drop table " + k + "; "
}
_, err := tx.Exec(dropTablesQuery)
if err != nil {
return fmt.Errorf("Migration1715019045AddSlugColumns.ExecDropTables: %w", err)
}
return nil
}
func initDB(immediate bool) *sql.DB {
if _, err := os.Stat("statusnook-data"); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir("statusnook-data", os.ModePerm)
if err != nil {
log.Fatalf("initDB.Mkdir: %s", err)
}
}
dsn := "file:statusnook-data/app.db?_foreign_keys=on&_journal_mode=wal"
if immediate {
dsn += "&_txlock=immediate"
}
db, err := sql.Open("sqlite3", dsn)
if err != nil {
log.Fatalf("initDB.Open: %s", err)
}
if immediate {
files, err := migrationsFS.ReadDir("migrations")
if err != nil {
log.Fatalf("initDB.ReadDir: %s", err)
}
slices.SortFunc(files, func(a, b fs.DirEntry) int {
return cmp.Compare(a.Name(), b.Name())
})
const tableCountQuery = `
select
count(*)
from
sqlite_schema
where
type = 'table' and
name not like 'sqlite_%';
`
tableCount := 0
row := db.QueryRow(tableCountQuery)
err = row.Scan(&tableCount)
if err != nil {
log.Fatalf("initDB.ScanTableCount: %s", err)
}
if tableCount == 0 {
tx, err := db.Begin()
if err != nil {
log.Fatalf("initDB.BeginExecSchema: %s", err)
}
defer tx.Rollback()
_, err = tx.Exec(sqlSchema)
if err != nil {
log.Fatalf("initDB.ExecSchema: %s", err)
}
params := []any{}
placeholders := ""
for i, v := range files {
placeholders += "(?, ?)"
if i < len(files)-1 {
placeholders += ", "
}
params = append(params, strings.TrimRight(v.Name(), ".sql"), true)
}
insertMigrationQuery := fmt.Sprintf(
`insert into migration(name, skipped) values %s;`,
placeholders,
)
_, err = tx.Exec(insertMigrationQuery, params...)
if err != nil {
log.Fatalf("initDB.ExecInsertMigration: %s", err)
}
err = tx.Commit()
if err != nil {
log.Fatalf("initDB.CommitExecSchema: %s", err)
}
} else {
const createMigrationTableQuery = `
create table if not exists migration(
id integer primary key,
name text not null unique,
skipped int not null
);
`
_, err := db.Exec(createMigrationTableQuery)
if err != nil {
log.Fatalf("initDB.ExecCreateMigrationTable: %s", err)
}
existingMigrations := map[string]bool{}
rows, err := db.Query("select name from migration")
if err != nil {
log.Fatalf("initDB.ExecQueryMigrations: %s", err)
}
defer rows.Close()
for rows.Next() {
var name string
err = rows.Scan(&name)
if err != nil {
log.Fatalf("initDB.ScanMigration: %s", err)
}
existingMigrations[name] = true
}
for _, file := range files {
migrationName := strings.TrimRight(file.Name(), ".sql")
if _, ok := existingMigrations[migrationName]; ok {
continue
}
data, err := migrationsFS.ReadFile(path.Join("migrations", file.Name()))
if err != nil {
log.Fatalf("initDB.ReadFile %s: %s", file.Name(), err)
}
func() {
tx, err := db.Begin()
if err != nil {
log.Fatalf("initDB.BeginMigration %s: %s", file.Name(), err)
}
defer tx.Rollback()
_, err = tx.Exec(string(data))
if err != nil {
log.Fatalf("initDB.ExecMigration %s: %s", file.Name(), err)
}
if file.Name() == "1715019045_add_slug_columns.sql" {
err = Migration1715019045AddSlugColumns(tx)
if err != nil {
log.Fatalf("initDB.Migration1715019045AddSlugColumns %s: %s", file.Name(), err)
}
}
insertMigrationQuery := fmt.Sprintf(
`insert into migration(name, skipped) values ('%s', false)`,
migrationName,
)
_, err = tx.Exec(insertMigrationQuery)
if err != nil {
log.Fatalf("initDB.ExecInsertMigrationSkip %s: %s", file.Name(), err)
}
err = tx.Commit()
if err != nil {
log.Fatalf("initDB.CommitMigration %s: %s", file.Name(), err)
}
if file.Name() == "1715019045_add_slug_columns.sql" {
_, err = db.Exec("vacuum")
if err != nil {
log.Printf("initDB.Migration1715019045AddSlugColumnsExecVacuum: %s", err)
}
}
}()
}
}
}
return db
}
func copyTable(tx *sql.Tx, src string, dst string) error {
cols := []string{}
rows, err := tx.Query("select name from pragma_table_info('" + src + "')")
if err != nil {
return fmt.Errorf("copyTable.Query: %w", err)
}
defer rows.Close()
for rows.Next() {
col := ""
err := rows.Scan(&col)
if err != nil {
return fmt.Errorf("copyTable.Scan: %w", err)
}
cols = append(cols, col)
}
query := fmt.Sprintf(`
insert into
%s (
%s
)
select
%s
from
%s
`,
dst,
strings.Join(cols, ", "),
strings.Join(cols, ", "),
src,
)
_, err = tx.Exec(query)
if err != nil {
return fmt.Errorf("copyTable.Exec: %w", err)
}
return nil
}
func copyNonSlugToSlugTable(tx *sql.Tx, src string, dst string) error {
srcCols := []string{}
rows, err := tx.Query("select name from pragma_table_info('" + src + "')")
if err != nil {
return fmt.Errorf("copyNonSlugToSlugTable.Query: %w", err)
}
defer rows.Close()
for rows.Next() {
col := ""
err := rows.Scan(&col)
if err != nil {
return fmt.Errorf("copyNonSlugToSlugTable.ScanTableInfo: %w", err)
}
srcCols = append(srcCols, col)
}
dstCols := append(append([]string{}, "id", "slug"), srcCols[1:]...)
srcColsPlusSlug := append(
append([]string{}, "id", "(select slug from t where id = "+src+".id)"),
srcCols[1:]...,
)
var count int
err = tx.QueryRow(
`select count(*) from ` + src,
).Scan(&count)
if err != nil {
return fmt.Errorf("copyNonSlugToSlugTable.ScanCount: %w", err)
}
if count == 0 {
return nil
}
cteQuery, params, err := generateSlugBackfillCte(tx, src)
if err != nil {
return fmt.Errorf("copyNonSlugToSlugTable.generateSlugBackfillCte: %w", err)
}
query := fmt.Sprintf(`
%s
insert into
%s (
%s
)
select
%s
from
%s;
`,
cteQuery,
dst,
strings.Join(dstCols, ", "),
strings.Join(srcColsPlusSlug, ", "),
src,
)
_, err = tx.Exec(query, params...)
if err != nil {
return fmt.Errorf("copyNonSlugToSlugTable.Exec: %w", err)
}
return nil
}
func generateSlugBackfillCte(tx *sql.Tx, tableName string) (string, []any, error) {
pattern := regexp.MustCompile(`[^\p{L}\d]+`)
query := "select id, name from " + tableName + " order by id asc"
rows, err := tx.Query(query)
if err != nil {
return "", []any{}, fmt.Errorf("generateSlugBackfillCte.Query: %w", err)
}
defer rows.Close()
idToName := map[int]string{}
slugToId := map[string]int{}
sortedIds := []int{}
for rows.Next() {
var id int
var name string
err := rows.Scan(&id, &name)
if err != nil {
return "", []any{}, fmt.Errorf("generateSlugBackfillCte.Scan: %w", err)
}
idToName[id] = name
sortedIds = append(sortedIds, id)
}
if len(idToName) == 0 {
return "", []any{}, nil
}
slices.Sort(sortedIds)
for _, id := range sortedIds {
attempt := 0
for {
slug := strings.Trim(pattern.ReplaceAllString(strings.ToLower(idToName[id]), "-"), "-")
if slug == "" {
slug = strconv.Itoa(attempt)
} else if attempt > 0 {
slug += "-" + strconv.Itoa(attempt)
}
attempt++
_, ok := slugToId[slug]
if !ok {
slugToId[slug] = id
break
}
}
}
if len(slugToId) == 0 {
return "", []any{}, nil
}
updateQuery := `
with t(slug, id) as(values
`
params := []any{}
i := 0
for slug, id := range slugToId {
updateQuery += "(?, ?)"
params = append(params, slug, id)
if i < len(slugToId)-1 {
updateQuery += ","
}
i++
}
updateQuery += ")"
return updateQuery, params, nil
}
var tmpls = map[string]*template.Template{}
func parseTmpl(name string, markup string) (*template.Template, error) {
if tmpl, ok := tmpls[name]; ok {
return tmpl, nil
}
const rootTmpl = `
<!DOCTYPE html>
<html>
<head>
<title>{{template "title" .}}</title>
<link rel="stylesheet" href="/static/main.css">
<script type="text/javascript" src="/static/htmx-1.9.12.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body hx-history="false">
<div class="root">
<div class="page">
{{if .Ctx.Status}}
{{if and (not .Ctx.HideUnconfirmedDomain) (and .Ctx.Auth.ID .Ctx.UnconfirmedDomainProblem)}}
<div class="banner">
<span>
<span class="title">Action required</span>:
issues acquiring certificate for '{{.Ctx.UnconfirmedDomain}}'
</span>
<a href="/admin/settings" hx-boost="true">
click here for details
</a>
</div>
{{end}}
<div class="status-header">
<div>
<a id="nook-name" href="/" hx-boost="true">{{.Ctx.Name}}</a>
{{if .Ctx.AdminArea}}
<input id="nav-toggle" type="checkbox">
<label for="nav-toggle">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M2 4.75A.75.75 0 0 1 2.75 4h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 4.75ZM2 10a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75A.75.75 0 0 1 2 10Zm0 5.25a.75.75 0 0 1 .75-.75h14.5a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1-.75-.75Z" clip-rule="evenodd" />
</svg>
</label>
<div class="nav nav--mobile">
<a
href="/admin/alerts"
{{if eq .Ctx.Nav "alerts"}}class="active-nav"{{end}}
hx-boost="true"
>
Alerts
</a>
<a
href="/admin/monitors"
{{if eq .Ctx.Nav "monitors"}}class="active-nav"{{end}}
hx-boost="true"
>
Monitors
</a>
<a
href="/admin/services"
{{if eq .Ctx.Nav "services"}}class="active-nav"{{end}}
hx-boost="true"
>
Services
</a>
<a
href="/admin/notifications"
{{if eq .Ctx.Nav "notifications"}}class="active-nav"{{end}}
hx-boost="true"
>
Notifications
</a>
<a
href="/admin/settings"
{{if eq .Ctx.Nav "settings"}}class="active-nav"{{end}}
hx-boost="true"
>
Settings
</a>
<a
href="/admin/update"
{{if eq .Ctx.Nav "update"}}class="active-nav"{{end}}
hx-boost="true"
>
Update
</a>
<a hx-post="/logout">Log out</a>
</div>
{{end}}
</div>
{{if .Ctx.Index}}
<div>
<div class="get-updates-container">
{{if or .HasEmailAlertChannel .HasSlackSetup}}
<button class="get-updates">
<span>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path d="M3.105 2.288a.75.75 0 0 0-.826.95l1.414 4.926A1.5 1.5 0 0 0 5.135 9.25h6.115a.75.75 0 0 1 0 1.5H5.135a1.5 1.5 0 0 0-1.442 1.086l-1.414 4.926a.75.75 0 0 0 .826.95 28.897 28.897 0 0 0 15.293-7.155.75.75 0 0 0 0-1.114A28.897 28.897 0 0 0 3.105 2.288Z" />
</svg>
Get updates
</span>
<span></span>
</button>
{{end}}
<dialog>
{{if .HasEmailAlertChannel}}
<button onclick="document.querySelector('.email-updates-modal').showModal();">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5">
<path d="M3 4a2 2 0 0 0-2 2v1.161l8.441 4.221a1.25 1.25 0 0 0 1.118 0L19 7.162V6a2 2 0 0 0-2-2H3Z" />
<path d="m19 8.839-7.77 3.885a2.75 2.75 0 0 1-2.46 0L1 8.839V14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8.839Z" />
</svg>
Email
</button>
{{end}}
{{if and .HasEmailAlertChannel .HasSlackSetup}}
<hr>
{{end}}
{{if .HasSlackSetup}}
<a href="{{.HasSlackSetup}}" target="_blank">
<svg viewBox="0 0 124 124" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M26.3996 78.2003C26.3996 85.3003 20.5996 91.1003 13.4996 91.1003C6.39961 91.1003 0.599609 85.3003 0.599609 78.2003C0.599609 71.1003 6.39961 65.3003 13.4996 65.3003H26.3996V78.2003Z" fill="#E01E5A"/>
<path d="M32.9004 78.2003C32.9004 71.1003 38.7004 65.3003 45.8004 65.3003C52.9004 65.3003 58.7004 71.1003 58.7004 78.2003V110.5C58.7004 117.6 52.9004 123.4 45.8004 123.4C38.7004 123.4 32.9004 117.6 32.9004 110.5V78.2003Z" fill="#E01E5A"/>
<path d="M45.8004 26.4001C38.7004 26.4001 32.9004 20.6001 32.9004 13.5001C32.9004 6.4001 38.7004 0.600098 45.8004 0.600098C52.9004 0.600098 58.7004 6.4001 58.7004 13.5001V26.4001H45.8004Z" fill="#36C5F0"/>
<path d="M45.7996 32.8999C52.8996 32.8999 58.6996 38.6999 58.6996 45.7999C58.6996 52.8999 52.8996 58.6999 45.7996 58.6999H13.4996C6.39961 58.6999 0.599609 52.8999 0.599609 45.7999C0.599609 38.6999 6.39961 32.8999 13.4996 32.8999H45.7996Z" fill="#36C5F0"/>
<path d="M97.5996 45.7999C97.5996 38.6999 103.4 32.8999 110.5 32.8999C117.6 32.8999 123.4 38.6999 123.4 45.7999C123.4 52.8999 117.6 58.6999 110.5 58.6999H97.5996V45.7999Z" fill="#2EB67D"/>
<path d="M91.0988 45.8001C91.0988 52.9001 85.2988 58.7001 78.1988 58.7001C71.0988 58.7001 65.2988 52.9001 65.2988 45.8001V13.5001C65.2988 6.4001 71.0988 0.600098 78.1988 0.600098C85.2988 0.600098 91.0988 6.4001 91.0988 13.5001V45.8001Z" fill="#2EB67D"/>
<path d="M78.1988 97.6001C85.2988 97.6001 91.0988 103.4 91.0988 110.5C91.0988 117.6 85.2988 123.4 78.1988 123.4C71.0988 123.4 65.2988 117.6 65.2988 110.5V97.6001H78.1988Z" fill="#ECB22E"/>
<path d="M78.1988 91.1003C71.0988 91.1003 65.2988 85.3003 65.2988 78.2003C65.2988 71.1003 71.0988 65.3003 78.1988 65.3003H110.499C117.599 65.3003 123.399 71.1003 123.399 78.2003C123.399 85.3003 117.599 91.1003 110.499 91.1003H78.1988Z" fill="#ECB22E"/>
</svg>
Slack
</a>
{{end}}
</dialog>
</div>
{{if and .Ctx.Index .Ctx.Auth.ID}}
<a class="icon-button" href="/admin/alerts" hx-boost="true">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5">
<path fill-rule="evenodd" d="M2.5 3A1.5 1.5 0 001 4.5v4A1.5 1.5 0 002.5 10h6A1.5 1.5 0 0010 8.5v-4A1.5 1.5 0 008.5 3h-6zm11 2A1.5 1.5 0 0012 6.5v7a1.5 1.5 0 001.5 1.5h4a1.5 1.5 0 001.5-1.5v-7A1.5 1.5 0 0017.5 5h-4zm-10 7A1.5 1.5 0 002 13.5v2A1.5 1.5 0 003.5 17h6a1.5 1.5 0 001.5-1.5v-2A1.5 1.5 0 009.5 12h-6z" clip-rule="evenodd" />
</svg>
</a>
{{end}}
</div>
{{else if .Ctx.AdminArea}}
<div class="nav">
<a
href="/admin/alerts"
{{if eq .Ctx.Nav "alerts"}}class="active-nav"{{end}}
hx-boost="true"
>
Alerts
</a>
<a
href="/admin/monitors"
{{if eq .Ctx.Nav "monitors"}}class="active-nav"{{end}}
hx-boost="true"
>
Monitors
</a>
<a
href="/admin/services"
{{if eq .Ctx.Nav "services"}}class="active-nav"{{end}}
hx-boost="true"
>
Services
</a>
<a
href="/admin/notifications"
{{if eq .Ctx.Nav "notifications"}}class="active-nav"{{end}}
hx-boost="true"
>
Notifications
</a>
<div id="nav-menu" class="menu" hx-preserve>
<button class="menu-button">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" class="w-4 h-4">
<path fill-rule="evenodd" d="M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" />
</svg>
</button>
<dialog>
<a href="/admin/settings" hx-boost="true">Settings</a>
<a href="/admin/update" hx-boost="true">Update</a>
<a hx-post="/logout">Log out</a>
</dialog>
</div>
</div>
{{end}}
</div>
{{end}}
{{template "body" .}}
</div>
</div>
<script>
document.body.addEventListener("htmx:beforeSwap", function(evt) {
if (!evt.detail.shouldSwap) {
evt.detail.shouldSwap = evt.detail.xhr.status === 400;
}
});
document.body.addEventListener("htmx:configRequest", function(evt) {
evt.detail.headers["csrf-token"] = "{{.Ctx.Auth.CSRFToken}}";
});
function onClick(e) {
if (!e.target.classList.contains("menu-button")) {
[...document.querySelectorAll("dialog:not(.modal)")].forEach(e => {e.close();});
document.removeEventListener("click", onClick);
}
}
[...document.querySelectorAll(".menu-button")].forEach(function(e) {
const menu = e.closest(".menu");
if (menu.hasAttribute("hx-preserve")) {
if (menu.dataset.preserve) {
return;
}
menu.dataset.preserve = true;
}
e.addEventListener("click", function() {
const options = menu.querySelector("dialog");
if (!options.open) {
[...document.querySelectorAll("dialog:not(.modal)")].forEach(e => {e.close();});
options.show();
document.addEventListener("click", onClick);
} else {
options.close();
}
});
});
{{if .Ctx.ShouldAttemptRedirect}}
(async () => {
const getResolveResponse = await fetch(
"https://" + "{{.Ctx.Domain}}/resolve",
{method: "GET"}
);
if (!getResolveResponse.ok || !getResolveResponse.headers.get("X-Statusnook")) {
return;
}
const postResolveResponse = await fetch(
window.location.origin + "/admin/resolve",
{
method: "POST",
headers: {
"csrf-token": "{{.Ctx.Auth.CSRFToken}}"
}
}
);
if (!postResolveResponse.ok) {
return;
}
const token = await postResolveResponse.text();
const params = new URLSearchParams({
token,
after: window.location.pathname,
});
window.location.href =
"https://" + "{{.Ctx.Domain}}/cross-auth?" + params.toString();
})();
{{end}}
</script>
</body>
</html>
`
tmpl, err := template.New(name).Parse(rootTmpl)
if err != nil {
return tmpl, err
}
tmpl, err = tmpl.Parse(markup)
if err != nil {
return tmpl, err
}
tmpls[name] = tmpl
return tmpl, nil
}
var emailTmpls = map[string]*template.Template{}
func parseEmailTmpl(name string, markup string) (*template.Template, error) {
if tmpl, ok := emailTmpls[name]; ok {
return tmpl, nil
}
tmpl := template.New(name)
tmpl, err := tmpl.Parse(markup)
if err != nil {
return tmpl, fmt.Errorf("parseEmailTmpl.Parse: %w", err)
}
emailTmpls[name] = tmpl
return tmpl, nil
}
var textTmpls = map[string]*textTemplate.Template{}
func parseTextTmpl(name string, markup string) (*textTemplate.Template, error) {
if tmpl, ok := textTmpls[name]; ok {
return tmpl, nil
}
tmpl := textTemplate.New(name)
tmpl, err := tmpl.Parse(markup)
if err != nil {
return tmpl, fmt.Errorf("parseTextTmpl.Parse: %w", err)
}
textTmpls[name] = tmpl
return tmpl, nil
}
//go:embed static/*
var staticFS embed.FS
//go:embed migrations/*
var migrationsFS embed.FS
var appWg sync.WaitGroup
var db *sql.DB
var appCtx context.Context
var cancelAppCtx context.CancelFunc
var rwDB *sql.DB
var metaSetup string
var metaName string
var metaDomain string
var metaUnconfirmedDomain string
var metaUnconfirmedDomainProblem string
var metaSSL string
var metaConfigFileEnabled bool
type statusCtxKey struct{}
type pageCtx struct {
Status string
Auth authCtx
Index bool
Name string
HXRequest bool
HXBoosted bool
AdminArea bool
Nav string
UnconfirmedDomainProblem string
UnconfirmedDomain string
HideUnconfirmedDomain bool
ShouldAttemptRedirect bool
Domain string
ConfigFile bool
}
func getPageCtx(r *http.Request) pageCtx {
status := ""
if val, ok := r.Context().Value(statusCtxKey{}).(string); ok {
status = val
}
authCtx := getAuthCtx(r)
adminURLPrefix := ""
adminArea := false
if strings.HasPrefix(r.URL.Path, "/admin/") {
adminURLPrefix = strings.Split(r.URL.Path, "/")[2]
adminArea = true
}
parsedURL, _ := url.ParseRequestURI("https://" + r.Host)
return pageCtx{
Status: status,
Auth: authCtx,
Index: r.URL.Path == "/" || r.URL.Path == "/history",
Name: metaName,
HXRequest: r.Header.Get("HX-Request") == "true",
HXBoosted: r.Header.Get("HX-Boosted") == "true",
AdminArea: adminArea,
Nav: adminURLPrefix,
UnconfirmedDomainProblem: metaUnconfirmedDomainProblem,
UnconfirmedDomain: metaUnconfirmedDomain,
HideUnconfirmedDomain: r.URL.Path == "/admin/settings",
ShouldAttemptRedirect: metaSSL == "true" && authCtx.ID != 0 &&
metaDomain != "" && parsedURL.Hostname() != metaDomain,
Domain: metaDomain,
ConfigFile: metaConfigFileEnabled,
}
}
func csrfMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions {
h.ServeHTTP(w, r)
return
}
csrfToken := r.Header.Get("csrf-token")
authCtx := getAuthCtx(r)
if csrfToken != authCtx.CSRFToken {
w.WriteHeader(http.StatusForbidden)
return
}
h.ServeHTTP(w, r)
})
}
func statusMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tx, err := db.Begin()
if err != nil {
log.Printf("statusMiddleware.Begin: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
severity, err := getSeverity(tx)
if err != nil {
tx.Rollback()
log.Printf("statusMiddleware.getSeverity: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if err = tx.Commit(); err != nil {
log.Printf("statusMiddleware.Commit: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
ctx := context.WithValue(r.Context(), statusCtxKey{}, severity)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
type authCtxKey struct{}
type authCtx struct {
ID int
CSRFToken string
}
func getAuthCtx(r *http.Request) authCtx {
ctx := authCtx{}
if val, ok := r.Context().Value(authCtxKey{}).(authCtx); ok {
ctx = val
}
return ctx
}
func createMonitorLog(
tx *sql.Tx,
startedAt time.Time,
endedAt time.Time,
responseCode int64,
errorMessage sql.NullString,
attempts int,
result string,
monitorID int,
) (int, error) {
const query = `
insert into
monitor_log(started_at, ended_at, response_code, error_message,
attempts, result, monitor_id)
values(?, ?, ?, ?, ?, ?, ?)
returning id
`
var id int
err := tx.QueryRow(
query,
startedAt,
endedAt,
responseCode,
errorMessage,
attempts,
result,
monitorID,
).Scan(&id)
if err != nil {
return id, fmt.Errorf("createMonitorLog.Exec: %w", err)
}
return id, nil
}
func createMonitorLogLastChecked(
tx *sql.Tx,
startedAt time.Time,
monitorID int,
monitorLogID int,
) error {
const query = `