summaryrefslogtreecommitdiffstats
path: root/roseh.moe.go
blob: 3a53208f2c64b535f97b1d3ce06acb3c71527e9c (plain) (blame)
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
package main

import (
	"context"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"embed"
	"encoding/base64"
	"encoding/binary"
	"flag"
	"fmt"
	"html/template"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"

	"roseh.moe/pkg/ccl"
	"roseh.moe/pkg/roseh.moe/internal/pwhash"
	"roseh.moe/pkg/wordlist"
)

var (
	port        = flag.Int("port", 42069, "port to listen on")
	selfURL     = flag.String("self-url", "http://localhost:42069", "base URL of the server")
	secretsFile = flag.String("secrets", "secrets.ccl", "secrets file")
	configFile  = flag.String("config", "config.ccl", "configuration file (ccl format https://pkg.go.dev/roseh.moe/pkg/ccl)")

	serverStartTime = time.Now()
)

var notepadPassword, secretKey []byte

func loadSecrets() error {
	fileBytes, err := os.ReadFile(*secretsFile)
	if err != nil {
		return err
	}
	var secretsConfig struct {
		NotepadPassword []byte
		SecretKey       []byte
	}
	if err := ccl.Unmarshal(fileBytes, &secretsConfig); err != nil {
		return fmt.Errorf("%s: %s", *secretsFile, err)
	}
	if len(secretsConfig.NotepadPassword) == 0 {
		return fmt.Errorf("%s: missing notepad-password", *secretsFile)
	}
	if len(secretsConfig.SecretKey) == 0 {
		return fmt.Errorf("%s: missing secret-key", *secretsFile)
	}
	notepadPassword = secretsConfig.NotepadPassword
	secretKey = secretsConfig.SecretKey
	return nil
}

type serviceConfiguration struct {
	packageRedirects map[string]string
	commandRedirects map[string]string
}

var (
	serviceConfigMu           sync.Mutex
	serviceConfig             *serviceConfiguration
	serviceConfigLastModified time.Time
)

func loadConfig() (*serviceConfiguration, error) {
	stat, err := os.Stat(*configFile)
	if err != nil {
		return nil, err
	}
	serviceConfigMu.Lock()
	oldConfig := serviceConfig
	configLastModified := serviceConfigLastModified
	serviceConfigMu.Unlock()
	newModTime := stat.ModTime()
	if !newModTime.After(configLastModified) {
		return oldConfig, nil
	}
	log.Printf("Reloading config file...")
	fileBytes, err := os.ReadFile(*configFile)
	if err != nil {
		return nil, err
	}
	var fileConfig struct {
		Redirect []struct{ Package, Command, To string }
	}
	if err := ccl.Unmarshal(fileBytes, &fileConfig); err != nil {
		return nil, err
	}
	config := &serviceConfiguration{
		packageRedirects: make(map[string]string),
		commandRedirects: make(map[string]string),
	}
	for _, redirect := range fileConfig.Redirect {
		if redirect.Package != "" {
			config.packageRedirects[redirect.Package] = redirect.To
		} else {
			config.commandRedirects[redirect.Command] = redirect.To
		}
	}
	serviceConfigMu.Lock()
	serviceConfig = config
	serviceConfigLastModified = newModTime
	serviceConfigMu.Unlock()
	return config, nil
}

var (
	//go:embed templates/404.html.template
	notFoundString   string
	notFoundTemplate = template.Must(template.New("notFound").Parse(notFoundString))
)

func notFound(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	type args struct {
		Path string
	}
	if err := notFoundTemplate.Execute(w, args{Path: r.URL.Path}); err != nil {
		log.Printf("Warning: notFound: %s", err)
	}
}

var (
	//go:embed templates/outline.html.template
	outlineString   string
	outlineTemplate = template.Must(template.New("outline").Parse(outlineString))

	//go:embed templates/index.html.template
	indexString   string
	indexTemplate = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(indexString)).Lookup("outline")
)

func index(w http.ResponseWriter, _ *http.Request) {
	if err := indexTemplate.Execute(w, nil); err != nil {
		log.Printf("Warning: index: %s", err)
	}
}

var (
	//go:embed templates/pong.html.template
	pongString   string
	pongTemplate = template.Must(template.New("pong").Parse(pongString))
)

