aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 030bbb68cb210e162e6fedc0cc8d56048eb73364
parent 5525f8c46519378bcc4ffe662529d57f68a7e821
Author: anon <anon@example.com>
Date:   Wed, 11 Nov 2026 04:53:23 +0000

Use client addresses forwarded by local nginx

Diffstat:
MDEVELOPERS.md | 9+++++++--
Mserver/browser_socket.go | 20++++++++++++++++++--
Mserver/browser_socket_test.go | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/browser_stream_test.go | 9++-------
4 files changed, 90 insertions(+), 11 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -30,8 +30,10 @@ admin map script remain compiled into both builds. Mutable world state is stored in `data/world.sqlite` and certificates in `data/https/`. Server logs go to `logs/server.log` and profiles to `logs/profiles/`. By default, the terminal and log file contain startup/shutdown, player connections -with peer IP and port, and errors. Browser connections retain the HTTP peer address; -when proxied, this is the proxy address. Pass `-trace` when debugging to also write +with peer IP and port, and errors. Browser connections from a loopback proxy use +the last `X-Forwarded-For` address in logs and `players.last_ip` (port 0, since the +header contains no port). Other connections retain their peer address. +Pass `-trace` when debugging to also write packet, movement and HTTP request traces to `logs/server.log`. Browser profiling is also off by default; sign in to `/admin` in the same browser, then open the game with `?profile=1` to collect and upload a diagnostic @@ -343,6 +345,9 @@ mark `ao_client` secure when using HTTPS. The cookie is scoped to the prefix. The admin dashboard requires a separate administrator login; initialize the first account before public exposure. See [administration](docs/admin.md). +For nginx on the same host, set `X-Forwarded-For` to `$proxy_add_x_forwarded_for` +so connection logs and the players table record the original client IP. + Keep saved player data and logs outside the public static directory. ### Backups and restore diff --git a/server/browser_socket.go b/server/browser_socket.go @@ -5,6 +5,7 @@ import ( "log" "net" "net/http" + "strings" "github.com/coder/websocket" ) @@ -22,6 +23,20 @@ type browserGameConn struct { func (connection *browserGameConn) RemoteAddr() net.Addr { return connection.peer } +func browserRemoteAddress(r *http.Request) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil || !net.ParseIP(host).IsLoopback() { + return r.RemoteAddr + } + // Local nginx appends the actual client after any untrusted forwarded values. + forwarded := r.Header.Get("X-Forwarded-For") + ip := net.ParseIP(strings.TrimSpace(forwarded[strings.LastIndexByte(forwarded, ',')+1:])) + if ip == nil { + return r.RemoteAddr + } + return net.JoinHostPort(ip.String(), "0") +} + func (server *server) browserWorld(w http.ResponseWriter, r *http.Request) { server.browserConnection(w, r, false) } @@ -52,13 +67,14 @@ func (server *server) browserConnection(w http.ResponseWriter, r *http.Request, return } defer finish() + remoteAddr := browserRemoteAddress(r) if socket.Subprotocol() == "ao-stream-v1" { - server.resumeBrowserStream(socket, id, credential, chat, r.RemoteAddr) + server.resumeBrowserStream(socket, id, credential, chat, remoteAddr) return } // Preserve the TCP byte stream across arbitrary binary WebSocket boundaries. - connection := &browserGameConn{Conn: websocket.NetConn(context.Background(), socket, websocket.MessageBinary), peer: browserPeerAddress(r.RemoteAddr)} + connection := &browserGameConn{Conn: websocket.NetConn(context.Background(), socket, websocket.MessageBinary), peer: browserPeerAddress(remoteAddr)} if chat { if err := server.serveChatClient(&chatClient{conn: connection, id: id, browserTokenHash: credential}); err != nil { log.Printf("Browser chat connection: %v", err) diff --git a/server/browser_socket_test.go b/server/browser_socket_test.go @@ -106,6 +106,69 @@ func TestBrowserWorldRejectsUnrelatedOrigin(t *testing.T) { } } +func TestBrowserWorldForwardedAddress(t *testing.T) { + for _, test := range []struct { + name, remote, forwarded, want string + }{ + {"nginx IPv4", "127.0.0.1:4321", "198.51.100.99, 192.0.2.10", "192.0.2.10"}, + {"nginx IPv6", "[::1]:4321", "2001:db8::5", "2001:db8::5"}, + {"direct client", "192.0.2.20:4321", "198.51.100.99", "192.0.2.20"}, + {"invalid header", "127.0.0.1:4321", "192.0.2.10, invalid", "127.0.0.1"}, + } { + t.Run(test.name, func(t *testing.T) { + world := newTestServer(t) + world.newCharacter().browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("visitor-token"))) + if err := world.saveUser(world.characters[1]); err != nil { + t.Fatal(err) + } + startTestService(t, world) + host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.RemoteAddr = test.remote + world.browserWorld(w, r) + })) + defer host.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + socket, _, err := websocket.Dial(ctx, host.URL, &websocket.DialOptions{ + HTTPHeader: http.Header{"Cookie": {"ao_client=visitor-token"}, "X-Forwarded-For": {test.forwarded}}, + }) + if err != nil { + t.Fatal(err) + } + defer socket.CloseNow() + connection := websocket.NetConn(ctx, socket, websocket.MessageBinary) + cookie, _ := hex.DecodeString("dfdf00010001002000000001000000020000001b000000010000000000000000") + if _, err := connection.Write(cookie); err != nil { + t.Fatal(err) + } + for { + packet, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e { + break + } + } + + // Connection logs and persisted player metadata must use the same IP. + callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { + address := state.clients[1].conn.RemoteAddr().String() + ip, _, err := net.SplitHostPort(address) + if err != nil || ip != test.want { + return fmt.Errorf("connection IP: %q, want %q", address, test.want) + } + return nil + })) + var saved string + if err := world.db.QueryRow("SELECT last_ip FROM players WHERE id=1").Scan(&saved); err != nil || saved != test.want { + t.Fatal("forwarded player IP was not persisted", saved, err) + } + }) + } +} + func TestBrowserWorldRequiresCredential(t *testing.T) { world := newTestServer(t) world.newCharacter().browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("visitor-token"))) diff --git a/server/browser_stream_test.go b/server/browser_stream_test.go @@ -32,19 +32,14 @@ func TestBrowserWorldResumesTheSameSessionWithoutLostOrDuplicatedBytes(t *testin t.Fatal(err) } startTestService(t, world) - host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("X-Test-Reconnected") == "1" { - r.RemoteAddr = "[2001:db8::7]:5678" - } - world.browserWorld(w, r) - })) + host := httptest.NewServer(http.HandlerFunc(world.browserWorld)) defer host.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() dial := func(received, acknowledged string) *websocket.Conn { headers := http.Header{"Cookie": {"ao_client=visitor-token"}} if received != "0" { - headers.Set("X-Test-Reconnected", "1") + headers.Set("X-Forwarded-For", "192.0.2.66, 2001:db8::7") } socket, _, err := websocket.Dial(ctx, host.URL, &websocket.DialOptions{ HTTPHeader: headers, Subprotocols: []string{"ao-stream-v1"},