aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/server.go
blob: 12d090d5eec24578a10325b83d6c262ff32641b9 (plain)
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
// Package admin implements the HTTP admin server: authenticated routes for
// editing game data (rooms, items, mobs, drops, triggers, colors, …), the
// embedded web UI, and the undo stack backing it.
package admin

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"embed"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"io/fs"
	"log"
	"math/big"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"thehouseoficarus/internal/behavior"
	"thehouseoficarus/internal/config"
	"thehouseoficarus/internal/item"
	"thehouseoficarus/internal/object"
	"thehouseoficarus/internal/player"
	"thehouseoficarus/internal/world"
)

//go:embed templates static
var embedded embed.FS

type AdminServer struct {
	cfg           *config.Config
	useTLS        bool
	accountStore  *player.AccountStore
	world         *world.World
	itemStore     *item.ItemStore
	objectStore   *object.ObjectStore
	mobStore      *world.MobStore
	dataDir       string
	httpServer    *http.Server
	undoStack     *UndoStack
	tmpl          *template.Template
	cookieSecret  []byte
	reloadCourses func()
	// runOnOwner synchronously executes an API task, or returns false when
	// the game is shutting down. All runtime callbacks below run INSIDE
	// that task and must not dispatch to the owner again.
	runOnOwner func(func()) bool
	// rewriteRoomIDs migrates room-ID-embedded state across all characters
	// (online + offline) when a room ID changes. Wired from the Game so the
	// admin web GUI can trigger the same migration as the swapid command
	// without the admin package depending on game.
	rewriteRoomIDs func(idMap map[int]int)
	// configPath is the on-disk config.yaml path, used by the color themer
	// to persist edited default_colors back to the file the game loaded.
	configPath string
	// evictRoom evicts cached in-room games (tables/machines) when a room
	// is deleted or renumbered: outstanding wagers are refunded through the
	// wired game callback before the cache entries drop.
	evictRoom func(roomID int)

	// rebuildCraftIndex rebuilds the in-game craft index after item files
	// change (create/update/delete/rename/move/undo/redo). Wired from the
	// Game so the web editor's item edits stay consistent with gameplay.
	rebuildCraftIndex func()
}