func pong(w http.ResponseWriter, _ *http.Request) {
	if err := pongTemplate.Execute(w, nil); err != nil {
		log.Printf("Warning: pong: %s", err)
	}
}

//go:embed static
var staticFiles embed.FS

func serveStaticFile(w http.ResponseWriter, r *http.Request, path string) {
	f, err := staticFiles.Open(path)
	if err != nil {
		notFound(w, r)
		return
	}
	defer f.Close()
	http.ServeContent(w, r, path, serverStartTime, f.(io.ReadSeeker))
}

func static(w http.ResponseWriter, r *http.Request) {
	serveStaticFile(w, r, strings.TrimPrefix(r.URL.Path, "/"))
}

func favicon(w http.ResponseWriter, r *http.Request) {
	serveStaticFile(w, r, "static/favicon.ico")
}

var (
	//go:embed templates/wormhole.html.template
	wormholeTemplateString string
	wormholeTemplate       = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(wormholeTemplateString)).Lookup("outline")
)

type wormholeTemplateArgs struct {
	Self string
	Hole string
}

func makeHole() string {
	const nWords = 10
	buf := make([]byte, 2*nWords)
	rand.Read(buf)
	words := make([]string, nWords)
	for i := range words {
		words[i] = wordlist.Words[binary.NativeEndian.Uint16(buf[2*i:])&0x1fff]
	}
	return strings.Join(words, "-")
}

func newWormhole(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/wormhole/"+makeHole()+"/upload", http.StatusSeeOther)
}

func wormhole(w http.ResponseWriter, r *http.Request) {
	if err := wormholeTemplate.Execute(w, wormholeTemplateArgs{Self: *selfURL, Hole: r.PathValue("hole")}); err != nil {
		log.Printf("Warning: wormhole: %s", err)
	}
}

type wormholeConn struct {
	done chan struct{}
	r    *multipart.Part
	w    http.ResponseWriter
}

var wormholeConnsMu sync.Mutex
var wormholeConns = make(map[string]wormholeConn)

func (c wormholeConn) wormholeCopy(ctx context.Context, hole string) error {
	wormholeConnsMu.Lock()
	prevConn, ok := wormholeConns[hole]
	if !ok {
		wormholeConns[hole] = c
		wormholeConnsMu.Unlock()
		defer func() {
			wormholeConnsMu.Lock()
			delete(wormholeConns, hole)
			wormholeConnsMu.Unlock()
		}()
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-c.done:
			return nil
		}
	}
	wormholeConnsMu.Unlock()
	defer close(prevConn.done)
	if c.w == nil {
		c.w = prevConn.w
	} else {
		c.r = prevConn.r
	}
	c.w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+c.r.FileName())
	if _, err := io.Copy(c.w, c.r); err != nil {
		return fmt.Errorf("copy: %s", err)
	}
	return nil
}

func wormholeSend(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	reader, err := r.MultipartReader()
	if err != nil {
		http.Error(w, fmt.Sprintf("Not a multipart/form-data request: %s", err), http.StatusBadRequest)
		return
	}
	for {
		part, err := reader.NextPart()
		if err != nil {
			break
		}
		if part.FormName() != "file" {
			continue
		}
		hole := r.PathValue("hole")
		if err := (wormholeConn{done: make(chan struct{}), r: part}).wormholeCopy(ctx, hole); err != nil {
			http.Error(w, fmt.Sprintf("Error during copy: %s", err), http.StatusServiceUnavailable)
		}
		fmt.Fprintf(w, "uploaded!")
		return
	}
	http.Error(w, "file not found", http.StatusBadRequest)
}

func wormholeRecv(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	hole := r.PathValue("hole")
	if err := (wormholeConn{done: make(chan struct{}), w: w}).wormholeCopy(ctx, hole); err != nil {
		http.Error(w, fmt.Sprintf("Error during copy: %s", err), http.StatusServiceUnavailable)
	}
}

func mac(msg []byte) []byte {
	mac := hmac.New(sha256.New, secretKey)
	mac.Write(msg)
	return mac.Sum(nil)
}

func sign(msg []byte) []byte {
	return append(msg, mac(msg)...)
}

