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
|
package admin
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"thehouseoficarus/internal/persistence"
)
type ExtraFile struct {
FilePath string `json:"file_path"`
OldContent []byte `json:"-"`
NewContent []byte `json:"-"`
NewFilePath string `json:"new_file_path,omitempty"`
IsDelete bool `json:"is_delete,omitempty"`
IsCreate bool `json:"is_create,omitempty"`
IsDirDelete bool `json:"is_dir_delete,omitempty"`
}
type ChangeDesc struct {
Time string `json:"time"`
Description string `json:"description"`
FilePath string `json:"file_path"`
NewFilePath string `json:"new_file_path,omitempty"`
OldContent []byte `json:"old_content"`
NewContent []byte `json:"new_content"`
IsDelete bool `json:"is_delete"`
IsCreate bool `json:"is_create"`
IsDirDelete bool `json:"is_dir_delete,omitempty"`
ExtraFiles []ExtraFile `json:"extra_files,omitempty"`
// IDMap records a room-ID change (oldID -> newID) included in the
// change. Undo applies its inverse, redo the forward map, through the
// wired runtime migration so players, Hub membership, and casino room
// keys move back and forth with the file images.
IDMap map[int]int `json:"id_map,omitempty"`
}
func (c ChangeDesc) ShortDesc() string {
switch {
case c.IsCreate:
return fmt.Sprintf("Created %s", filepath.Base(c.FilePath))
case c.IsDelete:
return fmt.Sprintf("Deleted %s", filepath.Base(c.FilePath))
case c.NewFilePath != "":
if filepath.Dir(c.FilePath) == filepath.Dir(c.NewFilePath) {
return fmt.Sprintf("Renamed %s", filepath.Base(c.NewFilePath))
}
return fmt.Sprintf("Moved %s", filepath.Base(c.NewFilePath))
default:
return fmt.Sprintf("Edited %s", filepath.Base(c.FilePath))
}
}
type UndoInfo struct {
CanUndo bool `json:"can_undo"`
CanRedo bool `json:"can_redo"`
UndoDesc string `json:"undo_desc"`
RedoDesc string `json:"redo_desc"`
StackSize int `json:"stack_size"`
RedoSize int `json:"redo_size"`
}
// UndoStack protects history with a mutex, not live game state. Production
// callers must execute Push/Undo/Redo/Clear within the editor's owner task.
// Undo/Redo and the subsequent rebuildAfterUndo are one task, not separate
// dispatches; migrateRoomIDs is an owner-only callback.
type UndoStack struct {
mu sync.Mutex
dataDir string
history []ChangeDesc
redo []ChangeDesc
maxSize int
filePath string
// migrateRoomIDs applies a room-ID map to runtime state (players, Hub
// membership, casino room keys) during undo/redo of room-ID changes.
migrateRoomIDs func(map[int]int)
// playerFileOnlineCheck reports whether the character/account addressed
// by a data-relative player file path is currently online. undo/redo
// writes those files directly, so it must refuse the same files the raw
// file editor refuses. Optional; nil disables the refusal.
playerFileOnlineCheck func(relPath string) bool
// lastErr records the most recent Undo/Redo failure so the HTTP handler
// can distinguish a genuine failure from an empty history (both return a
// nil change). Owner-task access only.
lastErr error
}
func NewUndoStack(dataDir string) *UndoStack {
us := &UndoStack{
dataDir: dataDir,
maxSize: 100,
filePath: filepath.Join(dataDir, ".admin_history.json"),
}
us.load()
return us
}
// SetMigrateRoomIDs wires the runtime room-ID migration used by undo/redo
// of room-ID changes. Called by the server after construction.
func (us *UndoStack) SetMigrateRoomIDs(fn func(map[int]int)) {
us.mu.Lock()
defer us.mu.Unlock()
us.migrateRoomIDs = fn
}
// SetPlayerFileOnlineCheck wires the online-session check used by undo/redo to
// refuse touching a character/account file the game still owns. It takes the
// same data-relative path form as AdminServer.SetPlayerFileOnlineCheck, which
// passes its own hook through here.
func (us *UndoStack) SetPlayerFileOnlineCheck(fn func(relPath string) bool) {
us.mu.Lock()
defer us.mu.Unlock()
us.playerFileOnlineCheck = fn
}
// RewritePaths re-prefixes every stored history path under oldPrefix so a
// directory rename does not leave stale absolute paths behind. Without this
// a later undo recreates the old directory and writes a duplicate file while
// the live file stays in the new directory. newPrefix may be empty to leave
// paths untouched.
func (us *UndoStack) RewritePaths(oldPrefix, newPrefix string) {
if oldPrefix == "" || newPrefix == "" || oldPrefix == newPrefix {
return
}
us.mu.Lock()
defer us.mu.Unlock()
sep := string(os.PathSeparator)
rewrite := func(p string) string {
if p == "" {
return p
}
if p == oldPrefix {
return newPrefix
}
if strings.HasPrefix(p, oldPrefix+sep) {
return filepath.Join(newPrefix, strings.TrimPrefix(p, oldPrefix+sep))
}
return p
}
rewriteDesc := func(c *ChangeDesc) {
c.FilePath = rewrite(c.FilePath)
c.NewFilePath = rewrite(c.NewFilePath)
for i := range c.ExtraFiles {
c.ExtraFiles[i].FilePath = rewrite(c.ExtraFiles[i].FilePath)
c.ExtraFiles[i].NewFilePath = rewrite(c.ExtraFiles[i].NewFilePath)
}
}
for i := range us.history {
rewriteDesc(&us.history[i])
}
for i := range us.redo {
rewriteDesc(&us.redo[i])
}
us.save()
}
func (us *UndoStack) Push(desc ChangeDesc) {
us.mu.Lock()
defer us.mu.Unlock()
desc.Time = time.Now().Format(time.RFC3339)
us.history = append(us.history, desc)
us.redo = nil
if len(us.history) > us.maxSize {
us.history = us.history[len(us.history)-us.maxSize:]
}
us.save()
log.Printf("undo: push %s", desc.ShortDesc())
}
func (us *UndoStack) Undo() *ChangeDesc {
us.mu.Lock()
defer us.mu.Unlock()
if len(us.history) == 0 {
return nil
}
last := us.history[len(us.history)-1]
if err := us.applyUndo(last); err != nil {
log.Printf("undo: failed %s: %v", last.ShortDesc(), err)
us.lastErr = err
return nil
}
us.lastErr = nil
// Runtime migration moves with the file images: undo applies the
// inverse room-ID map so players, Hub membership, and casino room keys
// return to the old location together.
if len(last.IDMap) > 0 && us.migrateRoomIDs != nil {
inverse := make(map[int]int, len(last.IDMap))
for from, to := range last.IDMap {
inverse[to] = from
}
us.migrateRoomIDs(inverse)
}
us.history = us.history[:len(us.history)-1]
us.redo = append(us.redo, last)
us.save()
log.Printf("undo: undid %s", last.ShortDesc())
return &last
}
func (us *UndoStack) Redo() *ChangeDesc {
us.mu.Lock()
defer us.mu.Unlock()
if len(us.redo) == 0 {
return nil
}
last := us.redo[len(us.redo)-1]
if err := us.applyRedo(last); err != nil {
log.Printf("redo: failed %s: %v", last.ShortDesc(), err)
us.lastErr = err
return nil
}
us.lastErr = nil
// Redo applies the forward room-ID map through the runtime migration.
if len(last.IDMap) > 0 && us.migrateRoomIDs != nil {
forward := make(map[int]int, len(last.IDMap))
for from, to := range last.IDMap {
forward[from] = to
}
us.migrateRoomIDs(forward)
}
us.redo = us.redo[:len(us.redo)-1]
us.history = append(us.history, last)
us.save()
log.Printf("redo: redid %s", last.ShortDesc())
return &last
}
// requireSnapshot rejects a nil before/after image on a change that must
// restore real content. A failed before-image read leaves nil, and writing
// it would truncate the file to zero bytes (which parses as a zero-value
// def), so a missing image must fail the undo/redo instead.
func requireSnapshot(content []byte, path, action string) error {
if content == nil {
return fmt.Errorf("%s %s: no snapshot recorded", action, path)
}
return nil
}
// applyUndo reverts a change: the primary file, then every extra file.
// Extra-file failures propagate: a multi-file undo that restored only part
// of a change must be reported as failed, never as success.
func (us *UndoStack) applyUndo(c ChangeDesc) error {
if err := us.checkPlayerFilesOffline(c); err != nil {
return err
}
// Resolve every secret-bearing image BEFORE touching the filesystem: the
// rename path below removes its target before the restored file is
// written, so a redacted history image that cannot be repaired must fail
// while both files are still intact.
restored, err := us.restoreSecret(c.OldContent, c.FilePath, c.NewFilePath)
if err != nil {
return err
}
for _, ef := range c.ExtraFiles {
if _, err := us.restoreSecret(ef.OldContent, ef.FilePath, ef.NewFilePath); err != nil {
return fmt.Errorf("undo restore %s: %w", ef.FilePath, err)
}
}
if c.NewFilePath != "" {
if err := os.Remove(c.NewFilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove %s: %w", c.NewFilePath, err)
}
}
if c.IsDelete {
if c.IsDirDelete {
if err := os.MkdirAll(c.FilePath, 0755); err != nil {
return fmt.Errorf("recreate dir %s: %w", c.FilePath, err)
}
} else {
if c.OldContent == nil {
return fmt.Errorf("restore deleted %s: no snapshot recorded", c.FilePath)
}
if err := us.writeSnapshot(c.FilePath, restored); err != nil {
return fmt.Errorf("restore deleted %s: %w", c.FilePath, err)
}
}
} else if c.IsCreate {
if err := os.Remove(c.FilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove created %s: %w", c.FilePath, err)
}
} else {
if err := requireSnapshot(c.OldContent, c.FilePath, "revert"); err != nil {
return err
}
if err := us.writeSnapshot(c.FilePath, restored); err != nil {
return fmt.Errorf("revert %s: %w", c.FilePath, err)
}
}
for _, ef := range c.ExtraFiles {
if err := us.applyUndoExtraFile(ef); err != nil {
return err
}
}
return nil
}
// applyRedo re-applies a change: the primary file, then every extra file.
// Extra-file failures propagate like undo.
func (us *UndoStack) applyRedo(c ChangeDesc) error {
if err := us.checkPlayerFilesOffline(c); err != nil {
return err
}
// See applyUndo: every image's secret is resolved before any file is
// removed, so a redacted image fails the redo without destroying either
// end of a rename.
restored, err := us.restoreSecret(c.NewContent, c.NewFilePath, c.FilePath)
if err != nil {
return err
}
for _, ef := range c.ExtraFiles {
if _, err := us.restoreSecret(ef.NewContent, ef.NewFilePath, ef.FilePath); err != nil {
return fmt.Errorf("redo restore %s: %w", ef.FilePath, err)
}
}
if c.NewFilePath != "" {
if err := os.Remove(c.FilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove %s: %w", c.FilePath, err)
}
}
if c.IsCreate {
target := c.FilePath
if c.NewFilePath != "" {
target = c.NewFilePath
}
if err := us.writeSnapshot(target, restored); err != nil {
return fmt.Errorf("recreate %s: %w", target, err)
}
for _, ef := range c.ExtraFiles {
if err := us.applyRedoExtraFile(ef); err != nil {
return err
}
}
} else if c.IsDelete {
if err := os.Remove(c.FilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("re-delete %s: %w", c.FilePath, err)
}
for _, ef := range c.ExtraFiles {
if err := us.applyRedoExtraFile(ef); err != nil {
return err
}
}
} else {
target := c.FilePath
if c.NewFilePath != "" {
target = c.NewFilePath
}
if err := requireSnapshot(c.NewContent, target, "reapply"); err != nil {
return err
}
if err := us.writeSnapshot(target, restored); err != nil {
return fmt.Errorf("reapply %s: %w", target, err)
}
for _, ef := range c.ExtraFiles {
if err := us.applyRedoExtraFile(ef); err != nil {
return err
}
}
}
return nil
}
func (us *UndoStack) applyUndoExtraFile(ef ExtraFile) error {
switch {
case ef.IsCreate:
if err := os.Remove(ef.FilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("undo remove %s: %w", ef.FilePath, err)
}
case ef.IsDelete && ef.IsDirDelete:
if err := os.MkdirAll(ef.FilePath, 0755); err != nil {
return fmt.Errorf("undo mkdir: %w", err)
}
case ef.IsDelete:
if ef.OldContent == nil {
return fmt.Errorf("undo restore %s: no snapshot recorded", ef.FilePath)
}
if err := us.writeRestored(ef.FilePath, ef.OldContent, ef.NewFilePath); err != nil {
return fmt.Errorf("undo restore %s: %w", ef.FilePath, err)
}
case ef.NewFilePath != "":
if err := requireSnapshot(ef.OldContent, ef.FilePath, "undo restore"); err != nil {
return err
}
if err := os.Remove(ef.NewFilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("undo remove %s: %w", ef.NewFilePath, err)
}
if err := us.writeRestored(ef.FilePath, ef.OldContent, ef.NewFilePath); err != nil {
return fmt.Errorf("undo restore %s: %w", ef.FilePath, err)
}
default:
if err := requireSnapshot(ef.OldContent, ef.FilePath, "undo revert"); err != nil {
return err
}
if err := us.writeRestored(ef.FilePath, ef.OldContent); err != nil {
return fmt.Errorf("undo revert %s: %w", ef.FilePath, err)
}
}
return nil
}
func (us *UndoStack) applyRedoExtraFile(ef ExtraFile) error {
switch {
case ef.IsDelete:
if err := os.Remove(ef.FilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("redo remove %s: %w", ef.FilePath, err)
}
case ef.IsCreate:
if err := us.writeRestored(ef.FilePath, ef.NewContent, ef.NewFilePath); err != nil {
return fmt.Errorf("redo create %s: %w", ef.FilePath, err)
}
case ef.NewFilePath != "":
if err := requireSnapshot(ef.NewContent, ef.NewFilePath, "redo create"); err != nil {
return err
}
if err := os.Remove(ef.FilePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("redo remove %s: %w", ef.FilePath, err)
}
if err := us.writeRestored(ef.NewFilePath, ef.NewContent, ef.FilePath); err != nil {
return fmt.Errorf("redo create %s: %w", ef.NewFilePath, err)
}
default:
if err := requireSnapshot(ef.NewContent, ef.FilePath, "redo reapply"); err != nil {
return err
}
if err := us.writeRestored(ef.FilePath, ef.NewContent); err != nil {
return fmt.Errorf("redo reapply %s: %w", ef.FilePath, err)
}
}
return nil
}
// writeRestored writes content to path after merging the live on-disk player
// secret back into it (see restoreSecret). A history image whose secret was
// redacted and has no live file left to take it from fails here instead of
// being written, so undo/redo reports the failure. Further paths are the
// change's counterparts (a rename's other end).
func (us *UndoStack) writeRestored(path string, content []byte, others ...string) error {
restored, err := us.restoreSecret(content, append([]string{path}, others...)...)
if err != nil {
return err
}
return us.writeSnapshot(path, restored)
}
// checkPlayerFilesOffline refuses an undo/redo touching a character/account
// file whose owner is online. The raw file editor refuses those files before
// writing them; undo/redo writes them through this stack, so it must refuse
// them too or a live character can be clobbered behind the editor's back.
func (us *UndoStack) checkPlayerFilesOffline(c ChangeDesc) error {
if us.playerFileOnlineCheck == nil {
return nil
}
for _, p := range changePaths(c) {
rel, ok := us.playerDataRelPath(p)
if !ok {
continue
}
if us.playerFileOnlineCheck(rel) {
return fmt.Errorf("%s is online; it must be logged out before this change can be undone or redone", rel)
}
}
return nil
}
// changePaths lists every file a change touches: the primary path, a rename's
// new path, and every extra file with its own new path.
func changePaths(c ChangeDesc) []string {
paths := []string{c.FilePath, c.NewFilePath}
for _, ef := range c.ExtraFiles {
paths = append(paths, ef.FilePath, ef.NewFilePath)
}
return paths
}
// writeSnapshot writes content to path, creating the parent directory and
// choosing the file mode from the path: player/account files are owner-only.
func (us *UndoStack) writeSnapshot(path string, content []byte) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
// Atomic temp+fsync+rename: a crash mid-undo must never leave a
// truncated world file (empty YAML parses as a zero-value def).
if err := persistence.WriteFile(path, content, us.fileMode(path)); err != nil {
return err
}
if us.isPlayerDataPath(path) {
// Tighten a file that was created world-readable before this fix.
if err := os.Chmod(path, 0600); err != nil {
return err
}
}
return nil
}
// fileMode returns the mode an undo/redo write should use for path.
func (us *UndoStack) fileMode(path string) os.FileMode {
if us.isPlayerDataPath(path) {
return 0600
}
return 0644
}
// isPlayerDataPath reports whether path is an account or character file under
// the data directory. These carry the password hash and live player state.
func (us *UndoStack) isPlayerDataPath(path string) bool {
_, ok := us.playerDataRelPath(path)
return ok
}
// playerDataRelPath returns the data-relative, slash-separated form of path
// when it is an account or character file, which is the form the game's
// online-session check (AdminPlayerFileOnline) accepts.
func (us *UndoStack) playerDataRelPath(path string) (string, bool) {
if path == "" {
return "", false
}
rel, err := filepath.Rel(us.dataDir, path)
if err != nil {
return "", false
}
rel = filepath.ToSlash(rel)
if strings.HasPrefix(rel, "players/accounts/") || strings.HasPrefix(rel, "players/characters/") {
return rel, true
}
return "", false
}
func (us *UndoStack) Info() UndoInfo {
us.mu.Lock()
defer us.mu.Unlock()
info := UndoInfo{
StackSize: len(us.history),
RedoSize: len(us.redo),
}
if len(us.history) > 0 {
info.CanUndo = true
info.UndoDesc = us.history[len(us.history)-1].ShortDesc()
}
if len(us.redo) > 0 {
info.CanRedo = true
info.RedoDesc = us.redo[len(us.redo)-1].ShortDesc()
}
return info
}
// undoExtraEntry and undoEntry are the persisted undo/redo wire types. They
// are declared ONCE and shared by save and load: when each function declared
// its own copy, a field added to one and not the other silently dropped
// persisted history on the next restart.
type undoExtraEntry struct {
FilePath string `json:"file_path"`
NewFilePath string `json:"new_file_path,omitempty"`
OldContent string `json:"old_content"`
NewContent string `json:"new_content"`
IsDelete bool `json:"is_delete,omitempty"`
IsCreate bool `json:"is_create,omitempty"`
IsDirDelete bool `json:"is_dir_delete,omitempty"`
}
type undoEntry struct {
Time string `json:"time"`
Description string `json:"description"`
FilePath string `json:"file_path"`
NewFilePath string `json:"new_file_path,omitempty"`
OldContent string `json:"old_content"`
NewContent string `json:"new_content"`
IsDelete bool `json:"is_delete"`
IsCreate bool `json:"is_create"`
IsDirDelete bool `json:"is_dir_delete,omitempty"`
ExtraFiles []undoExtraEntry `json:"extra_files,omitempty"`
IDMap map[int]int `json:"id_map,omitempty"`
}
type undoFile struct {
History []undoEntry `json:"history"`
Redo []undoEntry `json:"redo"`
}
func (us *UndoStack) save() {
toEntries := func(changes []ChangeDesc) []undoEntry {
var entries []undoEntry
for _, c := range changes {
var extra []undoExtraEntry
for _, ef := range c.ExtraFiles {
extra = append(extra, undoExtraEntry{
FilePath: ef.FilePath,
NewFilePath: ef.NewFilePath,
OldContent: string(us.redactContent(ef.OldContent, ef.FilePath, ef.NewFilePath)),
NewContent: string(us.redactContent(ef.NewContent, ef.FilePath, ef.NewFilePath)),
IsDelete: ef.IsDelete,
IsCreate: ef.IsCreate,
IsDirDelete: ef.IsDirDelete,
})
}
entries = append(entries, undoEntry{
Time: c.Time,
Description: c.Description,
FilePath: c.FilePath,
NewFilePath: c.NewFilePath,
OldContent: string(us.redactContent(c.OldContent, c.FilePath, c.NewFilePath)),
NewContent: string(us.redactContent(c.NewContent, c.FilePath, c.NewFilePath)),
IsDelete: c.IsDelete,
IsCreate: c.IsCreate,
IsDirDelete: c.IsDirDelete,
ExtraFiles: extra,
IDMap: c.IDMap,
})
}
return entries
}
data := undoFile{
History: toEntries(us.history),
Redo: toEntries(us.redo),
}
b, err := json.Marshal(data)
if err != nil {
log.Printf("undo: failed to marshal history: %v", err)
return
}
if err := persistence.WriteFile(us.filePath, b, 0600); err != nil {
log.Printf("undo: failed to write history file: %v", err)
return
}
// persistence.WriteFile preserves an existing file's mode: tighten a
// history file that a previous version created world-readable.
if err := os.Chmod(us.filePath, 0600); err != nil {
log.Printf("undo: failed to secure history file: %v", err)
}
}
// playerSecretKeys are the top-level YAML keys whose values must never be
// written to the on-disk undo history. Account password hashes are the
// primary case: the raw file editor exposes account files and an unredacted
// history file would leak every hash to any local reader (and be stageable
// into the repository).
var playerSecretKeys = []string{"password_hash"}
// redactContent replaces secret values with a placeholder before the content
// is serialized into the history file. The in-memory ChangeDesc keeps the
// real bytes; only the persisted copy is redacted. A redacted value cannot
// restore a deleted account's hash across a restart, which is an accepted
// trade for never storing credentials in the history.
func (us *UndoStack) redactContent(content []byte, paths ...string) []byte {
if content == nil {
return nil
}
for _, p := range paths {
if us.isPlayerDataPath(p) {
return redactPlayerSecrets(content)
}
}
return content
}
// redactPlayerSecrets replaces every known secret value in a player/account
// document with the editor's placeholder, returning content unchanged when
// the document does not parse or carries no secret.
func redactPlayerSecrets(content []byte) []byte {
m, err := yamlToMap(content)
if err != nil {
return content
}
changed := false
for _, key := range playerSecretKeys {
if _, ok := m[key]; ok {
m[key] = redactedAccountHash
changed = true
}
}
if !changed {
return content
}
out, err := marshalMapYAML(m)
if err != nil {
return content
}
return out
}
// restoreSecret merges the live on-disk password hash into content before an
// undo/redo overwrites an account file, so a hash that was redacted in the
// persisted history can never blank a live account after a restart. It looks
// at the primary target path and then the change's other path (a rename).
//
// When no path holds a live hash and content still carries the redaction
// placeholder, it returns an error: writing the placeholder would replace the
// account's real hash and lock both the owner and the raw editor out of it
// permanently, so undo/redo must report the failure instead of overwriting.
func (us *UndoStack) restoreSecret(content []byte, paths ...string) ([]byte, error) {
if content == nil {
return nil, nil
}
playerFile := false
for _, p := range paths {
if us.isPlayerDataPath(p) {
playerFile = true
break
}
}
if !playerFile {
return content, nil
}
cm, err := yamlToMap(content)
if err != nil {
return content, nil
}
hash, ok := cm["password_hash"]
if !ok {
return content, nil
}
for _, p := range paths {
if !us.isPlayerDataPath(p) {
continue
}
existing, err := os.ReadFile(p)
if err != nil {
continue
}
em, err := yamlToMap(existing)
if err != nil {
continue
}
live, ok := em["password_hash"]
if !ok {
continue
}
cm["password_hash"] = live
out, err := marshalMapYAML(cm)
if err != nil {
return content, nil
}
return out, nil
}
if fmt.Sprint(hash) == redactedAccountHash {
return nil, fmt.Errorf("the stored history image has a redacted password hash and no live account file to take it from")
}
return content, nil
}
// load restores persisted undo/redo history written by save. A missing or
// unreadable history file is not fatal: the stack simply starts empty. The
// editor documents that history survives restarts, so NewUndoStack calls this.
func (us *UndoStack) load() {
data, err := os.ReadFile(us.filePath)
if err != nil {
return
}
var sd undoFile
if err := json.Unmarshal(data, &sd); err != nil {
log.Printf("undo: failed to load history: %v", err)
return
}
toChanges := func(entries []undoEntry) []ChangeDesc {
out := make([]ChangeDesc, 0, len(entries))
for _, e := range entries {
// A before-image recorded as nil is persisted as "" and would
// reload as a non-nil empty slice, defeating requireSnapshot and
// letting undo truncate the file to zero bytes. Map it back to nil
// so the guard fires. An intentionally empty before-image is also
// refused, which is safer than zeroing a live file.
oldContent := []byte(e.OldContent)
if e.OldContent == "" {
oldContent = nil
}
c := ChangeDesc{
Time: e.Time,
Description: e.Description,
FilePath: e.FilePath,
NewFilePath: e.NewFilePath,
OldContent: oldContent,
NewContent: []byte(e.NewContent),
IsDelete: e.IsDelete,
IsCreate: e.IsCreate,
IsDirDelete: e.IsDirDelete,
IDMap: e.IDMap,
}
for _, ef := range e.ExtraFiles {
oldExtra := []byte(ef.OldContent)
if ef.OldContent == "" {
oldExtra = nil
}
c.ExtraFiles = append(c.ExtraFiles, ExtraFile{
FilePath: ef.FilePath,
NewFilePath: ef.NewFilePath,
OldContent: oldExtra,
NewContent: []byte(ef.NewContent),
IsDelete: ef.IsDelete,
IsCreate: ef.IsCreate,
IsDirDelete: ef.IsDirDelete,
})
}
out = append(out, c)
}
return out
}
us.history = toChanges(sd.History)
us.redo = toChanges(sd.Redo)
}
func (us *UndoStack) Clear() {
us.mu.Lock()
defer us.mu.Unlock()
us.history = nil
us.redo = nil
us.lastErr = nil
os.Remove(us.filePath)
log.Printf("undo: cleared history")
}
// LastError returns the error from the most recent failed Undo/Redo, or nil.
// A nil change plus a nil LastError means the history/redo stack was empty.
func (us *UndoStack) LastError() error {
us.mu.Lock()
defer us.mu.Unlock()
return us.lastErr
}
|