func NewServer(cfg *config.Config, useTLS bool, accountStore *player.AccountStore, w *world.World, is *item.ItemStore, os *object.ObjectStore, ms *world.MobStore, dataDir string, reloadCourses func(), rewriteRoomIDs func(map[int]int), evictRoom func(roomID int), rebuildCraftIndex func(), configPath string, runOnOwner func(func()) bool) (*AdminServer, error) {
	if runOnOwner == nil {
		return nil, fmt.Errorf("admin server requires an owner dispatcher")
	}
	secret := make([]byte, 32)
	if _, err := rand.Read(secret); err != nil {
		return nil, fmt.Errorf("cookie secret: %w", err)
	}

	tmpl, err := template.New("").Funcs(template.FuncMap{
		"json": func(v any) string {
			b, _ := json.Marshal(v)
			return string(b)
		},
	}).ParseFS(embedded, "templates/*.html")
	if err != nil {
		return nil, fmt.Errorf("parse templates: %w", err)
	}

	var port int
	if useTLS {
		port = cfg.AdminHTTPS.Port
	} else {
		port = cfg.AdminHTTP.Port
	}

	var cert tls.Certificate
	if useTLS {
		cert, err = loadOrGenerateCert(cfg)
		if err != nil {
			return nil, fmt.Errorf("admin cert: %w", err)
		}
	}

	s := &AdminServer{
		cfg:               cfg,
		useTLS:            useTLS,
		accountStore:      accountStore,
		world:             w,
		itemStore:         is,
		objectStore:       os,
		mobStore:          ms,
		dataDir:           dataDir,
		undoStack:         NewUndoStack(dataDir),
		tmpl:              tmpl,
		cookieSecret:      secret,
		reloadCourses:     reloadCourses,
		rewriteRoomIDs:    rewriteRoomIDs,
		evictRoom:         evictRoom,
		rebuildCraftIndex: rebuildCraftIndex,
		configPath:        configPath,
		runOnOwner:        runOnOwner,
	}
	// Undo/redo of room-ID changes applies the (inverse) runtime migration
	// through the same wired callback the rename uses.
	s.undoStack.SetMigrateRoomIDs(rewriteRoomIDs)

	mux := http.NewServeMux()

	staticFS, err := fs.Sub(embedded, "static")
	if err != nil {
		return nil, fmt.Errorf("static subfs: %w", err)
	}
	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))

	mux.HandleFunc("/login", s.handleLogin)
	mux.HandleFunc("/logout", s.handleLogout)

	apiMux := http.NewServeMux()
	apiMux.HandleFunc("/api/map", s.handleMap)
	apiMux.HandleFunc("/api/room-dirs", s.handleRoomDirs)
	apiMux.HandleFunc("/api/room-dirs/rename", s.handleRenameRoomDir)
	apiMux.HandleFunc("/api/room-dirs/create", s.handleCreateRoomDir)
	apiMux.HandleFunc("/api/rooms/link", s.handleRoomLink)
	apiMux.HandleFunc("/api/rooms/insert", s.handleRoomInsert)
	apiMux.HandleFunc("/api/rooms/remove", s.handleRoomRemove)
	apiMux.HandleFunc("/api/rooms/move", s.handleRoomMove)
	apiMux.HandleFunc("/api/rooms/rename", s.handleRoomRename)
	apiMux.HandleFunc("/api/rooms/swap", s.handleRoomSwap)
	apiMux.HandleFunc("/api/rooms/bulk-edit", s.handleBulkEdit)
	apiMux.HandleFunc("/api/rooms/bulk-delete", s.handleBulkDelete)
	apiMux.HandleFunc("/api/rooms", s.handleRooms)
	apiMux.HandleFunc("/api/rooms/new-empty", s.handleCreateEmptyRoom)
	apiMux.HandleFunc("/api/rooms/", s.handleRoomByID)
	apiMux.HandleFunc("/api/objects/rename", s.handleEntityRename("objects"))
	apiMux.HandleFunc("/api/objects/move", s.handleEntityMove("objects"))
	apiMux.HandleFunc("/api/objects/dirs", s.handleEntityDirs("objects"))
	apiMux.HandleFunc("/api/objects", s.handleObjects)
	apiMux.HandleFunc("/api/objects/", s.handleObjectByID)
	apiMux.HandleFunc("/api/items/rename", s.handleEntityRename("items"))
	apiMux.HandleFunc("/api/items/move", s.handleEntityMove("items"))
	apiMux.HandleFunc("/api/items/dirs", s.handleEntityDirs("items"))
	apiMux.HandleFunc("/api/items", s.handleItems)
	apiMux.HandleFunc("/api/items/", s.handleItemByID)
	apiMux.HandleFunc("/api/mobs/rename", s.handleEntityRename("mobs"))
	apiMux.HandleFunc("/api/mobs/move", s.handleEntityMove("mobs"))
	apiMux.HandleFunc("/api/mobs/dirs", s.handleEntityDirs("mobs"))
	apiMux.HandleFunc("/api/mobs", s.handleMobs)
	apiMux.HandleFunc("/api/mobs/", s.handleMobByID)
	apiMux.HandleFunc("/api/drops/rename", s.handleEntityRename("drops"))
	apiMux.HandleFunc("/api/drops/move", s.handleEntityMove("drops"))
	apiMux.HandleFunc("/api/drops/dirs", s.handleEntityDirs("drops"))
	apiMux.HandleFunc("/api/drops", s.handleDrops)
	apiMux.HandleFunc("/api/drops/", s.handleDropByID)
	apiMux.HandleFunc("/api/hazards/rename", s.handleEntityRename("hazards"))
	apiMux.HandleFunc("/api/hazards/move", s.handleEntityMove("hazards"))
	apiMux.HandleFunc("/api/hazards/dirs", s.handleEntityDirs("hazards"))
	apiMux.HandleFunc("/api/hazards", s.handleHazards)
	apiMux.HandleFunc("/api/hazards/", s.handleHazardByID)
	apiMux.HandleFunc("/api/techs/rename", s.handleEntityRename("techs"))
	apiMux.HandleFunc("/api/techs/move", s.handleEntityMove("techs"))
	apiMux.HandleFunc("/api/techs/dirs", s.handleEntityDirs("techs"))
	apiMux.HandleFunc("/api/techs", s.handleTechs)
	apiMux.HandleFunc("/api/techs/", s.handleTechByID)
	apiMux.HandleFunc("/api/modules/rename", s.handleEntityRename("modules"))
	apiMux.HandleFunc("/api/modules/move", s.handleEntityMove("modules"))
	apiMux.HandleFunc("/api/modules/dirs", s.handleEntityDirs("modules"))
	apiMux.HandleFunc("/api/modules", s.handleModules)
	apiMux.HandleFunc("/api/modules/", s.handleModuleByID)
	apiMux.HandleFunc("/api/courses", s.handleCourses)
	apiMux.HandleFunc("/api/courses/", s.handleCourseByID)
	apiMux.HandleFunc("/api/players", s.handlePlayers)
	apiMux.HandleFunc("/api/players/", s.handlePlayerByID)
	apiMux.HandleFunc("/api/dashboard", s.handleDashboard)
	apiMux.HandleFunc("/api/global_flags", s.handleGlobalFlags)
	apiMux.HandleFunc("/api/tools", s.handleTools)
	apiMux.HandleFunc("/api/stations", s.handleStations)
	apiMux.HandleFunc("/api/search", s.handleSearch)
	apiMux.HandleFunc("/api/undo/state", s.handleUndoState)
	apiMux.HandleFunc("/api/undo/undo", s.doUndo)
	apiMux.HandleFunc("/api/undo/redo", s.doRedo)
	apiMux.HandleFunc("/api/next-room-id", s.handleNextRoomID)
	apiMux.HandleFunc("/api/files", s.handleFiles)
	apiMux.HandleFunc("/api/files/rename", s.handleFileRename)
	apiMux.HandleFunc("/api/duplicate-rooms", s.handleDuplicateRooms)
	apiMux.HandleFunc("/api/rooms/resolve-duplicate", s.handleResolveDuplicate)
	apiMux.HandleFunc("/api/triggers", s.handleTriggers)
	apiMux.HandleFunc("/api/triggers/", s.handleTriggerByID)
	apiMux.HandleFunc("/api/colors", s.handleColors)
	apiMux.HandleFunc("/api/colors/reset", s.handleColorsReset)

	mux.Handle("/api/", s.authMiddleware(s.ownerMiddleware(apiMux)))

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if !s.checkAuth(r) {
			http.Redirect(w, r, "/login", http.StatusFound)
			return
		}
		page := strings.TrimPrefix(r.URL.Path, "/")
		if page == "" {
			page = "map"
		}
		if page == "map" {
			dups := behavior.CheckDuplicateIDs(filepath.Join(s.dataDir, "rooms"))
			if len(dups) > 0 {
				data := map[string]any{
					"Account":   s.accountFromCookie(r),
					"UndoStack": s.undoStack.Info(),
					"Page":      "duplicate-rooms",
				}
				s.renderPage(w, r, "layout", data)
				return
			}
		}
		data := map[string]any{
			"Account":   s.accountFromCookie(r),
			"UndoStack": s.undoStack.Info(),
			"Page":      page,
		}
		s.renderPage(w, r, "layout", data)
	})

	mux.HandleFunc("/editor/", func(w http.ResponseWriter, r *http.Request) {
		if !s.checkAuth(r) {
			http.Redirect(w, r, "/login", http.StatusFound)
			return
		}
		page := strings.TrimPrefix(r.URL.Path, "/editor/")
		if page == "map" {
			dups := behavior.CheckDuplicateIDs(filepath.Join(s.dataDir, "rooms"))
			if len(dups) > 0 {
				data := map[string]any{
					"Account":   s.accountFromCookie(r),
					"UndoStack": s.undoStack.Info(),
					"Page":      "duplicate-rooms",
				}
				s.renderPage(w, r, "layout", data)
				return
			}
		}
		data := map[string]any{
			"Account":   s.accountFromCookie(r),
			"UndoStack": s.undoStack.Info(),
			"Page":      page,
		}
		s.renderPage(w, r, "layout", data)
	})

	s.httpServer = &http.Server{
		Addr:              fmt.Sprintf(":%d", port),
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       30 * time.Second,
		WriteTimeout:      60 * time.Second,
		IdleTimeout:       60 * time.Second,
	}
	if useTLS {
		s.httpServer.TLSConfig = &tls.Config{
			Certificates: []tls.Certificate{cert},
			MinVersion:   tls.VersionTLS12,
		}
	}

	return s, nil
}