func verify(msg []byte) ([]byte, bool) {
	if len(msg) < sha256.Size {
		return nil, false
	}
	msg, messageMAC := msg[:len(msg)-sha256.Size], msg[len(msg)-sha256.Size:]
	expectedMAC := mac(msg)
	if !hmac.Equal(messageMAC, expectedMAC) {
		return nil, false
	}
	return msg, true
}

func makeToken() (string, error) {
	b, err := time.Now().MarshalBinary()
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(sign(b)), nil
}

const cookieExpiration = 180 * 24 * time.Hour

func attachCookie(w http.ResponseWriter) error {
	token, err := makeToken()
	if err != nil {
		return err
	}
	http.SetCookie(w, &http.Cookie{
		Name:        "auth",
		Value:       token,
		Path:        "/",
		Expires:     time.Now().Add(cookieExpiration),
		Secure:      true,
		HttpOnly:    true,
		SameSite:    http.SameSiteStrictMode,
		Partitioned: true,
	})
	return nil
}

func cookieAuth(w http.ResponseWriter, r *http.Request) (string, bool) {
	const csrfTokenLen = 32
	var csrfToken string
	if csrfCookie, err := r.Cookie("csrf-token"); err == nil {
		csrfToken = csrfCookie.Value
	} else {
		buf := make([]byte, csrfTokenLen)
		rand.Read(buf)
		csrfToken = base64.RawURLEncoding.EncodeToString(buf)
		http.SetCookie(w, &http.Cookie{
			Name:        "csrf-token",
			Value:       csrfToken,
			Path:        "/",
			Secure:      true,
			HttpOnly:    true,
			SameSite:    http.SameSiteStrictMode,
			Partitioned: true,
		})
	}

	cookie, err := r.Cookie("auth")
	if err != nil {
		return csrfToken, false
	}
	authCookie, err := base64.RawURLEncoding.DecodeString(cookie.Value)
	if err != nil {
		return csrfToken, false
	}
	msg, ok := verify(authCookie)
	if !ok {
		return csrfToken, false
	}
	var t time.Time
	if err := t.UnmarshalBinary(msg); err != nil {
		return csrfToken, false
	}
	cookieAge := time.Since(t)
	if cookieAge > cookieExpiration {
		return csrfToken, false
	}
	if cookieAge > 24*time.Hour {
		attachCookie(w)
	}
	return csrfToken, true
}

func checkCSRFToken(r *http.Request) error {
	cookie, err := r.Cookie("csrf-token")
	if err != nil {
		return err
	}
	cookieHash := sha256.Sum256([]byte(cookie.Value))
	formValueHash := sha256.Sum256([]byte(r.FormValue("csrf-token")))
	if subtle.ConstantTimeCompare(cookieHash[:], formValueHash[:]) == 0 {
		return fmt.Errorf("bad CSRF token")
	}
	return nil
}

func checkPassword(password string) bool {
	expectedHash, salt := notepadPassword[:len(notepadPassword)-pwhash.SaltSize], notepadPassword[len(notepadPassword)-pwhash.SaltSize:]
	hash, err := pwhash.Hash(password, salt)
	return err == nil && subtle.ConstantTimeCompare(hash, expectedHash) != 0
}

var (
	//go:embed templates/login.html.template
	loginTemplateString string
	loginTemplate       = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(loginTemplateString)).Lookup("outline")
)

type loginTemplateArgs struct {
	CSRFToken string
	Error     bool
}

func executeLoginTemplate(w io.Writer, csrfToken string) {
	if err := loginTemplate.Execute(w, loginTemplateArgs{CSRFToken: csrfToken}); err != nil {
		log.Printf("Warning: login: %s", err)
	}
}

func login(w http.ResponseWriter, r *http.Request) {
	if err := checkCSRFToken(r); err != nil {
		http.Error(w, "bad CSRF token", http.StatusBadRequest)
		return
	}
	if !checkPassword(r.FormValue("password")) {
		if err := loginTemplate.Execute(w, loginTemplateArgs{
			Error:     true,
			CSRFToken: r.FormValue("csrf-token"),
		}); err != nil {
			log.Printf("Warning: login: %s", err)
		}
		return
	}
	attachCookie(w)
	http.Redirect(w, r, "/notepad", http.StatusSeeOther)
}

