Merge control portal work from RPGTheory/aeternalis-portal
RPGTheory/aeternalis-portal had diverged from this repo (the git/CI/CD copy) with an in-progress control portal feature that was never synced back here, so none of it had gone through CI or been deployed: - New site/game/control routing split: index.html becomes a world directory landing page (site.ts), game.html is the renamed former index.html (main.ts), control.html is a new admin panel (control.ts, portal-shared.ts, portal.css). - Server: new internal/store/portal.go (character/world registry, command queue, admin grants) and internal/transport/control.go (portal API routes), plus a new internal/gitops package that lets the portal provision new worlds via a GitOps repo commit. - game.World gains BornAt/DiedAt/DeathReason and an operator Control() path (close/open admissions, awaken boss, end world, per-character rename/heal/unstuck/retire); death no longer reuses the same character id on rejoin, matching the "new life" permadeath model in Plan.md rather than the old bypass-prevention test's expectations. - deploy/: new control-egress network policy and portal/control values (admin role, GitOps repo/branch/values file/CIDRs). - New e2e coverage: tests/portal.spec.ts, tools/capture-world.mjs. Verified this repo's own independent commits (800ms movement-staleness window, 20s boss-attack poll, SRS/TLS deploy values, ubuntu-22.04 runner pin, DOCKER_HOST fix) were already present in the portal copy before merging, so nothing here regresses them. `tsc --noEmit`, the vite client build, and the protocol contract check all pass; no go.mod changes. Could not run `go build`/`go test` locally (no Go toolchain on PATH, Docker daemon not running) — every new/changed Go symbol was manually cross-referenced and resolves, but this should still be built and tested in CI before merging to master. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -18,21 +19,24 @@ import (
|
||||
)
|
||||
|
||||
type Auth struct {
|
||||
db *store.DB
|
||||
dev bool
|
||||
base string
|
||||
oauth *oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
mu sync.Mutex
|
||||
flows map[string]flow
|
||||
db *store.DB
|
||||
dev bool
|
||||
base string
|
||||
oauth *oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
mu sync.Mutex
|
||||
flows map[string]flow
|
||||
AdminRole string
|
||||
DevAdmin bool
|
||||
}
|
||||
type flow struct {
|
||||
verifier string
|
||||
expires time.Time
|
||||
returnTo string
|
||||
}
|
||||
|
||||
func NewAuth(ctx context.Context, db *store.DB, dev bool, base, issuer, client, secret string) (*Auth, error) {
|
||||
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}}
|
||||
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}, AdminRole: "aeternalis-admin"}
|
||||
if dev {
|
||||
return a, nil
|
||||
}
|
||||
@@ -62,16 +66,25 @@ func (a *Auth) account(r *http.Request) (string, error) {
|
||||
return a.db.Session(r.Context(), hash(c.Value))
|
||||
}
|
||||
func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error {
|
||||
return a.issueSession(w, r, account, false)
|
||||
}
|
||||
func (a *Auth) issueSession(w http.ResponseWriter, r *http.Request, account string, admin bool) error {
|
||||
token := game.ID() + game.ID()
|
||||
if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil {
|
||||
return err
|
||||
}
|
||||
if admin {
|
||||
if err := a.db.GrantAdmin(r.Context(), hash(token), 600); err != nil {
|
||||
_ = a.db.DeleteSession(r.Context(), hash(token))
|
||||
return err
|
||||
}
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: a.cookieName(), Value: token, Path: "/", HttpOnly: true, Secure: !a.dev, SameSite: http.SameSiteLaxMode, MaxAge: 86400})
|
||||
return nil
|
||||
}
|
||||
func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
|
||||
if a.dev {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
http.Redirect(w, r, safeReturn(r.URL.Query().Get("return")), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
state := game.ID() + game.ID()
|
||||
@@ -87,7 +100,7 @@ func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 503, "login capacity reached")
|
||||
return
|
||||
}
|
||||
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)}
|
||||
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute), safeReturn(r.URL.Query().Get("return"))}
|
||||
a.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Value: state, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 600})
|
||||
http.Redirect(w, r, a.oauth.AuthCodeURL(state, oauth2.S256ChallengeOption(v), oidc.Nonce(state)), http.StatusSeeOther)
|
||||
@@ -128,12 +141,57 @@ func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 401, "invalid identity token")
|
||||
return
|
||||
}
|
||||
if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); err != nil {
|
||||
var claims roleClaims
|
||||
if err = identity.Claims(&claims); err != nil {
|
||||
fail(w, 401, "invalid identity claims")
|
||||
return
|
||||
}
|
||||
if err = a.issueSession(w, r, hash(identity.Issuer+"\x00"+identity.Subject), claims.admin(a.AdminRole, a.oauth.ClientID)); err != nil {
|
||||
fail(w, 503, "session unavailable")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
http.Redirect(w, r, f.returnTo, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
type roleSet struct {
|
||||
Roles []string `json:"roles"`
|
||||
}
|
||||
type roleClaims struct {
|
||||
Realm roleSet `json:"realm_access"`
|
||||
Clients map[string]roleSet `json:"resource_access"`
|
||||
}
|
||||
|
||||
func (c roleClaims) admin(role, client string) bool {
|
||||
return role != "" && (slices.Contains(c.Realm.Roles, role) || slices.Contains(c.Clients[client].Roles, role))
|
||||
}
|
||||
func (a *Auth) isAdmin(r *http.Request) bool {
|
||||
if _, err := a.account(r); err != nil {
|
||||
return false
|
||||
}
|
||||
if a.dev && a.DevAdmin {
|
||||
return true
|
||||
}
|
||||
c, err := r.Cookie(a.cookieName())
|
||||
return err == nil && a.db.IsAdmin(r.Context(), hash(c.Value))
|
||||
}
|
||||
func safeReturn(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.IsAbs() || u.Host != "" || u.User != nil || u.Fragment != "" {
|
||||
return "/"
|
||||
}
|
||||
if u.Path == "/control" {
|
||||
return "/control"
|
||||
}
|
||||
if u.Path == "/game" {
|
||||
q := url.Values{}
|
||||
if world := u.Query().Get("world"); worldIDPattern.MatchString(world) {
|
||||
q.Set("world", world)
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
func validOrigin(r *http.Request, base string) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
|
||||
var worldIDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
|
||||
var namePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9 _-]{1,23}$`)
|
||||
var requestIDPattern = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
|
||||
func (h *HTTP) admin(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return "", false
|
||||
}
|
||||
if !h.auth.isAdmin(r) {
|
||||
fail(w, 403, "Administrator access required. Sign in again with the configured Keycloak role.")
|
||||
return "", false
|
||||
}
|
||||
return account, true
|
||||
}
|
||||
func (h *HTTP) portalRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/worlds", func(w http.ResponseWriter, r *http.Request) {
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, worlds)
|
||||
})
|
||||
mux.HandleFunc("GET /api/account", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
characters, err := h.auth.db.Characters(r.Context(), account, "")
|
||||
if err != nil {
|
||||
fail(w, 503, "character history unavailable")
|
||||
return
|
||||
}
|
||||
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if err != nil {
|
||||
fail(w, 503, "character registry unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"characters": characters, "active": active, "admin": h.auth.isAdmin(r)})
|
||||
})
|
||||
mux.HandleFunc("GET /api/control", func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.admin(w, r); !ok {
|
||||
return
|
||||
}
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
return
|
||||
}
|
||||
characters, err := h.auth.db.Characters(r.Context(), "", r.URL.Query().Get("world"))
|
||||
if err != nil {
|
||||
fail(w, 503, "character registry unavailable")
|
||||
return
|
||||
}
|
||||
commands, err := h.auth.db.Commands(r.Context(), "", false)
|
||||
if err != nil {
|
||||
fail(w, 503, "audit log unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"worlds": worlds, "characters": characters, "commands": commands, "provisioningEnabled": h.Provisioner != nil, "characterLimit": 500, "auditLimit": 100})
|
||||
})
|
||||
mux.HandleFunc("POST /api/control/commands", func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := h.admin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ID string `json:"id"`
|
||||
WorldID string `json:"worldId"`
|
||||
Op string `json:"op"`
|
||||
Target string `json:"target"`
|
||||
Value string `json:"value"`
|
||||
Reason string `json:"reason"`
|
||||
Confirm string `json:"confirm"`
|
||||
}
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid command")
|
||||
return
|
||||
}
|
||||
req.Reason = strings.TrimSpace(req.Reason)
|
||||
req.Value = strings.TrimSpace(req.Value)
|
||||
if !requestIDPattern.MatchString(req.ID) || !worldIDPattern.MatchString(req.WorldID) || len(req.Reason) < 5 || len(req.Reason) > 240 || len(req.Target) > 128 || len(req.Value) > 100 {
|
||||
fail(w, 400, "a valid request ID, world ID, and 5-240 character reason are required")
|
||||
return
|
||||
}
|
||||
switch req.Op {
|
||||
case "create-world":
|
||||
if h.Provisioner == nil {
|
||||
fail(w, 503, "GitOps provisioning is not configured")
|
||||
return
|
||||
}
|
||||
if !regexp.MustCompile(`^[0-9]{1,15}$`).MatchString(req.Value) {
|
||||
fail(w, 400, "seed must contain 1-15 digits")
|
||||
return
|
||||
}
|
||||
case "close-admissions", "open-admissions", "awaken-boss", "end-world", "heal", "unstuck", "retire", "revoke-sessions":
|
||||
case "rename":
|
||||
if !namePattern.MatchString(req.Value) {
|
||||
fail(w, 400, "name must be 2-24 letters, numbers, spaces or hyphens")
|
||||
return
|
||||
}
|
||||
default:
|
||||
fail(w, 400, "unknown command")
|
||||
return
|
||||
}
|
||||
if req.Op == "end-world" || req.Op == "awaken-boss" || req.Op == "retire" {
|
||||
expected := req.WorldID
|
||||
if req.Op == "retire" {
|
||||
expected = req.Target
|
||||
}
|
||||
if req.Confirm != expected {
|
||||
fail(w, 400, "confirmation does not match the target")
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.Op != "create-world" {
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
return
|
||||
}
|
||||
found := false
|
||||
for _, world := range worlds {
|
||||
if world.ID == req.WorldID && world.Available {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
fail(w, 409, "world owner is not available")
|
||||
return
|
||||
}
|
||||
}
|
||||
command := store.Command{ID: req.ID, WorldID: req.WorldID, Actor: actor, Op: req.Op, Target: req.Target, Value: req.Value, Reason: req.Reason}
|
||||
if req.Op == "create-world" {
|
||||
command.Target = req.WorldID
|
||||
command.WorldID = "_provision"
|
||||
}
|
||||
if err := h.auth.db.Enqueue(r.Context(), command); err != nil {
|
||||
fail(w, 409, "command could not be queued; request ID may already be used")
|
||||
return
|
||||
}
|
||||
respond(w, 202, map[string]string{"id": command.ID, "status": "pending"})
|
||||
})
|
||||
}
|
||||
func (h *HTTP) RunProvisioning(ctx context.Context) {
|
||||
if h.Provisioner == nil {
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(2 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if !h.s.ready.Load() {
|
||||
return
|
||||
}
|
||||
commands, err := h.auth.db.Commands(ctx, "_provision", true)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, c := range commands {
|
||||
if c.Op != "create-world" {
|
||||
continue
|
||||
}
|
||||
request, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
result, err := h.Provisioner.CreateWorld(request, c.Target, c.Value)
|
||||
cancel()
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
result = err.Error()
|
||||
}
|
||||
_ = h.auth.db.FinishProvision(ctx, c.ID, result, err == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
|
||||
func TestControlAuthorizationAndExecution(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "control.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
w := game.New("control-test", 1, time.Now(), b)
|
||||
lease, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(w, lease)
|
||||
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
|
||||
assets := t.TempDir()
|
||||
for _, f := range []string{"index.html", "game.html", "control.html"} {
|
||||
if err = os.WriteFile(filepath.Join(assets, f), []byte("<!doctype html><title>"+f+"</title>"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
server := httptest.NewServer(NewHTTP(svc, auth, assets, nil).Handler())
|
||||
defer server.Close()
|
||||
auth.base = server.URL
|
||||
request := func(method, path, body, token, origin string) int {
|
||||
t.Helper()
|
||||
r, _ := http.NewRequest(method, server.URL+path, strings.NewReader(body))
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: auth.cookieName(), Value: token})
|
||||
}
|
||||
r.Header.Set("Origin", origin)
|
||||
response, err := server.Client().Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
return response.StatusCode
|
||||
}
|
||||
for _, path := range []string{"/", "/game", "/control", "/worlds/control-test/api/config"} {
|
||||
if status := request("GET", path, "", "", ""); status != 200 {
|
||||
t.Fatal(path, status)
|
||||
}
|
||||
}
|
||||
if status := request("GET", "/worlds/another/api/config", "", "", ""); status != 404 {
|
||||
t.Fatal("wrong world routed", status)
|
||||
}
|
||||
if request("GET", "/api/control", "", "", "") != 401 {
|
||||
t.Fatal("anonymous admin access")
|
||||
}
|
||||
token := game.ID() + game.ID()
|
||||
_ = db.CreateSession(ctx, hash(token), "operator")
|
||||
if request("GET", "/api/control", "", token, "") != 403 {
|
||||
t.Fatal("player has admin access")
|
||||
}
|
||||
_ = db.GrantAdmin(ctx, hash(token), 600)
|
||||
if request("GET", "/api/control", "", token, "") != 200 {
|
||||
t.Fatal("admin denied")
|
||||
}
|
||||
body := `{"id":"` + game.ID() + `","worldId":"control-test","op":"close-admissions","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", body, token, "https://evil.example") != 403 {
|
||||
t.Fatal("cross-origin admin command")
|
||||
}
|
||||
if request("POST", "/api/control/commands", body, token, server.URL) != 202 {
|
||||
t.Fatal("command not queued")
|
||||
}
|
||||
if err = svc.controls(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !w.AdmissionsClosed {
|
||||
t.Fatal("command not applied by world owner")
|
||||
}
|
||||
commands, _ := db.Commands(ctx, w.ID, false)
|
||||
if len(commands) != 1 || commands[0].Status != "completed" {
|
||||
t.Fatal("command not audited")
|
||||
}
|
||||
bad := `{"id":"` + game.ID() + `","worldId":"control-test","op":"end-world","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", bad, token, server.URL) != 400 {
|
||||
t.Fatal("destructive action without confirmation")
|
||||
}
|
||||
_ = db.DeleteSession(ctx, hash(token))
|
||||
if request("GET", "/api/control", "", token, "") != 401 {
|
||||
t.Fatal("revoked admin session accepted")
|
||||
}
|
||||
}
|
||||
func TestKeycloakRolesAndReturnURL(t *testing.T) {
|
||||
var claims roleClaims
|
||||
_ = json.Unmarshal([]byte(`{"realm_access":{"roles":["player"]},"resource_access":{"game":{"roles":["aeternalis-admin"]},"other":{"roles":["foreign-admin"]}}}`), &claims)
|
||||
if !claims.admin("aeternalis-admin", "game") || claims.admin("foreign-admin", "game") || claims.admin("", "game") {
|
||||
t.Fatal("role scope validation")
|
||||
}
|
||||
for _, raw := range []string{"https://evil.example", "//evil.example/game", "/\\evil", "/game#fragment", "/control?next=https://evil"} {
|
||||
if result := safeReturn(raw); result != "/" && result != "/control" {
|
||||
t.Fatal("unsafe return", raw, result)
|
||||
}
|
||||
}
|
||||
if safeReturn("/game?world=world-002&evil=value") != "/game?world=world-002" {
|
||||
t.Fatal("game return lost or untrusted query retained")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/gitops"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
@@ -24,12 +25,13 @@ type Destination struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
type HTTP struct {
|
||||
s *Service
|
||||
auth *Auth
|
||||
assets string
|
||||
worlds []Destination
|
||||
mu sync.Mutex
|
||||
rates map[string]*bucket
|
||||
s *Service
|
||||
auth *Auth
|
||||
assets string
|
||||
worlds []Destination
|
||||
mu sync.Mutex
|
||||
rates map[string]*bucket
|
||||
Provisioner *gitops.Client
|
||||
}
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
@@ -94,6 +96,7 @@ func (h *HTTP) allow(r *http.Request) bool {
|
||||
}
|
||||
func (h *HTTP) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h.portalRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world frozen")
|
||||
@@ -164,13 +167,18 @@ func (h *HTTP) Handler() http.Handler {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if err != nil {
|
||||
fail(w, 503, "character registry unavailable")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if c := h.s.world.ForAccount(account); c != nil {
|
||||
if c := h.s.world.ForAccount(account); c != nil && active != nil && active.WorldID == h.s.world.ID && active.ID == c.View.Entity.ID {
|
||||
respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()})
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info()})
|
||||
respond(w, 200, map[string]any{"character": nil, "world": h.s.world.Info(), "active": active})
|
||||
})
|
||||
mux.HandleFunc("POST /api/join", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
@@ -237,6 +245,12 @@ func (h *HTTP) Handler() http.Handler {
|
||||
respond(w, 200, map[string]bool{"ok": true})
|
||||
})
|
||||
mux.HandleFunc("GET /ws", h.socket)
|
||||
for route, file := range map[string]string{"/{$}": "index.html", "/game": "game.html", "/control": "control.html"} {
|
||||
mux.HandleFunc("GET "+route, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.ServeFile(w, r, filepath.Join(h.assets, file))
|
||||
})
|
||||
}
|
||||
files := http.FileServer(http.Dir(h.assets))
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
|
||||
clean := filepath.Clean(filepath.FromSlash(r.URL.Path))
|
||||
@@ -258,6 +272,17 @@ func (h *HTTP) Handler() http.Handler {
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
prefix := "/worlds/" + h.s.world.ID
|
||||
if strings.HasPrefix(r.URL.Path, prefix+"/") {
|
||||
r = r.Clone(r.Context())
|
||||
u := *r.URL
|
||||
u.Path = strings.TrimPrefix(u.Path, prefix)
|
||||
u.RawPath = ""
|
||||
r.URL = &u
|
||||
} else if strings.HasPrefix(r.URL.Path, "/worlds/") {
|
||||
fail(w, 404, "unknown world route")
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
@@ -307,6 +332,12 @@ func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
id := c.View.Entity.ID
|
||||
active, err := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if err != nil || active == nil || active.WorldID != h.s.world.ID || active.ID != id {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 409, "character is not active in this world")
|
||||
return
|
||||
}
|
||||
if h.s.peers[id] != nil {
|
||||
h.s.mu.Unlock()
|
||||
fail(w, 409, "character already connected")
|
||||
|
||||
@@ -22,13 +22,14 @@ type peer struct {
|
||||
close func()
|
||||
}
|
||||
type Service struct {
|
||||
mu sync.Mutex
|
||||
world *game.World
|
||||
lease *store.Lease
|
||||
peers map[string]*peer
|
||||
ready atomic.Bool
|
||||
lastSave time.Time
|
||||
done chan struct{}
|
||||
mu sync.Mutex
|
||||
world *game.World
|
||||
lease *store.Lease
|
||||
peers map[string]*peer
|
||||
ready atomic.Bool
|
||||
lastSave time.Time
|
||||
lastControl time.Time
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewService(w *game.World, l *store.Lease) *Service {
|
||||
@@ -66,6 +67,14 @@ func (s *Service) Run(ctx context.Context) {
|
||||
}
|
||||
s.world.Advance(now, now.Sub(last).Seconds())
|
||||
last = now
|
||||
if now.Sub(s.lastControl) >= time.Second {
|
||||
if err := s.controls(ctx); err != nil {
|
||||
s.ready.Store(false)
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.lastControl = now
|
||||
}
|
||||
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
|
||||
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := s.persist(saveCtx, "")
|
||||
@@ -125,6 +134,18 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
}
|
||||
var c *game.Character
|
||||
var err error
|
||||
active, err := s.lease.DB.ActiveCharacter(ctx, account)
|
||||
if err != nil {
|
||||
return p.Character{}, errors.New("character registry unavailable")
|
||||
}
|
||||
if active != nil {
|
||||
transfer := claim != "" && active.ID == claim && active.State == "eligible" && active.WorldID != s.world.ID
|
||||
resume := claim == "" && active.WorldID == s.world.ID
|
||||
if !transfer && !resume {
|
||||
return p.Character{}, store.ErrLivingCharacter
|
||||
}
|
||||
}
|
||||
existing := s.world.ForAccount(account)
|
||||
if claim != "" {
|
||||
c, err = s.lease.DB.ReadPassage(ctx, claim, account)
|
||||
if err != nil {
|
||||
@@ -139,11 +160,62 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
return p.Character{}, err
|
||||
}
|
||||
}
|
||||
if err = s.persist(ctx, claim); err != nil {
|
||||
if err = s.lease.Save(ctx, s.world, claim); err != nil {
|
||||
if errors.Is(err, store.ErrLivingCharacter) {
|
||||
if existing == nil {
|
||||
delete(s.world.Characters, c.View.Entity.ID)
|
||||
}
|
||||
return p.Character{}, err
|
||||
}
|
||||
s.ready.Store(false)
|
||||
for _, peer := range s.peers {
|
||||
peer.close()
|
||||
}
|
||||
return p.Character{}, errors.New("world persistence unavailable")
|
||||
}
|
||||
s.lastSave = time.Now()
|
||||
view := c.View
|
||||
view.Inventory = maps.Clone(view.Inventory)
|
||||
view.Skills = maps.Clone(view.Skills)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (s *Service) controls(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
commands, err := s.lease.DB.Commands(ctx, s.world.ID, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, command := range commands {
|
||||
result := ""
|
||||
if time.Now().Unix()-command.CreatedAt > 900 {
|
||||
result = "command expired before execution"
|
||||
} else if command.Op == "revoke-sessions" {
|
||||
found := false
|
||||
for id, c := range s.world.Characters {
|
||||
if c.Account == command.Target {
|
||||
found = true
|
||||
s.world.Disconnect(id)
|
||||
if p := s.peers[id]; p != nil {
|
||||
p.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
result = "account not found in world"
|
||||
}
|
||||
} else if err = s.world.Control(command.Op, command.Target, command.Value, command.Reason); err != nil {
|
||||
result = err.Error()
|
||||
}
|
||||
if err = s.lease.SaveCommand(ctx, s.world, "", &command, result); err != nil {
|
||||
s.ready.Store(false)
|
||||
for _, peer := range s.peers {
|
||||
peer.close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.lastSave = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user