// ServeHTTP exposes the same authenticated routes used by ListenAndServe.
func (s *AdminServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.httpServer.Handler.ServeHTTP(w, r)
}

func (s *AdminServer) ListenAndServe() error {
	ln, err := net.Listen("tcp", s.httpServer.Addr)
	if err != nil {
		return fmt.Errorf("admin listen: %w", err)
	}
	if s.useTLS {
		tlsLn := tls.NewListener(ln, s.httpServer.TLSConfig)
		return s.httpServer.Serve(tlsLn)
	}
	return s.httpServer.Serve(ln)
}

func (s *AdminServer) authMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !s.checkAuth(r) {
			http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func (s *AdminServer) checkAuth(r *http.Request) bool {
	cookie, err := r.Cookie("admin_session")
	if err != nil {
		return false
	}
	parts := strings.SplitN(cookie.Value, ":", 2)
	if len(parts) != 2 {
		return false
	}
	account := parts[0]
	sig := parts[1]

	if !s.isAdminAccount(account) {
		return false
	}

	mac := hmac.New(sha256.New, s.cookieSecret)
	mac.Write([]byte(account))
	expected := hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(sig), []byte(expected))
}

func (s *AdminServer) isAdminAccount(name string) bool {
	acc, err := s.accountStore.LoadAccount(name)
	if err != nil {
		return false
	}
	return acc.Admin
}