var (
	//go:embed templates/note.html.template
	notepadString   string
	notepadTemplate = template.Must(template.Must(outlineTemplate.Clone()).New("body").Parse(notepadString)).Lookup("outline")

	notepadContentsMu sync.Mutex
	notepadContents   string
)

type notepadTemplateArgs struct {
	Content   string
	CSRFToken string
}

func notepad(w http.ResponseWriter, r *http.Request) {
	csrfToken, ok := cookieAuth(w, r)
	if !ok {
		executeLoginTemplate(w, csrfToken)
		return
	}
	notepadContentsMu.Lock()
	currentContent := notepadContents
	notepadContentsMu.Unlock()
	if err := notepadTemplate.Execute(w, notepadTemplateArgs{Content: currentContent, CSRFToken: csrfToken}); err != nil {
		log.Printf("Warning: notepad: %s", err)
	}
}

func saveNote(w http.ResponseWriter, r *http.Request) error {
	if err := checkCSRFToken(r); err != nil {
		return err
	}
	if _, ok := cookieAuth(w, r); !ok {
		return fmt.Errorf("not logged in")
	}
	newContent := r.FormValue("content")
	notepadContentsMu.Lock()
	notepadContents = newContent
	notepadContentsMu.Unlock()
	return nil
}

func autosave(w http.ResponseWriter, r *http.Request) {
	msg := "Saved ✓"
	if err := saveNote(w, r); err != nil {
		msg = fmt.Sprintf("Failed to save: %s", err)
	}
	if err := notepadTemplate.ExecuteTemplate(w, "saveIndicator", msg); err != nil {
		log.Printf("Warning: autosave: %s", err)
	}
}

func cmd(w http.ResponseWriter, r *http.Request) {
	serviceConfig, err := loadConfig()
	if err != nil {
		http.Error(w, fmt.Sprintf("load config: %s", err), http.StatusInternalServerError)
		return
	}
	source, ok := serviceConfig.commandRedirects[r.PathValue("cmd")]
	if !ok {
		notFound(w, r)
		return
	}
	if r.FormValue("go-get") == "1" {
		fmt.Fprintf(w, `<meta name="go-import" content="roseh.moe/cmd/%s %s">`, r.PathValue("cmd"), source)
	} else {
		http.Redirect(w, r, "https://pkg.go.dev/roseh.moe/cmd/"+r.PathValue("cmd"), http.StatusFound)
	}
}

func pkg(w http.ResponseWriter, r *http.Request) {
	serviceConfig, err := loadConfig()
	if err != nil {
		http.Error(w, fmt.Sprintf("load config: %s", err), http.StatusInternalServerError)
		return
	}
	source, ok := serviceConfig.packageRedirects[r.PathValue("pkg")]
	if !ok {
		notFound(w, r)
		return
	}
	if r.FormValue("go-get") == "1" {
		fmt.Fprintf(w, `<meta name="go-import" content="roseh.moe/pkg/%s %s">`, r.PathValue("pkg"), source)
	} else {
		http.Redirect(w, r, "https://pkg.go.dev/roseh.moe/pkg/"+r.PathValue("pkg"), http.StatusFound)
	}
}

func main() {
	flag.Parse()

	if err := loadSecrets(); err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("GET /pong", pong)
	http.HandleFunc("GET /wormhole", newWormhole)
	http.HandleFunc("GET /wormhole/{hole}/upload", wormhole)
	http.HandleFunc("POST /wormhole/{hole}/upload", wormholeSend)
	http.HandleFunc("GET /wormhole/{hole}", wormholeRecv)
	http.HandleFunc("POST /login", login)
	http.HandleFunc("GET /notepad", notepad)
	http.HandleFunc("POST /notepad", autosave)
	http.HandleFunc("GET /cmd/{cmd}", cmd)
	http.HandleFunc("GET /pkg/{pkg}", pkg)
	http.HandleFunc("GET /static/", static)
	http.HandleFunc("GET /favicon.ico", favicon)
	http.HandleFunc("GET /{$}", index)
	http.HandleFunc("GET /", notFound)

	addr := fmt.Sprintf(":%d", *port)
	log.Printf("Listening on %q", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}