Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
1477 lines (1349 loc) · 41.9 KB
/
Copy pathserver.go
File metadata and controls
1477 lines (1349 loc) · 41.9 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 httpserver
import (
"crypto/sha256"
"encoding/json"
"errors"
"io/fs"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/ZenNotes/znserver"
"github.com/ZenNotes/znserver/internal/config"
"github.com/ZenNotes/znserver/internal/vault"
"github.com/ZenNotes/znserver/internal/watcher"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
// Per-request body envelope allowances applied on top of the
// configured note/asset size limits. They cover JSON keys + structural
// overhead (writeNote) and multipart boundaries + form fields
// (uploadAsset). Generous enough to never reject a payload that's
// within the configured limit.
const (
jsonEnvelopeBytes int64 = 64 << 10 // 64 KiB
multipartOverheadBytes int64 = 256 << 10 // 256 KiB
)
type Server struct {
mu sync.RWMutex
Config config.Config
Vault *vault.Vault
Watcher *watcher.Watcher
Static fs.FS // embedded web bundle, may be nil in dev
sessions *sessionStore
loginLimiter *attemptLimiter
wsRejectLimiter *attemptLimiter
loggedOrigins sync.Map // origin -> struct{}; dedupes CORS-rejection logs
// loggedOriginCount is how many are in loggedOrigins.
loggedOriginCount atomic.Int64
// Set once by EnableMCP before Router runs, and read-only after. mcp stays nil
// unless MCP is on, in which case /mcp is not routed at all.
mcp http.Handler
mcpTokens map[[sha256.Size]byte]bool
// mcpResponseBytes is mcpResponseLimit, worked out once.
mcpResponseBytes int64
// self is the finished router, which the MCP tools call in-process.
self http.Handler
}
func init() {
// Go's builtin MIME table lacks web-font types, and static assets are served
// with X-Content-Type-Options: nosniff, so register them explicitly. The web
// bundle self-hosts Excalidraw's woff2 fonts under /excalidraw-assets/.
_ = mime.AddExtensionType(".woff2", "font/woff2")
_ = mime.AddExtensionType(".woff", "font/woff")
_ = mime.AddExtensionType(".ttf", "font/ttf")
_ = mime.AddExtensionType(".otf", "font/otf")
}
func New(v *vault.Vault, w *watcher.Watcher, static fs.FS, cfg config.Config) *Server {
// Opt-in: persist browser sessions next to the host config so they survive a
// restart. Off by default — an empty path keeps the store purely in-memory.
sessionsPath := ""
if cfg.PersistSessions {
sessionsPath = config.SessionsPath()
}
return &Server{
Vault: v,
Watcher: w,
Static: static,
Config: cfg,
sessions: newSessionStore(sessionsPath),
loginLimiter: newAttemptLimiter(10*time.Minute, 10),
wsRejectLimiter: newAttemptLimiter(1*time.Minute, 20),
}
}
func (s *Server) currentVault() *vault.Vault {
s.mu.RLock()
defer s.mu.RUnlock()
return s.Vault
}
func (s *Server) currentWatcher() *watcher.Watcher {
s.mu.RLock()
defer s.mu.RUnlock()
return s.Watcher
}
func (s *Server) currentConfig() config.Config {
s.mu.RLock()
defer s.mu.RUnlock()
return s.Config
}
func (s *Server) switchVaultRoot(nextPath string) (*vault.Vault, error) {
cfg := s.currentConfig()
nextVault, err := vault.New(nextPath, vault.Options{
FileMode: cfg.VaultFileMode,
DirMode: cfg.VaultDirMode,
MaxAssetBytes: cfg.MaxAssetBytes,
})
if err != nil {
return nil, err
}
// Non-fatal: a vault switch must not fail just because inotify is
// unavailable; fall back to a no-op watcher in that case. (#179)
nextWatcher := watcher.StartOrDisabled(nextVault.Root(), cfg.DisableWatcher)
s.mu.Lock()
prevWatcher := s.Watcher
s.Vault = nextVault
s.Watcher = nextWatcher
s.Config.VaultPath = nextVault.Root()
cfg = s.Config
s.mu.Unlock()
if prevWatcher != nil {
prevWatcher.Close()
}
_ = config.SaveHost(cfg)
return nextVault, nil
}
func (s *Server) Router() http.Handler {
inner := chi.NewRouter()
inner.Route("/api", func(r chi.Router) {
r.Get("/healthz", s.healthz)
r.Get("/version", s.version)
r.Get("/capabilities", s.capabilities)
r.Get("/platform", s.platform)
r.Get("/session", s.sessionStatus)
r.Post("/session/login", s.sessionLogin)
r.Post("/session/logout", s.sessionLogout)
r.Group(func(r chi.Router) {
r.Use(s.requireAuth)
s.registerProtectedRoutes(r)
})
})
// Legacy root-level API compatibility. Keep this around so the web client
// still works during partial restarts or when an older bundle is cached.
inner.Get("/healthz", s.healthz)
inner.Get("/version", s.version)
inner.Get("/capabilities", s.capabilities)
inner.Get("/platform", s.platform)
inner.Get("/session", s.sessionStatus)
inner.Post("/session/login", s.sessionLogin)
inner.Post("/session/logout", s.sessionLogout)
inner.Group(func(r chi.Router) {
r.Use(s.requireAuth)
s.registerProtectedRoutes(r)
})
// Outside requireAuth, which takes the server's token: /mcp has its own.
if s.mcp != nil {
inner.Handle("/mcp", s.mcp)
}
// Static / PWA fallback.
if s.Static != nil {
inner.Get("/*", s.serveStatic)
}
outer := chi.NewRouter()
outer.Use(middleware.RequestID)
// Intentionally not using middleware.RealIP: it rewrites
// r.RemoteAddr from X-Forwarded-For unconditionally, which would
// let any client spoof the rate-limit and audit identity.
// clientAddressKey() does trust-aware extraction instead.
outer.Use(s.securityHeadersMiddleware)
outer.Use(s.corsMiddleware)
outer.Use(middleware.Recoverer)
s.self = outer
basePath := s.currentConfig().BasePath
if basePath != "" {
outer.Mount(basePath, inner)
return outer
}
outer.Mount("/", inner)
return outer
}
func (s *Server) registerProtectedRoutes(r chi.Router) {
r.Post("/session/rotate-token", s.sessionRotateToken)
r.Get("/vault", s.vaultInfo)
r.Get("/vault/settings", s.vaultSettings)
r.Post("/vault/settings", s.setVaultSettings)
r.Post("/vault/select", s.selectVault)
r.Get("/fs/browse", s.browseDirectories)
r.Get("/notes", s.listNotes)
r.Get("/folders", s.listFolders)
r.Get("/assets", s.listAssets)
r.Get("/assets/exists", s.assetsExists)
r.Get("/assets/raw", s.rawAsset)
r.Post("/assets/upload", s.uploadAsset)
r.Post("/assets/rename", s.renameAsset)
r.Post("/assets/move", s.moveAsset)
r.Post("/assets/duplicate", s.duplicateAsset)
r.Post("/assets/delete", s.deleteAsset)
r.Get("/assets/deleted", s.listDeletedAssets)
r.Post("/assets/restore", s.restoreDeletedAsset)
r.Post("/assets/purge", s.purgeDeletedAsset)
r.Post("/assets/empty-deleted", s.emptyDeletedAssets)
r.Get("/notes/read", s.readNote)
r.Get("/comments/read", s.readComments)
r.Post("/comments/write", s.writeComments)
r.Post("/notes/write", s.writeNote)
r.Post("/notes/create", s.createNote)
r.Post("/excalidraw/create", s.createExcalidraw)
r.Post("/notes/rename", s.renameNote)
r.Post("/notes/delete", s.deleteNote)
r.Post("/notes/trash", s.trashNote)
r.Post("/notes/restore", s.restoreNote)
r.Post("/notes/empty-trash", s.emptyTrash)
r.Post("/notes/archive", s.archiveNote)
r.Post("/notes/unarchive", s.unarchiveNote)
r.Post("/notes/duplicate", s.duplicateNote)
r.Post("/notes/move", s.moveNote)
r.Post("/folders/create", s.createFolder)
r.Post("/folders/rename", s.renameFolder)
r.Post("/folders/delete", s.deleteFolder)
r.Post("/folders/duplicate", s.duplicateFolder)
r.Get("/templates", s.listTemplates)
r.Get("/templates/read", s.readTemplate)
r.Post("/templates/write", s.writeTemplate)
r.Post("/templates/delete", s.deleteTemplate)
r.Get("/search/capabilities", s.searchCapabilities)
r.Get("/search/text", s.searchText)
r.Get("/tasks", s.allTasks)
r.Get("/tasks/for", s.tasksFor)
r.Post("/demo/generate", s.demoGenerate)
r.Post("/demo/remove", s.demoRemove)
r.Get("/workflows", s.listWorkflows)
r.Post("/workflows/write", s.writeWorkflow)
r.Post("/workflows/delete", s.deleteWorkflow)
r.Post("/workflows/apply", s.applyWorkflow)
r.Post("/workflows/undo", s.undoWorkflowRun)
r.Get("/workflows/runs", s.listWorkflowRuns)
r.Post("/workflows/runs/delete", s.deleteWorkflowRuns)
r.Get("/watch", s.watchWS)
}
func platformName() string {
switch runtime.GOOS {
case "darwin":
return "darwin"
case "windows":
return "win32"
default:
return "linux"
}
}
func (s *Server) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cfg := s.currentConfig()
expected := strings.TrimSpace(cfg.AuthToken)
if expected == "" {
next.ServeHTTP(w, r)
return
}
provided := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
if subtleCompare(provided, expected) || s.requestAuthenticatedViaSession(r) {
next.ServeHTTP(w, r)
return
}
if strings.HasSuffix(r.URL.Path, "/watch") || r.URL.Path == "/watch" {
if !s.wsRejectLimiter.allow(s.clientAddressKey(r)) {
http.Error(w, "too many unauthorized websocket attempts", http.StatusTooManyRequests)
return
}
}
w.Header().Set("WWW-Authenticate", `Bearer realm="ZenNotes"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
})
}
// --- Responses ---
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, err error) {
var statusErr httpStatusError
if errors.As(err, &statusErr) {
http.Error(w, statusErr.Error(), statusErr.code)
return
}
if errors.Is(err, vault.ErrPathEscape) || errors.Is(err, vault.ErrThroughSymlink) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if errors.Is(err, vault.ErrInvalidWorkflow) || errors.Is(err, vault.ErrInvalidTemplate) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if errors.Is(err, vault.ErrWorkflowConflict) {
http.Error(w, err.Error(), http.StatusConflict)
return
}
// A missing file is the caller's answer, not our failure. Clients rely on
// this to tell "absent" apart from "broken": desktop remote databases map
// 404 to null and surface everything else.
if errors.Is(err, os.ErrNotExist) {
http.Error(w, "not found", http.StatusNotFound)
return
}
// Asking to read a directory as a file is a malformed request, not a
// server failure, and saying 500 sent one report chasing a broken server
// that was working correctly.
//
// The vault layer classifies this from its own stat, because the errno is
// not portable: reading a directory gives EISDIR on Unix and
// ERROR_INVALID_FUNCTION on Windows, which is how this answered 400 on
// macOS and Linux and 500 on Windows for two weeks. EISDIR stays as a
// fallback for read paths that have not been classified, where it is still
// right on the platforms that produce it.
if errors.Is(err, vault.ErrIsDirectory) || errors.Is(err, syscall.EISDIR) {
http.Error(w, "path is a directory, not a file", http.StatusBadRequest)
return
}
log.Printf("handler error: %v", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
}
// Error body for the vault-picker routes (/fs/browse, /vault/select).
//
// Every other route answers an error with plain text, which is fine because
// nothing has to tell those errors apart from anything else. These two do: a
// server that predates the routes answers with the router's own plain-text
// 404, and a current server answers a vanished directory with a 404 of its
// own. Only the JSON body distinguishes them, so the web client shows "that
// directory is gone" instead of "upgrade your server" (and vice versa).
type routeErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
}
func writeCodedError(w http.ResponseWriter, err error) {
status := http.StatusInternalServerError
message := "internal server error"
var statusErr httpStatusError
switch {
case errors.As(err, &statusErr):
status, message = statusErr.code, statusErr.Error()
case errors.Is(err, vault.ErrPathEscape), errors.Is(err, vault.ErrThroughSymlink):
status, message = http.StatusBadRequest, err.Error()
case errors.Is(err, os.ErrNotExist):
status, message = http.StatusNotFound, err.Error()
default:
log.Printf("handler error: %v", err)
}
writeJSON(w, status, routeErrorBody{Code: errorCodeForStatus(status), Message: message})
}
func errorCodeForStatus(status int) string {
switch status {
case http.StatusNotFound:
return "not_found"
case http.StatusForbidden:
return "forbidden"
case http.StatusBadRequest:
return "bad_request"
case http.StatusConflict:
return "conflict"
default:
return "internal_error"
}
}
func readJSON[T any](r *http.Request, out *T) error {
return json.NewDecoder(r.Body).Decode(out)
}
// --- Handlers: meta ---
func (s *Server) healthz(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (s *Server) version(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"version": znserver.Version(),
"go": runtime.Version(),
})
}
func (s *Server) capabilities(w http.ResponseWriter, _ *http.Request) {
cfg := s.currentConfig()
writeJSON(w, http.StatusOK, map[string]any{
// The release this binary was built from, which clients print in bug
// reports (`:version` and Settings' version details).
"version": znserver.Version(),
"platform": platformName(),
"authRequired": strings.TrimSpace(cfg.AuthToken) != "",
"supportsSessionLogin": true,
"browseRootsEnforced": !cfg.AllowUnscopedBrowse,
"supportsVaultSelection": true,
"supportsDirectoryBrowsing": true,
// Honest, not aspirational: the watcher can be a no-op fallback
// (inotify-restricted hosts, ZENNOTES_DISABLE_WATCHER, #179), and a
// client that believes a dead feed never refreshes on its own.
"supportsWatch": s.currentWatcher().Active(),
// The full asset mutation family incl. the deleted-assets store
// (delete/duplicate/restore/purge). Desktop remote workspaces gate
// on this to give older servers a "server needs an update" message
// instead of a bare 404.
"supportsAssetOps": true,
// Workflow files and run journals live in the mounted vault, and the
// prepared-run endpoint applies them under the same vault lock as note
// writes. Its presence lets bundled web clients enable authoring and Run.
"supportsWorkflows": true,
// Custom-template CRUD under .zennotes/templates/ (the /templates
// routes), the same files the desktop keeps for a local vault. Absent
// before 2.46: the web client and a desktop on a remote vault hide New
// template and Edit there and say the server needs an update.
"supportsCustomTemplates": true,
// vault.json's `sharesLocation` (where a share from the macOS Share
// menu is filed) survives the /vault/settings round-trip. Absent
// before 2.79, whose settings save drops it: a desktop on such a
// server hides Default shares location rather than offer a choice
// the server forgets, and files its shares in Quick Notes.
"supportsSharesLocation": true,
// vault.json's `templates.folder` (#1024) survives the
// /vault/settings round-trip, and the task scan and text search leave
// that folder out. Absent before 2.80, whose settings save drops it:
// the clients hide the Template folder row rather than offer a choice
// the server forgets.
"supportsTemplateFolder": true,
// Listings mark a note or asset that is a link (`symlink`). Absent on a
// server that lists them unmarked, where a client showing only part of
// a vault cannot tell a linked file from a real one, and so cannot
// trust a listed path to stay inside what it shows.
"supportsSymlinkMarks": true,
// Says out loud that a missing file answers 404 rather than 500.
// Databases are composed from file reads where "absent" and "failed"
// mean opposite things (see remote-absence.ts), and a server that
// cannot say which is which forced clients to probe for the answer.
// Absent from every server before 2.20.2, which is exactly what makes
// it usable as a signal.
"reportsMissingAsNotFound": true,
})
}
func (s *Server) platform(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"platform": platformName()})
}
func (s *Server) vaultInfo(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, s.currentVault().Info())
}
func (s *Server) vaultSettings(w http.ResponseWriter, _ *http.Request) {
settings, err := s.currentVault().GetSettings()
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, settings)
}
func (s *Server) setVaultSettings(w http.ResponseWriter, r *http.Request) {
var req vault.VaultSettings
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
settings, err := s.currentVault().SetSettings(req)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, settings)
}
func (s *Server) selectVault(w http.ResponseWriter, r *http.Request) {
if osPath := strings.TrimSpace(os.Getenv("ZENNOTES_VAULT_PATH")); osPath != "" {
http.Error(w, "vault path is managed by ZENNOTES_VAULT_PATH", http.StatusConflict)
return
}
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if strings.TrimSpace(req.Path) == "" {
http.Error(w, "vault path is required", http.StatusBadRequest)
return
}
allowedPath, err := s.ensureBrowsePathAllowed(req.Path)
if err != nil {
writeCodedError(w, err)
return
}
nextVault, err := s.switchVaultRoot(allowedPath)
if err != nil {
writeCodedError(w, err)
return
}
writeJSON(w, http.StatusOK, nextVault.Info())
}
type directoryBrowseEntry struct {
Name string `json:"name"`
Path string `json:"path"`
}
type directoryBrowseShortcut struct {
Label string `json:"label"`
Path string `json:"path"`
}
type directoryBrowseResult struct {
CurrentPath string `json:"currentPath"`
ParentPath *string `json:"parentPath"`
Entries []directoryBrowseEntry `json:"entries"`
Shortcuts []directoryBrowseShortcut `json:"shortcuts"`
}
func appendBrowseShortcut(shortcuts []directoryBrowseShortcut, label string, path string) []directoryBrowseShortcut {
cleaned := strings.TrimSpace(path)
if cleaned == "" {
return shortcuts
}
for _, shortcut := range shortcuts {
if shortcut.Path == cleaned {
return shortcuts
}
}
if info, err := os.Stat(cleaned); err != nil || !info.IsDir() {
return shortcuts
}
return append(shortcuts, directoryBrowseShortcut{Label: label, Path: cleaned})
}
func browseRootLabel(path string, index int) string {
cleaned := filepath.Clean(path)
root := filesystemRootForPath(cleaned)
if cleaned == root {
return "Mounted Root"
}
base := filepath.Base(cleaned)
if base == "." || base == string(filepath.Separator) || strings.TrimSpace(base) == "" {
return "Mounted Root"
}
if index == 0 {
return base
}
return base
}
func defaultBrowsePath() string {
if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {
return home
}
if runtime.GOOS == "windows" {
return `C:\`
}
return string(filepath.Separator)
}
func filesystemRootForPath(p string) string {
if volume := filepath.VolumeName(p); volume != "" {
return volume + string(filepath.Separator)
}
return string(filepath.Separator)
}
func (s *Server) browseDirectories(w http.ResponseWriter, r *http.Request) {
requested := strings.TrimSpace(r.URL.Query().Get("path"))
target := requested
if target == "" {
target = s.defaultBrowsePath()
}
target, err := s.ensureBrowsePathAllowed(target)
if err != nil {
writeCodedError(w, err)
return
}
dirEntries, err := os.ReadDir(target)
if err != nil {
writeCodedError(w, err)
return
}
entries := make([]directoryBrowseEntry, 0, len(dirEntries))
for _, entry := range dirEntries {
childPath := filepath.Join(target, entry.Name())
childInfo, err := os.Stat(childPath)
if err != nil || !childInfo.IsDir() {
continue
}
if _, err := s.ensureBrowsePathAllowed(childPath); err != nil {
continue
}
entries = append(entries, directoryBrowseEntry{
Name: entry.Name(),
Path: childPath,
})
}
sort.Slice(entries, func(i, j int) bool {
left := strings.ToLower(entries[i].Name)
right := strings.ToLower(entries[j].Name)
if left == right {
return entries[i].Name < entries[j].Name
}
return left < right
})
parentPath := filepath.Dir(target)
var parent *string
if parentPath != "" && parentPath != target {
if allowedParent, err := s.ensureBrowsePathAllowed(parentPath); err == nil {
parent = &allowedParent
}
}
writeJSON(w, http.StatusOK, directoryBrowseResult{
CurrentPath: target,
ParentPath: parent,
Entries: entries,
Shortcuts: s.browseShortcuts(),
})
}
// --- Listing ---
func (s *Server) listNotes(w http.ResponseWriter, _ *http.Request) {
notes, err := s.currentVault().ListNotes()
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, notes)
}
func (s *Server) listFolders(w http.ResponseWriter, _ *http.Request) {
folders, err := s.currentVault().ListFolders()
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, folders)
}
func (s *Server) listAssets(w http.ResponseWriter, _ *http.Request) {
assets, err := s.currentVault().ListAssets()
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, assets)
}
func (s *Server) assetsExists(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"exists": s.currentVault().HasAssetsDir()})
}
// --- Notes ---
func (s *Server) readNote(w http.ResponseWriter, r *http.Request) {
rel := r.URL.Query().Get("path")
if _, isMCP := r.Context().Value(mcpResponseLimitKey{}).(int64); isMCP {
size, err := s.currentVault().NoteSize(rel)
if err != nil {
writeError(w, err)
return
}
if tooLargeForMCP(w, r, size) {
return
}
}
note, err := s.currentVault().ReadNote(rel)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, note)
}
func (s *Server) readComments(w http.ResponseWriter, r *http.Request) {
rel := r.URL.Query().Get("path")
comments, err := s.currentVault().ReadNoteComments(rel)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, comments)
}
func (s *Server) writeComments(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
Comments []vault.NoteComment `json:"comments"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
comments, err := s.currentVault().WriteNoteComments(req.Path, req.Comments)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, comments)
}
func (s *Server) writeNote(w http.ResponseWriter, r *http.Request) {
cfg := s.currentConfig()
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxNoteBytes+jsonEnvelopeBytes)
var req struct {
Path string `json:"path"`
Body string `json:"body"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().WriteNote(req.Path, req.Body)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) createNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder vault.NoteFolder `json:"folder"`
Title string `json:"title"`
Subpath string `json:"subpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().CreateNote(req.Folder, req.Title, req.Subpath)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) createExcalidraw(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder vault.NoteFolder `json:"folder"`
Title string `json:"title"`
Subpath string `json:"subpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().CreateExcalidraw(req.Folder, req.Title, req.Subpath)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) renameNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
Title string `json:"title"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().RenameNote(req.Path, req.Title)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) deleteNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.currentVault().DeleteNote(req.Path); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) trashNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().MoveToTrash(req.Path)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) restoreNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().RestoreFromTrash(req.Path)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) emptyTrash(w http.ResponseWriter, _ *http.Request) {
if err := s.currentVault().EmptyTrash(); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) archiveNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().ArchiveNote(req.Path)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) unarchiveNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().UnarchiveNote(req.Path)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) duplicateNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().DuplicateNote(req.Path)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
func (s *Server) moveNote(w http.ResponseWriter, r *http.Request) {
var req struct {
Path string `json:"path"`
TargetFolder vault.NoteFolder `json:"targetFolder"`
TargetSubpath string `json:"targetSubpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
meta, err := s.currentVault().MoveNote(req.Path, req.TargetFolder, req.TargetSubpath)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, meta)
}
// --- Folders ---
func (s *Server) createFolder(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder vault.NoteFolder `json:"folder"`
Subpath string `json:"subpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.currentVault().CreateFolder(req.Folder, req.Subpath); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) renameFolder(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder vault.NoteFolder `json:"folder"`
OldSubpath string `json:"oldSubpath"`
NewSubpath string `json:"newSubpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
out, err := s.currentVault().RenameFolder(req.Folder, req.OldSubpath, req.NewSubpath)
if err != nil {
writeError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"subpath": out})
}
func (s *Server) deleteFolder(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder vault.NoteFolder `json:"folder"`
Subpath string `json:"subpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.currentVault().DeleteFolder(req.Folder, req.Subpath); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) duplicateFolder(w http.ResponseWriter, r *http.Request) {
var req struct {
Folder vault.NoteFolder `json:"folder"`
Subpath string `json:"subpath"`
}
if err := readJSON(r, &req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
out, err := s.currentVault().DuplicateFolder(req.Folder, req.Subpath)
if err != nil {
writeError(w, err)