func (s *AdminServer) setAuthCookie(w http.ResponseWriter, account string) {
	mac := hmac.New(sha256.New, s.cookieSecret)
	mac.Write([]byte(account))
	sig := hex.EncodeToString(mac.Sum(nil))
	http.SetCookie(w, &http.Cookie{
		Name:     "admin_session",
		Value:    account + ":" + sig,
		Path:     "/",
		HttpOnly: true,
		Secure:   s.useTLS,
		SameSite: http.SameSiteStrictMode,
		MaxAge:   86400,
	})
}

func (s *AdminServer) handleLogin(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet {
		data := map[string]any{}
		s.renderPage(w, r, "login.html", data)
		return
	}
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	account := strings.TrimSpace(r.FormValue("account"))
	password := r.FormValue("password")

	acc, err := s.accountStore.LoadAccount(account)
	if err != nil || !player.CheckPassword(password, acc.PasswordHash) {
		s.renderPage(w, r, "login.html", map[string]any{"Error": "Invalid account name or password."})
		return
	}

	if !acc.Admin {
		s.renderPage(w, r, "login.html", map[string]any{"Error": "Account is not authorized as admin."})
		return
	}

	// Expensive password hashing stays off the owner. Reload the account
	// inside the task so an upgrade cannot overwrite a concurrent character
	// rename/create or a password/admin change made since authentication.
	var upgradedHash string
	if player.NeedsRehash(acc.PasswordHash) {
		upgradedHash, _ = player.HashPassword(password)
	}
	authorized := false
	if !s.runOnOwner(func() {
		current, err := s.accountStore.LoadAccount(account)
		if err != nil || !current.Admin || current.PasswordHash != acc.PasswordHash {
			return
		}
		authorized = true
		if upgradedHash != "" {
			current.PasswordHash = upgradedHash
			if err := s.accountStore.SaveAccount(current); err != nil {
				log.Printf("admin login: password rehash save for %s: %v", account, err)
			}
		}
		s.undoStack.Clear()
	}) {
		writeJSONError(w, "game is shutting down", http.StatusServiceUnavailable)
		return
	}
	if !authorized {
		http.Error(w, "account changed; please sign in again", http.StatusUnauthorized)
		return
	}
	s.setAuthCookie(w, account)
	http.Redirect(w, r, "/", http.StatusFound)
}

