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>
208 lines
6.1 KiB
Go
208 lines
6.1 KiB
Go
package transport
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"net/url"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"aeternalis/server/internal/game"
|
|
"aeternalis/server/internal/store"
|
|
"github.com/coreos/go-oidc/v3/oidc"
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
type Auth struct {
|
|
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{}, AdminRole: "aeternalis-admin"}
|
|
if dev {
|
|
return a, nil
|
|
}
|
|
if !strings.HasPrefix(base, "https://") || !strings.HasPrefix(issuer, "https://") || client == "" {
|
|
return nil, errors.New("production requires HTTPS PUBLIC_URL, OIDC_ISSUER, and OIDC_CLIENT_ID")
|
|
}
|
|
provider, err := oidc.NewProvider(ctx, issuer)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
a.oauth = &oauth2.Config{ClientID: client, ClientSecret: secret, Endpoint: provider.Endpoint(), RedirectURL: base + "/auth/callback", Scopes: []string{oidc.ScopeOpenID}}
|
|
a.verifier = provider.Verifier(&oidc.Config{ClientID: client})
|
|
return a, nil
|
|
}
|
|
func hash(s string) string { b := sha256.Sum256([]byte(s)); return hex.EncodeToString(b[:]) }
|
|
func (a *Auth) cookieName() string {
|
|
if a.dev {
|
|
return "aeternalis_session"
|
|
}
|
|
return "__Host-aeternalis_session"
|
|
}
|
|
func (a *Auth) account(r *http.Request) (string, error) {
|
|
c, err := r.Cookie(a.cookieName())
|
|
if err != nil || len(c.Value) != 64 {
|
|
return "", errors.New("not authenticated")
|
|
}
|
|
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, safeReturn(r.URL.Query().Get("return")), http.StatusSeeOther)
|
|
return
|
|
}
|
|
state := game.ID() + game.ID()
|
|
v := oauth2.GenerateVerifier()
|
|
a.mu.Lock()
|
|
for key, f := range a.flows {
|
|
if time.Now().After(f.expires) {
|
|
delete(a.flows, key)
|
|
}
|
|
}
|
|
if len(a.flows) >= 4096 {
|
|
a.mu.Unlock()
|
|
fail(w, 503, "login capacity reached")
|
|
return
|
|
}
|
|
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)
|
|
}
|
|
func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
|
|
if a.dev {
|
|
fail(w, 404, "not enabled")
|
|
return
|
|
}
|
|
state := r.URL.Query().Get("state")
|
|
cookie, err := r.Cookie("__Host-aeternalis_login")
|
|
if err != nil || state == "" || cookie.Value != state {
|
|
fail(w, 400, "invalid login state")
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
f, ok := a.flows[state]
|
|
delete(a.flows, state)
|
|
a.mu.Unlock()
|
|
if !ok || time.Now().After(f.expires) {
|
|
fail(w, 400, "login expired")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
token, err := a.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(f.verifier))
|
|
if err != nil {
|
|
fail(w, 401, "login exchange failed")
|
|
return
|
|
}
|
|
raw, ok := token.Extra("id_token").(string)
|
|
if !ok {
|
|
fail(w, 401, "identity token missing")
|
|
return
|
|
}
|
|
identity, err := a.verifier.Verify(ctx, raw)
|
|
if err != nil || identity.Nonce != state {
|
|
fail(w, 401, "invalid identity token")
|
|
return
|
|
}
|
|
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, 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")
|
|
if origin == "" {
|
|
return false
|
|
}
|
|
expected, err := url.Parse(base)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
actual, err := url.Parse(origin)
|
|
return err == nil && actual.Scheme == expected.Scheme && actual.Host == expected.Host && actual.Path == "" && actual.RawQuery == "" && actual.User == nil
|
|
}
|