Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1359 lines (1305 loc) · 42.3 KB
/
Copy pathmain.go
File metadata and controls
1359 lines (1305 loc) · 42.3 KB
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 (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"database/sql"
"embed"
"encoding/base64"
"encoding/hex"
"errors"
"flag"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"mime"
"net"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/argon2"
_ "modernc.org/sqlite"
)
//go:embed web/*
var webFS embed.FS
const (
maxUploadBytes = int64(2 << 30)
sessionTTL = 12 * time.Hour
)
type config struct {
listen, shareListen, publicBase, managementBase, dbPath, dataDir, adminUser, adminPassword, adminPasswordFile string
cookieSecure bool
}
type app struct {
db *sql.DB
cfg config
templates *template.Template
writeMu sync.Mutex
shareMu sync.Mutex
}
type user struct {
ID int64 `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
Quota int64 `json:"quota"`
Disabled bool `json:"disabled"`
CreatedAt string `json:"created_at"`
}
type principal struct {
UserID int64
Username string
Role string
CSRF string
Expires time.Time
MustChangePassword bool
}
type share struct {
ID int64
OwnerID int64
Token string
Name string
RelPath string
ExpiresAt sql.NullString
Active bool
CreatedAt string
}
type fileItem struct {
Name, Path, Type, Modified, URL string
Size int64
}
type pageData struct {
Title, Page, Lang, Slogan, CSRF, Username, Role, CurrentPath, ParentPath, ShareURL, Error, Notice string
Quota, Used int64
Users []user
Files []fileItem
Shares []share
Audit []map[string]string
}
var usernameRx = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{2,31}$`)
func main() {
cfg := config{}
flag.StringVar(&cfg.listen, "listen", "127.0.0.1:8080", "management listener")
flag.StringVar(&cfg.shareListen, "share-listen", "127.0.0.1:8081", "public share listener")
flag.StringVar(&cfg.publicBase, "public-base", "", "public share base URL, for example http://10.0.0.2:8081")
flag.StringVar(&cfg.managementBase, "management-base", "", "management base URL used for preview iframes, for example http://10.0.0.2:8080")
flag.StringVar(&cfg.dbPath, "db", "./filehub.db", "SQLite database")
flag.StringVar(&cfg.dataDir, "data", "./data", "file storage root")
flag.StringVar(&cfg.adminUser, "admin-user", "admin", "bootstrap administrator username")
flag.StringVar(&cfg.adminPassword, "admin-password", "", "bootstrap administrator password")
flag.StringVar(&cfg.adminPasswordFile, "admin-password-file", "", "read the bootstrap administrator password from a file")
flag.BoolVar(&cfg.cookieSecure, "cookie-secure", false, "set Secure session cookies")
flag.Parse()
if err := os.MkdirAll(cfg.dataDir, 0750); err != nil {
log.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(cfg.dbPath), 0750); err != nil {
log.Fatal(err)
}
db, err := sql.Open("sqlite", "file:"+cfg.dbPath+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)")
if err != nil {
log.Fatal(err)
}
defer db.Close()
a := &app{db: db, cfg: cfg}
a.templates = parseTemplates()
if err := a.migrate(); err != nil {
log.Fatal(err)
}
if err := a.bootstrapAdmin(); err != nil {
log.Fatal(err)
}
errCh := make(chan error, 2)
go func() {
log.Printf("PageRelay management listening on http://%s", cfg.listen)
errCh <- serve(cfg.listen, a.managementHandler())
}()
go func() {
log.Printf("PageRelay shares listening on http://%s", cfg.shareListen)
errCh <- serve(cfg.shareListen, a.publicHandler())
}()
log.Fatal(<-errCh)
}
func parseTemplates() *template.Template {
return template.Must(template.New("layout.html").Funcs(template.FuncMap{
"formatBytes": formatBytes,
"divGB": func(v int64) int64 { return v >> 30 },
"pct": func(used, quota int64) int {
if quota <= 0 {
return 0
}
p := used * 100 / quota
if p > 100 {
return 100
}
return int(p)
},
"isAdmin": func(role string) bool { return role == "admin" },
}).ParseFS(webFS, "web/*.html"))
}
func (a *app) managementHandler() http.Handler {
manage := http.NewServeMux()
manage.HandleFunc("/assets/", staticAsset)
manage.HandleFunc("/health", a.health)
manage.HandleFunc("/login", a.login)
manage.HandleFunc("/logout", a.logout)
manage.HandleFunc("/change-password", a.requireAuth(a.changePassword))
manage.HandleFunc("/", a.requireAuth(a.dashboard))
manage.HandleFunc("/files", a.requireAuth(a.files))
manage.HandleFunc("/content", a.requireAuth(a.content))
manage.HandleFunc("/p/", a.publicPreview)
manage.HandleFunc("/api/list", a.requireAuth(a.apiList))
manage.HandleFunc("/api/item", a.requireAuth(a.apiItem))
manage.HandleFunc("/api/share", a.requireAuth(a.apiShare))
manage.HandleFunc("/api/new", a.requireAuth(a.apiNew))
manage.HandleFunc("/api/save", a.requireAuth(a.apiSave))
manage.HandleFunc("/api/directories", a.requireAuth(a.apiDirectories))
manage.HandleFunc("/api/move", a.requireAuth(a.apiMove))
manage.HandleFunc("/api/delete-batch", a.requireAuth(a.apiDeleteBatch))
manage.HandleFunc("/api/download", a.requireAuth(a.apiDownload))
manage.HandleFunc("/upload", a.requireAuth(a.upload))
manage.HandleFunc("/mkdir", a.requireAuth(a.mkdir))
manage.HandleFunc("/rename", a.requireAuth(a.renameFile))
manage.HandleFunc("/delete", a.requireAuth(a.deleteFile))
manage.HandleFunc("/shares", a.requireAuth(a.shares))
manage.HandleFunc("/shares/create", a.requireAuth(a.createShare))
manage.HandleFunc("/shares/revoke", a.requireAuth(a.revokeShare))
manage.HandleFunc("/admin/users", a.requireAdmin(a.adminUsers))
manage.HandleFunc("/admin/users/create", a.requireAdmin(a.createUser))
manage.HandleFunc("/admin/users/update", a.requireAdmin(a.updateUser))
manage.HandleFunc("/admin/audit", a.requireAdmin(a.adminAudit))
return securityHeaders(false, manage)
}
func (a *app) publicHandler() http.Handler {
public := http.NewServeMux()
public.HandleFunc("/assets/", staticAsset)
public.HandleFunc("/health", a.health)
public.HandleFunc("/s/", a.publicShare)
public.HandleFunc("/p/", a.publicPreview)
return securityHeaders(true, public)
}
func serve(addr string, handler http.Handler) error {
s := &http.Server{Addr: addr, Handler: handler, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 1 << 20}
return s.ListenAndServe()
}
func securityHeaders(public bool, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
if !public {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; img-src 'self' data:; media-src 'self'; frame-src 'self' http: https:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'")
}
next.ServeHTTP(w, r)
})
}
func staticAsset(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
methodNotAllowed(w)
return
}
name := strings.TrimPrefix(r.URL.Path, "/assets/")
if name != "app.css" && name != "app.js" && name != "pagerelay-logo.svg" && name != "pagerelay-icon.svg" && name != "mermaid.min.js" {
http.NotFound(w, r)
return
}
b, err := webFS.ReadFile("web/" + name)
if err != nil {
http.NotFound(w, r)
return
}
if strings.HasSuffix(name, ".css") {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
} else if strings.HasSuffix(name, ".svg") {
w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8")
} else {
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
}
w.Header().Set("Cache-Control", "public, max-age=3600")
_, _ = w.Write(b)
}
func (a *app) migrate() error {
stmts := []string{
`CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE COLLATE NOCASE, password_hash TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('admin','user')), quota_bytes INTEGER NOT NULL DEFAULT 10737418240, disabled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE TABLE IF NOT EXISTS sessions (token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, csrf TEXT NOT NULL, expires_at TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE TABLE IF NOT EXISTS shares (id INTEGER PRIMARY KEY AUTOINCREMENT, owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, token_value TEXT NOT NULL, name TEXT NOT NULL, rel_path TEXT NOT NULL, expires_at TEXT, active INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE TABLE IF NOT EXISTS audit_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, action TEXT NOT NULL, target TEXT NOT NULL DEFAULT '', ip TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE TABLE IF NOT EXISTS preview_tokens (token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, rel_path TEXT NOT NULL, expires_at TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE INDEX IF NOT EXISTS idx_sessions_user_expires ON sessions(user_id, expires_at)`,
`CREATE INDEX IF NOT EXISTS idx_shares_owner_active ON shares(owner_id, active)`,
`CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at DESC)`,
`CREATE INDEX IF NOT EXISTS idx_preview_tokens_expires ON preview_tokens(expires_at)`,
}
for _, stmt := range stmts {
if _, err := a.db.Exec(stmt); err != nil {
return err
}
}
_, _ = a.db.Exec(`DELETE FROM sessions WHERE expires_at < datetime('now')`)
_, _ = a.db.Exec(`DELETE FROM preview_tokens WHERE expires_at < datetime('now')`)
// PageRelay 2.0 uses a simple enabled/disabled share state. Keep every
// previously active link valid and leave revoked links revoked.
if err := addColumnIfMissing(a.db, `users`, `must_change_password`, `INTEGER NOT NULL DEFAULT 0`); err != nil {
return err
}
_, _ = a.db.Exec(`UPDATE shares SET expires_at=NULL WHERE active=1`)
_, _ = a.db.Exec(`PRAGMA optimize`)
return nil
}
func addColumnIfMissing(db *sql.DB, table, column, decl string) error {
rows, err := db.Query(fmt.Sprintf(`PRAGMA table_info(%s)`, table))
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var cid int
var name, typ string
var notnull, pk int
var dflt sql.NullString
if err := rows.Scan(&cid, &name, &typ, ¬null, &dflt, &pk); err != nil {
return err
}
if name == column {
return nil // already present
}
}
if _, err := db.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, table, column, decl)); err != nil {
return err
}
return nil
}
func (a *app) bootstrapAdmin() error {
var count int
if err := a.db.QueryRow(`SELECT COUNT(*) FROM users WHERE role='admin'`).Scan(&count); err != nil {
return err
}
if count > 0 {
return nil
}
password := a.cfg.adminPassword
if password == "" && a.cfg.adminPasswordFile != "" {
contents, err := os.ReadFile(a.cfg.adminPasswordFile)
if err != nil {
return fmt.Errorf("read bootstrap password file: %w", err)
}
password = strings.TrimRight(string(contents), "\r\n")
}
mustChange := 0
if password == "" {
// Fixed default credentials; the administrator must set a real password
// on first login. Discoverable for novice operators deploying from
// source without passing a password flag.
password = "admin"
mustChange = 1
log.Printf("BOOTSTRAP ADMIN: default credentials %s/admin — you must set a new password on first login", a.cfg.adminUser)
} else if len(password) < 10 {
return errors.New("bootstrap administrator password must contain at least 10 characters")
}
hash, err := hashPassword(password)
if err != nil {
return err
}
res, err := a.db.Exec(`INSERT INTO users(username,password_hash,role,quota_bytes,must_change_password) VALUES(?,?,'admin',?,?)`, a.cfg.adminUser, hash, int64(100<<30), mustChange)
if err != nil {
return err
}
id, _ := res.LastInsertId()
return os.MkdirAll(a.userRoot(id), 0750)
}
func (a *app) health(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
_, _ = io.WriteString(w, "ok\n")
}
func (a *app) login(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Language")
if r.Method == http.MethodGet {
a.render(w, "login", loginPageData(r, false))
return
}
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
if err := r.ParseForm(); err != nil {
badRequest(w, "请求无效")
return
}
var u user
var hash string
var disabled, mustChange int
err := a.db.QueryRow(`SELECT id,username,password_hash,role,quota_bytes,disabled,must_change_password,created_at FROM users WHERE username=?`, strings.TrimSpace(r.FormValue("username"))).Scan(&u.ID, &u.Username, &hash, &u.Role, &u.Quota, &disabled, &mustChange, &u.CreatedAt)
if err != nil || disabled != 0 || !verifyPassword(hash, r.FormValue("password")) {
a.audit(0, "login_failed", strings.TrimSpace(r.FormValue("username")), clientIP(r))
time.Sleep(350 * time.Millisecond)
a.renderStatus(w, http.StatusUnauthorized, "login", loginPageData(r, true))
return
}
token, csrf := randomToken(32), randomToken(24)
expires := time.Now().Add(sessionTTL).UTC()
if _, err := a.db.Exec(`INSERT INTO sessions(token_hash,user_id,csrf,expires_at) VALUES(?,?,?,?)`, tokenHash(token), u.ID, csrf, expires.Format("2006-01-02 15:04:05")); err != nil {
serverError(w, err)
return
}
http.SetCookie(w, &http.Cookie{Name: "filehub_session", Value: token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: a.cfg.cookieSecure, Expires: expires})
a.audit(u.ID, "login", "", clientIP(r))
if mustChange == 1 {
http.Redirect(w, r, "/change-password", http.StatusSeeOther)
return
}
http.Redirect(w, r, "/files", http.StatusSeeOther)
}
func loginPageData(r *http.Request, invalidCredentials bool) pageData {
data := pageData{Title: "登录", Page: "login", Lang: "zh-CN", Slogan: "将本地文件快速变成可分享的网页。"}
primaryLanguage := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("Accept-Language"), ",")[0]))
if strings.HasPrefix(primaryLanguage, "en") {
data.Title = "Sign in"
data.Lang = "en"
data.Slogan = "Turn local files into shareable web pages."
}
if invalidCredentials {
if data.Lang == "en" {
data.Error = "Incorrect username or password"
} else {
data.Error = "用户名或密码不正确"
}
}
return data
}
func (a *app) logout(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
p, ok := a.authenticate(r)
if !ok || !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
if c, err := r.Cookie("filehub_session"); err == nil {
_, _ = a.db.Exec(`DELETE FROM sessions WHERE token_hash=?`, tokenHash(c.Value))
}
http.SetCookie(w, &http.Cookie{Name: "filehub_session", Value: "", Path: "/", HttpOnly: true, MaxAge: -1, SameSite: http.SameSiteStrictMode, Secure: a.cfg.cookieSecure})
a.audit(p.UserID, "logout", "", clientIP(r))
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
func (a *app) changePassword(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method == http.MethodGet {
data := changePasswordPageData(r)
data.CSRF = p.CSRF
a.render(w, "change-password", data)
return
}
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
if err := r.ParseForm(); err != nil {
badRequest(w, "请求无效")
return
}
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
var hash string
if err := a.db.QueryRow(`SELECT password_hash FROM users WHERE id=?`, p.UserID).Scan(&hash); err != nil {
serverError(w, err)
return
}
if !verifyPassword(hash, r.FormValue("current")) {
a.renderStatus(w, http.StatusUnauthorized, "change-password", changePasswordPageDataWithError(r, "当前密码不正确", p.CSRF))
return
}
newPass := r.FormValue("new")
if len(newPass) < 10 {
a.renderStatus(w, http.StatusBadRequest, "change-password", changePasswordPageDataWithError(r, "新密码至少 10 位", p.CSRF))
return
}
if newPass != r.FormValue("confirm") {
a.renderStatus(w, http.StatusBadRequest, "change-password", changePasswordPageDataWithError(r, "两次输入的新密码不一致", p.CSRF))
return
}
newHash, err := hashPassword(newPass)
if err != nil {
serverError(w, err)
return
}
if _, err := a.db.Exec(`UPDATE users SET password_hash=?,must_change_password=0 WHERE id=?`, newHash, p.UserID); err != nil {
serverError(w, err)
return
}
// Drop every other session so the new password takes effect elsewhere;
// the current session (a fresh one issued at login) stays.
if c, err := r.Cookie("filehub_session"); err == nil {
_, _ = a.db.Exec(`DELETE FROM sessions WHERE user_id=? AND token_hash!=?`, p.UserID, tokenHash(c.Value))
}
p.MustChangePassword = false
a.audit(p.UserID, "password_change", "", clientIP(r))
http.Redirect(w, r, "/files", http.StatusSeeOther)
}
func changePasswordPageData(r *http.Request) pageData {
data := pageData{Title: "设置密码", Page: "change-password", Lang: "zh-CN", Slogan: "首次登录,请设置新密码后继续。"}
primaryLanguage := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("Accept-Language"), ",")[0]))
if strings.HasPrefix(primaryLanguage, "en") {
data.Title = "Set password"
data.Lang = "en"
data.Slogan = "Set a new password to continue."
}
return data
}
func changePasswordPageDataWithError(r *http.Request, msg string, csrf string) pageData {
data := changePasswordPageData(r)
data.Error = msg
data.CSRF = csrf
return data
}
func (a *app) authenticate(r *http.Request) (principal, bool) {
c, err := r.Cookie("filehub_session")
if err != nil || len(c.Value) < 32 {
return principal{}, false
}
var p principal
var expires string
var disabled, mustChange int
err = a.db.QueryRow(`SELECT u.id,u.username,u.role,s.csrf,s.expires_at,u.disabled,u.must_change_password FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=?`, tokenHash(c.Value)).Scan(&p.UserID, &p.Username, &p.Role, &p.CSRF, &expires, &disabled, &mustChange)
if err != nil || disabled != 0 {
return principal{}, false
}
p.MustChangePassword = mustChange == 1
p.Expires, _ = time.Parse("2006-01-02 15:04:05", expires)
if time.Now().UTC().After(p.Expires) {
_, _ = a.db.Exec(`DELETE FROM sessions WHERE token_hash=?`, tokenHash(c.Value))
return principal{}, false
}
return p, true
}
func (a *app) requireAuth(next func(http.ResponseWriter, *http.Request, principal)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
p, ok := a.authenticate(r)
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if p.MustChangePassword && r.URL.Path != "/change-password" && r.URL.Path != "/logout" {
http.Redirect(w, r, "/change-password", http.StatusSeeOther)
return
}
next(w, r, p)
}
}
func (a *app) requireAdmin(next func(http.ResponseWriter, *http.Request, principal)) http.HandlerFunc {
return a.requireAuth(func(w http.ResponseWriter, r *http.Request, p principal) {
if p.Role != "admin" {
http.Error(w, "禁止访问", http.StatusForbidden)
return
}
next(w, r, p)
})
}
func (a *app) checkCSRF(r *http.Request, p principal) bool {
return r.FormValue("csrf") != "" && hmac.Equal([]byte(r.FormValue("csrf")), []byte(p.CSRF))
}
func (a *app) dashboard(w http.ResponseWriter, r *http.Request, p principal) {
http.Redirect(w, r, "/files", http.StatusSeeOther)
}
func (a *app) files(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodGet {
methodNotAllowed(w)
return
}
rel, err := cleanRel(r.URL.Query().Get("path"))
if err != nil {
badRequest(w, "目录无效")
return
}
root := a.userRoot(p.UserID)
full, err := safeJoin(root, rel)
if err != nil {
badRequest(w, "目录无效")
return
}
info, err := os.Stat(full)
if err != nil || !info.IsDir() {
if os.IsNotExist(err) {
http.NotFound(w, r)
} else {
serverError(w, err)
}
return
}
used := dirSize(root)
quota := a.userQuota(p.UserID)
parent := ""
if rel != "" {
parent = path.Dir(rel)
if parent == "." {
parent = ""
}
}
a.render(w, "files", pageData{Title: "文件工作台", Page: "files", CSRF: p.CSRF, Username: p.Username, Role: p.Role, CurrentPath: rel, ParentPath: parent, Used: used, Quota: quota})
}
func (a *app) content(w http.ResponseWriter, r *http.Request, p principal) {
rel, err := cleanRel(r.URL.Query().Get("path"))
if err != nil || rel == "" {
badRequest(w, "路径无效")
return
}
full, err := safeJoin(a.userRoot(p.UserID), rel)
if err != nil {
badRequest(w, "路径无效")
return
}
info, err := os.Stat(full)
if err != nil || info.IsDir() {
http.NotFound(w, r)
return
}
a.audit(p.UserID, "content_read", rel, clientIP(r))
servePrivateFile(w, r, full, info)
}
func servePrivateFile(w http.ResponseWriter, r *http.Request, file string, info fs.FileInfo) {
ext := strings.ToLower(filepath.Ext(file))
ctype := mime.TypeByExtension(ext)
if ctype == "" {
ctype = "application/octet-stream"
}
w.Header().Set("Content-Type", ctype)
// Never execute user-authored HTML inside the authenticated management origin.
if ext == ".html" || ext == ".htm" || ext == ".svg" {
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", info.Name()))
}
f, err := os.Open(file)
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
http.ServeContent(w, r, info.Name(), info.ModTime(), f)
}
func (a *app) upload(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes)
if err := r.ParseMultipartForm(32 << 20); err != nil {
badRequest(w, "上传内容过大或格式错误")
return
}
defer r.MultipartForm.RemoveAll()
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
rel, err := cleanRel(r.FormValue("path"))
if err != nil {
badRequest(w, "目录无效")
return
}
root := a.userRoot(p.UserID)
destDir, err := safeJoin(root, rel)
if err != nil {
badRequest(w, "目录无效")
return
}
files := r.MultipartForm.File["files"]
if len(files) == 0 {
badRequest(w, "没有选择文件")
return
}
a.writeMu.Lock()
defer a.writeMu.Unlock()
used := dirSize(root)
quota := a.userQuota(p.UserID)
// Optional per-file relative paths submitted by the folder-upload UI.
// When present they line up with files[] by index and carry structure
// such as "photos/2024/img.png"; otherwise we fall back to the base name.
paths := r.MultipartForm.Value["paths"]
for idx, fh := range files {
raw := fh.Filename
if idx < len(paths) && paths[idx] != "" {
raw = paths[idx]
}
// Preserve folder structure: the relative path is sanitized and we
// create intermediate directories before writing the file.
fileRel, err := cleanRel(raw)
if err != nil || fileRel == "" {
continue
}
if strings.HasPrefix(filepath.Base(fileRel), ".") {
continue
}
src, err := fh.Open()
if err != nil {
serverError(w, err)
return
}
dest, err := safeJoin(destDir, fileRel)
if err != nil {
src.Close()
badRequest(w, "文件名无效")
return
}
if err := os.MkdirAll(filepath.Dir(dest), 0750); err != nil {
src.Close()
serverError(w, err)
return
}
var oldSize int64
if oldInfo, statErr := os.Stat(dest); statErr == nil {
if oldInfo.IsDir() {
src.Close()
badRequest(w, "同名目录已存在")
return
}
oldSize = oldInfo.Size()
}
if used-oldSize+fh.Size > quota {
src.Close()
http.Error(w, "存储配额不足", http.StatusRequestEntityTooLarge)
return
}
tmp := dest + ".upload-" + randomToken(6)
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0640)
if err != nil {
src.Close()
serverError(w, err)
return
}
n, copyErr := io.Copy(out, src)
closeErr := out.Close()
src.Close()
if copyErr != nil || closeErr != nil {
os.Remove(tmp)
serverError(w, firstErr(copyErr, closeErr))
return
}
if err := os.Rename(tmp, dest); err != nil {
os.Remove(tmp)
serverError(w, err)
return
}
used = used - oldSize + n
uploadedPath := path.Join(rel, fileRel)
if _, err := a.ensureShare(p.UserID, uploadedPath); err != nil {
serverError(w, err)
return
}
a.audit(p.UserID, "upload", uploadedPath, clientIP(r))
}
a.writeSuccess(w, r, rel)
}
func (a *app) mkdir(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
r.ParseForm()
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
rel, err := cleanRel(r.FormValue("path"))
if err != nil {
badRequest(w, "目录无效")
return
}
name := filepath.Base(strings.TrimSpace(r.FormValue("name")))
if name == "." || name == "" || strings.HasPrefix(name, ".") {
badRequest(w, "目录名无效")
return
}
base, _ := safeJoin(a.userRoot(p.UserID), rel)
dest, err := safeJoin(base, name)
if err != nil {
badRequest(w, "目录名无效")
return
}
if err := os.Mkdir(dest, 0750); err != nil {
badRequest(w, "目录已存在或无法创建")
return
}
a.audit(p.UserID, "mkdir", path.Join(rel, name), clientIP(r))
a.writeSuccess(w, r, rel)
}
func (a *app) renameFile(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
_ = r.ParseForm()
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
rel, err := cleanRel(r.FormValue("path"))
if err != nil || rel == "" {
badRequest(w, "路径无效")
return
}
newName := filepath.Base(strings.TrimSpace(r.FormValue("name")))
if newName == "." || newName == "" || strings.HasPrefix(newName, ".") {
badRequest(w, "新名称无效")
return
}
root := a.userRoot(p.UserID)
source, err := safeJoin(root, rel)
if err != nil {
badRequest(w, "路径无效")
return
}
parent := path.Dir(rel)
if parent == "." {
parent = ""
}
base, _ := safeJoin(root, parent)
dest, err := safeJoin(base, newName)
if err != nil {
badRequest(w, "新名称无效")
return
}
if _, err := os.Stat(dest); err == nil {
badRequest(w, "同名文件或目录已存在")
return
}
if err := os.Rename(source, dest); err != nil {
serverError(w, err)
return
}
newRel := path.Join(parent, newName)
_, _ = a.db.Exec(`UPDATE shares SET rel_path = ? || substr(rel_path, length(?) + 1), name = CASE WHEN rel_path = ? THEN ? ELSE name END WHERE owner_id=? AND (rel_path=? OR rel_path LIKE ?)`, newRel, rel, rel, newName, p.UserID, rel, rel+"/%")
a.audit(p.UserID, "rename", rel+" -> "+newRel, clientIP(r))
a.writeSuccess(w, r, parent)
}
func (a *app) deleteFile(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
r.ParseForm()
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
rel, err := cleanRel(r.FormValue("path"))
if err != nil || rel == "" {
badRequest(w, "路径无效")
return
}
full, err := safeJoin(a.userRoot(p.UserID), rel)
if err != nil {
badRequest(w, "路径无效")
return
}
if err := os.RemoveAll(full); err != nil {
serverError(w, err)
return
}
_, _ = a.db.Exec(`UPDATE shares SET active=0 WHERE owner_id=? AND (rel_path=? OR rel_path LIKE ?)`, p.UserID, rel, rel+"/%")
a.audit(p.UserID, "delete", rel, clientIP(r))
parent := path.Dir(rel)
if parent == "." {
parent = ""
}
a.writeSuccess(w, r, parent)
}
func (a *app) shares(w http.ResponseWriter, r *http.Request, p principal) {
rows, err := a.db.Query(`SELECT id,owner_id,token_value,name,rel_path,expires_at,active,created_at FROM shares WHERE owner_id=? ORDER BY id DESC`, p.UserID)
if err != nil {
serverError(w, err)
return
}
defer rows.Close()
var list []share
for rows.Next() {
var s share
rows.Scan(&s.ID, &s.OwnerID, &s.Token, &s.Name, &s.RelPath, &s.ExpiresAt, &s.Active, &s.CreatedAt)
list = append(list, s)
}
a.render(w, "shares", pageData{Title: "分享链接", Page: "shares", CSRF: p.CSRF, Username: p.Username, Role: p.Role, Shares: list, ShareURL: a.shareBase(r)})
}
func (a *app) createShare(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
r.ParseForm()
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
rel, err := cleanRel(r.FormValue("path"))
if err != nil || rel == "" {
badRequest(w, "请选择文件或目录")
return
}
full, err := safeJoin(a.userRoot(p.UserID), rel)
if err != nil {
badRequest(w, "路径无效")
return
}
if _, err := os.Stat(full); err != nil {
http.NotFound(w, r)
return
}
if _, err = a.ensureShare(p.UserID, rel); err != nil {
serverError(w, err)
return
}
a.audit(p.UserID, "share_create", rel, clientIP(r))
http.Redirect(w, r, "/shares", http.StatusSeeOther)
}
func (a *app) revokeShare(w http.ResponseWriter, r *http.Request, p principal) {
if r.Method != http.MethodPost {
methodNotAllowed(w)
return
}
r.ParseForm()
if !a.checkCSRF(r, p) {
badRequest(w, "请求已过期")
return
}
id, _ := strconv.ParseInt(r.FormValue("id"), 10, 64)
_, err := a.db.Exec(`UPDATE shares SET active=0 WHERE id=? AND owner_id=?`, id, p.UserID)
if err != nil {
serverError(w, err)
return
}
a.audit(p.UserID, "share_revoke", strconv.FormatInt(id, 10), clientIP(r))
http.Redirect(w, r, "/shares", http.StatusSeeOther)
}
func (a *app) publicShare(w http.ResponseWriter, r *http.Request) {
rest := strings.TrimPrefix(r.URL.Path, "/s/")
parts := strings.SplitN(rest, "/", 2)
if len(parts) == 0 || len(parts[0]) < 20 {
http.NotFound(w, r)
return
}
var s share
err := a.db.QueryRow(`SELECT id,owner_id,token_value,name,rel_path,expires_at,active,created_at FROM shares WHERE token_hash=?`, tokenHash(parts[0])).Scan(&s.ID, &s.OwnerID, &s.Token, &s.Name, &s.RelPath, &s.ExpiresAt, &s.Active, &s.CreatedAt)
if err != nil || !s.Active {
http.NotFound(w, r)
return
}
if s.ExpiresAt.Valid {
expires, _ := time.Parse("2006-01-02 15:04:05", s.ExpiresAt.String)
if time.Now().UTC().After(expires) {
http.NotFound(w, r)
return
}
}
base, err := safeJoin(a.userRoot(s.OwnerID), s.RelPath)
if err != nil {
http.NotFound(w, r)
return
}
info, err := os.Stat(base)
if err != nil {
http.NotFound(w, r)
return
}
if !info.IsDir() {
// An HTML or Markdown share acts like a mini-site: assets referenced
// with relative URLs (images, css, js, sub-pages) are served from
// the same directory tree, mirroring the preview endpoint behaviour.
// Without a trailing slash the browser resolves relative asset URLs
// against /s/ (dropping the token) and they 404, so redirect.
if len(parts) == 1 {
if detectPreview(s.RelPath, false) == "html" {
http.Redirect(w, r, "/s/"+parts[0]+"/", http.StatusSeeOther)
return
}
}
if len(parts) > 1 && parts[1] != "" {
switch detectPreview(s.RelPath, false) {
case "html", "markdown":
assetRel, err := cleanRel(parts[1])
if err != nil {
http.NotFound(w, r)
return
}
asset, err := safeJoin(filepath.Dir(base), assetRel)
if err != nil {
http.NotFound(w, r)
return
}
assetInfo, err := os.Stat(asset)
if err != nil || assetInfo.IsDir() {
http.NotFound(w, r)
return
}
serveSharedFile(w, r, asset, assetInfo)
return
default:
http.NotFound(w, r)
return
}
}
if detectPreview(s.RelPath, false) == "markdown" {
a.serveMarkdownPreview(w, r, base, info.Name(), "/s/"+parts[0]+"/")
return
}
serveSharedFile(w, r, base, info)
return