func (s *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name:     "admin_session",
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
		Secure:   s.useTLS,
	})
	http.Redirect(w, r, "/login", http.StatusFound)
}

func (s *AdminServer) renderPage(w http.ResponseWriter, r *http.Request, name string, data map[string]any) {
	if data == nil {
		data = map[string]any{}
	}
	if _, ok := data["Account"]; !ok {
		if acc := s.accountFromCookie(r); acc != "" {
			data["Account"] = acc
		}
	}
	if _, ok := data["UndoStack"]; !ok {
		data["UndoStack"] = s.undoStack.Info()
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
		log.Printf("template error (%s): %v", name, err)
	}
}

func (s *AdminServer) accountFromCookie(r *http.Request) string {
	cookie, err := r.Cookie("admin_session")
	if err != nil {
		return ""
	}
	parts := strings.SplitN(cookie.Value, ":", 2)
	if len(parts) != 2 {
		return ""
	}
	return parts[0]
}

func loadOrGenerateCert(cfg *config.Config) (tls.Certificate, error) {
	if cfg.TLS.CertFile != "" && cfg.TLS.KeyFile != "" {
		return tls.LoadX509KeyPair(cfg.TLS.CertFile, cfg.TLS.KeyFile)
	}
	log.Printf("admin_https: using self-signed certificate (no shared tls cert configured)")
	return generateSelfSignedCert()
}

func generateSelfSignedCert() (tls.Certificate, error) {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return tls.Certificate{}, fmt.Errorf("rsa key generation: %w", err)
	}
	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	if err != nil {
		return tls.Certificate{}, fmt.Errorf("serial number: %w", err)
	}
	now := time.Now()
	tmpl := &x509.Certificate{
		SerialNumber: serial,
		Subject: pkix.Name{
			CommonName: "THOI Admin Self-Signed Certificate",
		},
		NotBefore:             now.Add(-1 * time.Hour),
		NotAfter:              now.Add(365 * 24 * time.Hour),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA:                  true,
		DNSNames:              []string{"localhost"},
		IPAddresses:           []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
	}
	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		return tls.Certificate{}, fmt.Errorf("x509 creation: %w", err)
	}
	return tls.Certificate{
		Certificate: [][]byte{certDER},
		PrivateKey:  key,
	}, nil
}

func writeJSON(w http.ResponseWriter, data any) {
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(data); err != nil {
		log.Printf("json encode error: %v", err)
	}
}

func writeJSONError(w http.ResponseWriter, msg string, code int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(map[string]any{"error": msg})
}

// failJSON writes a JSON error body without changing the HTTP status. This
// is the long-standing wire behavior most admin editors depend on: they read
// res.error out of a 200 response, while api wrappers in admin.js treat any
// non-200 as a thrown raw-text error. Unifying status codes requires a
// coordinated change across the static JS clients; do not silently switch
// call sites to non-200 codes here.
func failJSON(w http.ResponseWriter, msg string) {
	writeJSONError(w, msg, http.StatusOK)
}

