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>
178 lines
6.2 KiB
Go
178 lines
6.2 KiB
Go
package gitops
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"go.yaml.in/yaml/v3"
|
|
)
|
|
|
|
type Config struct{ Repository, Branch, File, Token, PublicURL string }
|
|
type Client struct {
|
|
config Config
|
|
endpoint string
|
|
http *http.Client
|
|
}
|
|
|
|
var identifier = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
|
|
var seedPattern = regexp.MustCompile(`^[0-9]{1,15}$`)
|
|
|
|
func New(c Config) (*Client, error) {
|
|
if c.Repository == "" && c.Token == "" {
|
|
return nil, nil
|
|
}
|
|
u, err := url.Parse(c.Repository)
|
|
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
|
return nil, errors.New("CONTROL_GITOPS_REPOSITORY must be an HTTPS repository URL without credentials")
|
|
}
|
|
parts := strings.Split(strings.Trim(strings.TrimSuffix(u.Path, ".git"), "/"), "/")
|
|
if len(parts) != 2 {
|
|
return nil, errors.New("GitOps repository must have owner/repository path")
|
|
}
|
|
for _, p := range parts {
|
|
if p == "." || p == ".." || !regexp.MustCompile(`^[A-Za-z0-9_.-]+$`).MatchString(p) {
|
|
return nil, errors.New("invalid repository path")
|
|
}
|
|
}
|
|
if c.Token == "" || c.Branch == "" || c.File == "" || path.Clean(c.File) != c.File || strings.HasPrefix(c.File, "/") || strings.Contains(c.File, "\\") || strings.HasPrefix(c.File, "..") || !strings.HasSuffix(c.File, ".yaml") {
|
|
return nil, errors.New("GitOps requires token, branch, and repository-relative .yaml file")
|
|
}
|
|
public, err := url.Parse(c.PublicURL)
|
|
if err != nil || public.Scheme != "https" || public.Host == "" || public.Path != "" || public.RawQuery != "" || public.User != nil {
|
|
return nil, errors.New("GitOps requires an HTTPS public origin")
|
|
}
|
|
endpoint := u.Scheme + "://" + u.Host + "/api/v1/repos/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1]) + "/contents/"
|
|
for i, p := range strings.Split(c.File, "/") {
|
|
if i > 0 {
|
|
endpoint += "/"
|
|
}
|
|
endpoint += url.PathEscape(p)
|
|
}
|
|
return &Client{c, endpoint, &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
|
|
}
|
|
func (c *Client) request(ctx context.Context, method string, body any) ([]byte, int, error) {
|
|
var r io.Reader
|
|
if body != nil {
|
|
data, err := json.Marshal(body)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
r = bytes.NewReader(data)
|
|
}
|
|
u := c.endpoint
|
|
if method == http.MethodGet {
|
|
u += "?ref=" + url.QueryEscape(c.config.Branch)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, u, r)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
req.Header.Set("Authorization", "token "+c.config.Token)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
res, err := c.http.Do(req)
|
|
if err != nil {
|
|
return nil, 0, errors.New("GitOps service unavailable")
|
|
}
|
|
defer res.Body.Close()
|
|
raw, err := io.ReadAll(io.LimitReader(res.Body, 2<<20))
|
|
if err != nil {
|
|
return nil, res.StatusCode, errors.New("GitOps response unavailable")
|
|
}
|
|
return raw, res.StatusCode, nil
|
|
}
|
|
func mapping(n *yaml.Node, key string) *yaml.Node {
|
|
if n.Kind != yaml.MappingNode {
|
|
return nil
|
|
}
|
|
for i := 0; i < len(n.Content); i += 2 {
|
|
if n.Content[i].Value == key {
|
|
return n.Content[i+1]
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func scalar(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v} }
|
|
|
|
// Only the worlds sequence is changed; image pins, comments and runtime settings
|
|
// stay intact. Gitea's content SHA rejects concurrent image-promotion overwrites.
|
|
func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, error) {
|
|
if !identifier.MatchString(id) || !seedPattern.MatchString(seed) {
|
|
return "", errors.New("invalid world ID or seed")
|
|
}
|
|
for attempt := 0; attempt < 3; attempt++ {
|
|
raw, status, err := c.request(ctx, http.MethodGet, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if status != 200 {
|
|
return "", fmt.Errorf("GitOps values could not be read (HTTP %d)", status)
|
|
}
|
|
var file struct {
|
|
SHA string `json:"sha"`
|
|
Content string `json:"content"`
|
|
}
|
|
if json.Unmarshal(raw, &file) != nil || file.SHA == "" {
|
|
return "", errors.New("invalid GitOps file response")
|
|
}
|
|
data, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(file.Content, "\n", ""))
|
|
if err != nil {
|
|
return "", errors.New("invalid GitOps file encoding")
|
|
}
|
|
var doc yaml.Node
|
|
if yaml.Unmarshal(data, &doc) != nil || len(doc.Content) != 1 {
|
|
return "", errors.New("invalid GitOps YAML")
|
|
}
|
|
root := doc.Content[0]
|
|
worlds := mapping(root, "worlds")
|
|
portal := mapping(root, "portal")
|
|
public, _ := url.Parse(c.config.PublicURL)
|
|
if portal == nil || mapping(portal, "host") == nil || mapping(portal, "host").Value != public.Host {
|
|
return "", errors.New("GitOps portal.host must match PUBLIC_URL before provisioning")
|
|
}
|
|
if worlds == nil || worlds.Kind != yaml.SequenceNode {
|
|
return "", errors.New("GitOps values must contain a worlds list")
|
|
}
|
|
for _, world := range worlds.Content {
|
|
key := mapping(world, "id")
|
|
if key != nil && key.Value == id {
|
|
existing := mapping(world, "seed")
|
|
if existing != nil && existing.Value == seed {
|
|
return "World definition already committed; waiting for ArgoCD readiness.", nil
|
|
}
|
|
return "", errors.New("world ID already exists with a different seed")
|
|
}
|
|
}
|
|
if len(worlds.Content) >= 50 {
|
|
return "", errors.New("operator world limit reached (50)")
|
|
}
|
|
worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host)}})
|
|
encoded, err := yaml.Marshal(&doc)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
body := map[string]string{"branch": c.config.Branch, "sha": file.SHA, "content": base64.StdEncoding.EncodeToString(encoded), "message": "Provision Aeternalis world " + id}
|
|
_, status, err = c.request(ctx, http.MethodPut, body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if status == 200 || status == 201 {
|
|
return "World definition committed; waiting for ArgoCD readiness.", nil
|
|
}
|
|
if status != 409 && status != 422 {
|
|
return "", fmt.Errorf("GitOps commit rejected (HTTP %d)", status)
|
|
}
|
|
}
|
|
return "", errors.New("GitOps changed concurrently; retry the request")
|
|
}
|