func readJSON(r *http.Request, v any) error {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	return json.Unmarshal(body, v)
}

func (s *AdminServer) handleUndoState(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, s.undoStack.Info())
}

func (s *AdminServer) doUndo(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	change := s.undoStack.Undo()
	if change == nil {
		writeJSON(w, map[string]any{"message": "Nothing to undo"})
		return
	}
	s.rebuildAfterUndo(change)
	resp := map[string]any{"message": "Undid: " + change.ShortDesc()}
	dups := behavior.CheckDuplicateIDs(filepath.Join(s.dataDir, "rooms"))
	if len(dups) > 0 {
		resp["has_duplicates"] = true
	}
	writeJSON(w, resp)
}

func (s *AdminServer) doRedo(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	change := s.undoStack.Redo()
	if change == nil {
		writeJSON(w, map[string]any{"message": "Nothing to redo"})
		return
	}
	s.rebuildAfterUndo(change)
	resp := map[string]any{"message": "Redid: " + change.ShortDesc()}
	dups := behavior.CheckDuplicateIDs(filepath.Join(s.dataDir, "rooms"))
	if len(dups) > 0 {
		resp["has_duplicates"] = true
	}
	writeJSON(w, resp)
}

func (s *AdminServer) handleEntityDirs(entityType string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		var body struct {
			Action  string `json:"action"`
			Name    string `json:"name"`
			Dir     string `json:"dir"`
			NewName string `json:"new_name"`
		}
		if err := readJSON(r, &body); err != nil {
			failJSON(w, "invalid")
			return
		}
		switch body.Action {
		case "create":
			if err := createEntityDir(s.dataDir, entityType, body.Name); err != nil {
				failJSON(w, err.Error())
				return
			}
			writeJSON(w, map[string]any{"ok": true, "name": body.Name})
		case "delete":
			changes, err := deleteEntityDir(s.dataDir, entityType, body.Dir)
			if err != nil {
				failJSON(w, err.Error())
				return
			}
			for _, ch := range changes {
				s.undoStack.Push(ch)
			}
			writeJSON(w, map[string]any{"ok": true, "moved": len(changes) - 1})
		case "rename_dir":
			if err := renameEntityDir(s.dataDir, entityType, body.Dir, body.NewName); err != nil {
				failJSON(w, err.Error())
				return
			}
			writeJSON(w, map[string]any{"ok": true, "name": body.NewName})
		default:
			failJSON(w, "unknown action")
		}
	}
}

func (s *AdminServer) handleEntityRename(entityType string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		var body struct {
			ID    string `json:"id"`
			NewID string `json:"new_id"`
		}
		if err := readJSON(r, &body); err != nil || body.ID == "" || body.NewID == "" ||
			!validEntityID(body.NewID) {
			failJSON(w, "invalid")
			return
		}
		oldPath, newPath, data, err := renameEntityFile(s.dataDir, entityType, body.ID, body.NewID)
		if err != nil {
			failJSON(w, err.Error())
			return
		}
		desc := fmt.Sprintf("rename %s %s to %s", entityType, body.ID, body.NewID)
		s.undoStack.Push(ChangeDesc{
			Description: desc,
			FilePath:    oldPath,
			NewFilePath: newPath,
			OldContent:  data,
			NewContent:  data,
		})
		s.invalidateEntityCaches(entityType)
		writeJSON(w, map[string]any{"ok": true, "id": body.NewID})
	}
}

func (s *AdminServer) handleEntityMove(entityType string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		var body struct {
			ID  string `json:"id"`
			Dir string `json:"dir"`
		}
		if err := readJSON(r, &body); err != nil || body.ID == "" {
			failJSON(w, "invalid")
			return
		}
		oldPath, newPath, data, err := moveEntityFile(s.dataDir, entityType, body.ID, body.Dir)
		if err != nil {
			failJSON(w, err.Error())
			return
		}
		desc := fmt.Sprintf("move %s %s to %s/", entityType, body.ID, body.Dir)
		if body.Dir == "" {
			desc = fmt.Sprintf("move %s %s to root", entityType, body.ID)
		}
		s.undoStack.Push(ChangeDesc{
			Description: desc,
			FilePath:    oldPath,
			NewFilePath: newPath,
			OldContent:  data,
			NewContent:  data,
		})
		s.invalidateEntityCaches(entityType)
		writeJSON(w, map[string]any{"ok": true})
	}
}

func (s *AdminServer) rebuildAfterUndo(change *ChangeDesc) {
	s.world.RebuildRoomIndex(s.dataDir)
	s.world.ClearHazardCache()

	for _, p := range changeFiles(change) {
		rel, err := filepath.Rel(filepath.Join(s.dataDir, "rooms"), p)
		if err != nil {
			continue
		}
		if rel == "." || rel == ".." || strings.HasPrefix(rel, "..") {
			continue
		}
		name := filepath.Base(p)
		if idStr := strings.TrimSuffix(name, ".yaml"); idStr != name {
			if id, err := strconv.Atoi(idStr); err == nil && id > 0 {
				// Only drop runtime room state when the room file is now gone
				// (undo-of-create, redo-of-delete, directory deletion): a
				// rename's undo restores the file and the inverse migration
				// rekeys its runtime state back — clearing it here would
				// destroy the room's live contents.
				if _, statErr := os.Stat(p); os.IsNotExist(statErr) {
					s.world.ClearRoomState(id)
					// Drop any in-memory mob instances too so they don't keep
					// ticking against a room that no longer exists.
					if s.mobStore != nil {
						s.mobStore.RemoveMobsInRoom(id)
					}
					// The room no longer exists, so its cached casino games
					// (tables/machines) must be evicted like the direct-delete
					// API does: outstanding wagers are refunded through the
					// wired game callback before the cache entries drop.
					if s.evictRoom != nil {
						s.evictRoom(id)
					}
				}
			}
		}
	}

	for _, p := range changeFiles(change) {
		s.invalidateEntityCacheForPath(p)
	}

	// Course definitions changed on disk (create/update/delete via undo or
	// redo): the runtime course index must reload, exactly like the course
	// API handlers do, or gameplay keeps traversing the stale course.
	for _, p := range changeFiles(change) {
		if rel, err := filepath.Rel(filepath.Join(s.dataDir, "courses"), p); err == nil &&
			!strings.HasPrefix(rel, "..") && rel != "." {
			s.reloadCoursesIfWired()
			break
		}
	}
}

func (s *AdminServer) invalidateEntityCaches(entityType string) {
	switch entityType {
	case "mobs":
		s.mobStore.ReloadDefs(s.dataDir)
	case "drops":
		behavior.ClearDropIndex()
	case "items":
		if s.itemStore != nil {
			s.itemStore.Reload(s.dataDir)
		}
		if s.rebuildCraftIndex != nil {
			s.rebuildCraftIndex()
		}
	}
}

func (s *AdminServer) invalidateEntityCacheForPath(path string) {
	for _, subdir := range []string{"mobs", "drops", "items"} {
		rel, err := filepath.Rel(filepath.Join(s.dataDir, subdir), path)
		if err == nil && !strings.HasPrefix(rel, "..") && rel != "." {
			s.invalidateEntityCaches(subdir)
		}
	}
}

func changeFiles(change *ChangeDesc) []string {
	files := []string{change.FilePath}
	if change.NewFilePath != "" {
		files = append(files, change.NewFilePath)
	}
	for _, ef := range change.ExtraFiles {
		files = append(files, ef.FilePath)
	}
	return files
}