diff --git a/README.md b/README.md index 0b30f268..b3c8c35e 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,28 @@ Behind a reverse proxy every request comes from the proxy's address. To log the - Recommended: keep `X-Forwarded-For`, let the proxy pass it on (Traefik: `forwardedHeaders.trustedIPs` with [Cloudflare's ranges](https://www.cloudflare.com/ips/)) and list both the proxy and Cloudflare's ranges in `trustedProxies`. Every hop appends its peer to the chain, so a client that bypasses Cloudflare ends up as the first untrusted entry and is logged as itself. - Simpler: `"remoteIPHeaders": ["CF-Connecting-IP"]` with only the proxy in `trustedProxies`. This header holds a single address that the proxy passes on unchecked, so let only Cloudflare reach the proxy (firewall), otherwise a client that bypasses Cloudflare can set it itself. +## Recording List and Player Profiles + +The recording list is paged on the server. `GET /api/v1/operations` takes these optional query parameters, and its `X-Total-Count` header carries the number of matches across all pages. Without `limit` it returns every match in id order, as before. A full page also carries `X-Next-Cursor`: passed back as `after`, it continues right behind that page's last recording, so recordings added or deleted in between neither repeat one nor skip one. + +| Parameter | Description | +|-----------|-------------| +| `limit`, `after` | Page size (at most 500) and the `X-Next-Cursor` of the page before | +| `offset` | Matches to skip, counted when the request runs | +| `sort`, `dir` | `date` (by the instant, offsets of RFC3339 dates included), `name` or `duration`; `asc` (default) or `desc` | +| `q` | Mission name, world name or installed world display name contains, in any case of any script | +| `world` | Recorded on one of these worlds; repeat or comma-separate | +| `player` | Recordings a player of this in-game name took part in | +| `playerUid` | Recordings the player with this Steam UID took part in | +| `tagExact` | Tag equals, in the same case, as a tag chip in the UI selects | +| `name`, `tag`, `newer`, `older` | Mission name contains, tag contains, date range | + +`GET /api/v1/operations/summary` returns the totals and filter options of every recording. World names are stored in lower case, so each world it offers selects its recordings. + +Players are indexed per recording by Steam UID when the recording has one and by in-game name otherwise, so a player keeps one profile under every name they play as, including several names in one recording, which still counts once. The UID and every name come from the player's units, connections and Zeus slots, though a connection alone does not count as taking part. A unit recorded without a UID takes the one its name was seen with in the same recording. A player recorded without any UID has a separate profile by name. Converted recordings are indexed from their JSON source, because the v1 protobuf has no UIDs. The index is built when a recording is converted, streamed or uploaded, and recordings stored before it existed are indexed once at startup. + +`GET /api/v1/players?q=` searches players by any name they used or by exact Steam UID. `GET /api/v1/players/profile?uid=` returns one player's missions, kills, deaths, sides and other names across recordings; `?name=` finds a player recorded without a UID. The **Players** page in the UI, reached from the header or from player matches under the recording search, shows the same data. + ## Large Recording Support ### Overview diff --git a/cmd/ocap-webserver/main.go b/cmd/ocap-webserver/main.go index 58c06677..b2636af4 100644 --- a/cmd/ocap-webserver/main.go +++ b/cmd/ocap-webserver/main.go @@ -199,6 +199,10 @@ func runApp(d appDeps) error { }, ) + // Streamed recordings reach player search through the indexer; uploads + // through conversion or the stats computer below. + handlerOpts = append(handlerOpts, server.WithPlayerIndexer(worker)) + if setting.Conversion.Enabled { // Pass worker to handler for event-driven conversion on upload handlerOpts = append(handlerOpts, server.WithConversionTrigger(worker)) @@ -235,6 +239,12 @@ func runApp(d appDeps) error { handlerOpts = append(handlerOpts, server.WithMapTool(jm, tools, setting.Maps)) } + // Recordings stored before chat was masked are masked before they are + // served, and swept once in the background. + chatRedactor := server.NewChatRedactor(operation, setting.Data) + handlerOpts = append(handlerOpts, server.WithChatRedactor(chatRedactor)) + go chatRedactor.Backfill(ctx) + server.NewHandler(s, operation, marker, ammo, setting, handlerOpts...) // Handle graceful shutdown diff --git a/docs/streaming-architecture.md b/docs/streaming-architecture.md index 202c0611..d57cbd08 100644 --- a/docs/streaming-architecture.md +++ b/docs/streaming-architecture.md @@ -43,6 +43,38 @@ timeline. Older clients that omit the declaration keep their zero-based frames, legacy marker end sentinel and projectile trajectory field name. Unknown future message types are logged and skipped. +A chat message that starts with `#login`, in any case, carries the server admin +password. The addon masks it before sending, and the web masks it again on +receipt for older addons: the command is kept and everything after it becomes +`********`, a fixed mask that does not reveal the password's length. Both skip +the same leading whitespace: Unicode White_Space and U+FEFF. Files stored +before this rule are masked in place before the server first serves any of +them, and swept once at startup: the v2 manifest and each precompressed sidecar +that differs from it, since a sidecar can be requested by name, and the v1 JSON +under both `.json.gz` and `.json`. JSON chat is matched as decoded, since a +writer may spell letters as `\u` escapes, and the JSON is read as a stream: +only one event is held at a time, so a long position history costs no memory. +The manifest with its sidecars, the `.json.gz` and the `.json` are each checked +and served on their own: a part the server cannot vouch for is not served, and +keeps only itself from being served, so a damaged copy in one format leaves the +other playable. That covers a JSON it cannot read, a manifest of no schema it +writes, and a sidecar left without its manifest, as a partial restore can leave +one. `chat_redaction_revision` marks a recording once all three are clean. No +file that can hold chat is served if it belongs to no recording or no check +reads it: a `manifest.*` file other than the manifest and its sidecars, or a +file under the temporary name it was written under, which a crash from before +masking may have left. Only the manifest's own sidecars stand in for a file +that is asked for. A sidecar is removed before its artifact is replaced, so a +failure part way leaves none of the old bytes. An upload is staged in a directory of its own under +`.upload-staging/`, which `/data/` never serves and no recording may be named +after, and masked there before it is published by a rename, because a replaced +recording keeps its mark until the new row is written. An upload that is not a +JSON object is refused. `/data/` serves a file only by the name it is stored +under: no backslash, and on Windows no other case, trailing dot or space, 8.3 +short name or stream suffix. Conversion carries chat into v1 protobuf as JSON +in the event message, masked too, and playback masks again. The v1 JSON chat entry is `[frame, "chat", +message, fromName, channel]`; copies written earlier end at the message. + Each accepted mission gets one unique storage key, used for its database row, v2 directory and v1 `.json.gz` copy. At mission end the web writes: diff --git a/docs/testkit.md b/docs/testkit.md index 0b52a42c..a501c37f 100644 --- a/docs/testkit.md +++ b/docs/testkit.md @@ -38,8 +38,8 @@ For a diagnostic goroutine-leak profile after three synthetic reconnect-and-disc | `route-access` | Prefixed viewer access to stored JSON and v2-generated downloads, protected admin mutations, and producer credential rejection | | `steam-boundary` | Fake OpenID verifier and loopback profile API, denied allowlist access and provider errors | | `stream-recovery` | Loopback reconnect, repeated starts, partial replacement, durable end, repeated discard, and fake-clock tests for reservation timeouts and a failed keepalive write | -| `conversion-recovery` | Temporary conversion artifacts, status failures and admin retry | -| `playback-delivery` | Synthetic artifact serving and decoding, v2 to v1 export, lazy sidecar replay and Gear exports, event-time factions, and bounded chunk traversal | +| `conversion-recovery` | Temporary conversion artifacts, status failures, admin retry, and player index jobs that finish after their recording was deleted or replaced | +| `playback-delivery` | Synthetic artifact serving and decoding, v2 to v1 export, lazy sidecar replay and Gear exports, event-time factions, bounded chunk traversal, converted chat, and #login passwords masked in stored files, their sidecars and uploads before any is served, with a large recording checked in bounded memory, each format checked and served on its own, and no staged upload, orphaned sidecar, leftover temporary copy or other name of a file served | | `map-boundary` | Synthetic ZIP and job lifecycle, authenticated SSE, stubbed CDN fallback | | `startup` | Fake dependencies for startup, failure and shutdown wiring | diff --git a/internal/conversion/players_test.go b/internal/conversion/players_test.go new file mode 100644 index 00000000..46e6484d --- /dev/null +++ b/internal/conversion/players_test.go @@ -0,0 +1,393 @@ +package conversion + +import ( + "compress/gzip" + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/OCAP2/web/internal/server" + "github.com/OCAP2/web/internal/storage" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +// playersRecording is a synthetic v1 JSON recording: two players on opposing +// sides (one respawned under another case of their name), an AI rifleman, a +// vehicle and a Zeus operator. +const playersRecording = `{ + "worldName": "altis", + "missionName": "Synthetic players", + "captureDelay": 1, + "endFrame": 100, + "entities": [ + {"id": 1, "type": "unit", "name": "Nosey", "side": "WEST", "group": "Alpha 1-1", "role": "Rifleman", "isPlayer": 1, "startFrameNum": 0, "positions": [], "framesFired": []}, + {"id": 2, "type": "unit", "name": "Nomad", "side": "EAST", "group": "Bravo", "role": "Medic", "isPlayer": 1, "startFrameNum": 0, "positions": [], "framesFired": []}, + {"id": 3, "type": "unit", "name": "Rifleman", "side": "WEST", "isPlayer": 0, "startFrameNum": 0, "positions": [], "framesFired": []}, + {"id": 4, "type": "unit", "name": "NOSEY", "side": "WEST", "group": "Charlie", "role": "Pilot", "isPlayer": 1, "startFrameNum": 50, "positions": [], "framesFired": []}, + {"id": 5, "type": "car", "name": "Offroad", "class": "car", "startFrameNum": 0, "positions": [], "framesFired": []} + ], + "events": [ + [10, "killed", 2, [1, "rifle"], 50], + [11, "killed", 3, [1, "rifle"], 20], + [12, "killed", 5, [2, "launcher"], 80], + [13, "killed", 1, [2, "rifle"], 30], + [14, "killed", 2, [2, "grenade"], 0] + ], + "times": [] +}` + +// uidRecording is a synthetic v1 JSON recording from an addon that sends Steam +// UIDs: on player units and on connection events. Nomad's unit carries none, +// but their connection does. +const uidRecording = `{ + "worldName": "altis", + "missionName": "Synthetic UIDs", + "captureDelay": 1, + "endFrame": 100, + "entities": [ + {"id": 1, "type": "unit", "name": "Nosey", "side": "WEST", "isPlayer": 1, "playerUid": "76561190000000001", "startFrameNum": 0, "positions": [], "framesFired": []}, + {"id": 2, "type": "unit", "name": "Nomad", "side": "EAST", "isPlayer": 1, "startFrameNum": 0, "positions": [], "framesFired": []} + ], + "events": [ + [0, "connected", "Nomad", "76561190000000002"], + [10, "killed", 2, [1, "rifle"], 50] + ], + "times": [] +}` + +// writeRecording writes a gzipped JSON recording into dir as name.json.gz. +func writeRecording(t *testing.T, dir, name, content string) { + t.Helper() + f, err := os.Create(filepath.Join(dir, name+".json.gz")) + require.NoError(t, err) + gw := gzip.NewWriter(f) + _, err = gw.Write([]byte(content)) + require.NoError(t, err) + require.NoError(t, gw.Close()) + require.NoError(t, f.Close()) +} + +func TestComputePlayers(t *testing.T) { + manifest := &storage.Manifest{ + Entities: []storage.EntityDef{ + {ID: 1, Type: "unit", Name: "Nosey", Side: "WEST", Role: "Rifleman", Group: "Alpha", IsPlayer: true}, + {ID: 2, Type: "unit", Name: "Nomad", Side: "EAST", IsPlayer: true}, + {ID: 3, Type: "unit", Name: "Rifleman", Side: "WEST"}, + {ID: 4, Type: "unit", Name: " nosey ", Side: "EAST", Role: "Pilot", IsPlayer: true}, + {ID: 5, Type: "vehicle", Name: "Offroad"}, + {ID: 6, Type: "unit", Name: " ", IsPlayer: true}, + {ID: 7, Type: "unit", Name: "Sideless", IsPlayer: true}, + {ID: 8, Type: "unit", Name: "Also sideless"}, + }, + Events: []storage.Event{ + {Type: "killed", SourceID: 1, TargetID: 2}, // kill + {Type: "killed", SourceID: 1, TargetID: 3}, // team kill, also a kill + {Type: "killed", SourceID: 4, TargetID: 5}, // vehicle kill by the respawned Nosey + {Type: "killed", SourceID: 2, TargetID: 2}, // suicide: a death, no kill + {Type: "killed", SourceID: 3, TargetID: 1}, // death to AI + {Type: "killed", SourceID: 1, TargetID: 99}, // unknown victim + {Type: "killed", SourceID: 7, TargetID: 8}, // no sides: no team kill + {Type: "hit", SourceID: 1, TargetID: 2}, + {Type: "zeusEntity", Message: `{"curatorId": 1, "name": "Game Master"}`}, + {Type: "zeusEntity", Message: `{"curatorId": 2, "name": "NOMAD"}`}, + {Type: "zeusEntity", Message: `{"curatorId": 3, "name": ""}`}, + {Type: "zeusEntity", Message: `not json`}, + }, + } + + assert.Equal(t, []server.OperationPlayer{ + {Name: "Nosey", Side: "WEST", Role: "Rifleman", Group: "Alpha", Kills: 2, TeamKills: 1, VehicleKills: 1, Deaths: 1}, + {Name: "Nomad", Side: "EAST", Deaths: 2}, + {Name: "Sideless", Kills: 1}, + {Name: "Game Master", Side: "VIRTUAL", Role: "Zeus"}, + }, computePlayers(manifest)) + + assert.Empty(t, computePlayers(&storage.Manifest{})) +} + +// A Steam UID identifies a player under any name. A unit, connection or Zeus +// slot without one takes the UID its name was seen with in the recording, +// unless two UIDs share that name. +func TestComputePlayersBySteamUID(t *testing.T) { + const nosey, raven, twinA, twinB, viper, zeus = "76561190000000001", "76561190000000002", "76561190000000003", "76561190000000004", "76561190000000005", "76561190000000006" + manifest := &storage.Manifest{ + Entities: []storage.EntityDef{ + {ID: 1, Type: "unit", Name: "Nosey", Side: "WEST", IsPlayer: true, PlayerUID: " " + nosey + " "}, + {ID: 2, Type: "unit", Name: "nosey", Side: "WEST", Role: "Pilot", IsPlayer: true}, // respawn without a UID + {ID: 3, Type: "unit", Name: "Raven", Side: "EAST", IsPlayer: true}, // UID from the connection + {ID: 4, Type: "unit", Name: "Twin", IsPlayer: true, PlayerUID: twinA}, + {ID: 5, Type: "unit", Name: "Twin", IsPlayer: true, PlayerUID: twinB}, + {ID: 6, Type: "unit", Name: "Twin", IsPlayer: true}, // two UIDs share the name + {ID: 7, Type: "unit", Name: "Nomad", IsPlayer: true}, + {ID: 8, Type: "unit", Name: "Viper", Side: "EAST", IsPlayer: true, PlayerUID: viper}, + {ID: 9, Type: "unit", Name: "Rifleman", Side: "EAST", PlayerUID: "ignored for AI"}, + }, + Events: []storage.Event{ + {Type: "connected", Message: "Raven", PlayerUID: raven}, + {Type: "disconnected", Message: "Raven"}, + {Type: "connected", Message: "", PlayerUID: "no name"}, + {Type: "connected", Message: "", PlayerUID: nosey}, // a connection without a name adds none + {Type: "connected", Message: "Nosey on the server", PlayerUID: nosey}, + {Type: "connected", Message: "Watcher", PlayerUID: "76561190000000007"}, // connected, never took part + {Type: "killed", SourceID: 2, TargetID: 3}, + {Type: "zeusEntity", Message: `{"name": "Game Master", "playerUid": "` + zeus + `"}`}, + {Type: "zeusEntity", Message: `{"name": "Viper"}`}, // the Viper unit's UID + {Type: "zeusEntity", Message: `{"name": "Nosey alt", "playerUid": "` + nosey + `"}`}, // Nosey under another name + }, + } + + assert.Equal(t, []server.OperationPlayer{ + {UID: nosey, Name: "Nosey", OtherNames: []string{"Nosey alt", "Nosey on the server"}, Side: "WEST", Kills: 1}, + {UID: raven, Name: "Raven", Side: "EAST", Deaths: 1}, + {UID: twinA, Name: "Twin"}, + {UID: twinB, Name: "Twin"}, + {Name: "Twin"}, + {Name: "Nomad"}, + {UID: viper, Name: "Viper", Side: "EAST"}, + {UID: zeus, Name: "Game Master", Side: "VIRTUAL", Role: "Zeus"}, + }, computePlayers(manifest)) +} + +// Two units of one recording that share a Steam UID are one player under both +// names: searchable by either, with the other listed, and counted once. +func TestPlayerIndexKeepsBothNamesOfAUID(t *testing.T) { + dir := t.TempDir() + writeRecording(t, dir, "renamed", `{ + "worldName": "altis", "missionName": "Renamed", "captureDelay": 1, "endFrame": 10, + "entities": [ + {"id": 1, "type": "unit", "name": "Nosey", "side": "WEST", "isPlayer": 1, "playerUid": "76561190000000001", "startFrameNum": 0, "positions": [], "framesFired": []}, + {"id": 2, "type": "unit", "name": "Raven", "side": "WEST", "isPlayer": 1, "playerUid": "76561190000000001", "startFrameNum": 5, "positions": [], "framesFired": []} + ], + "events": [], "times": [] + }`) + repo, err := server.NewRepoOperation(filepath.Join(dir, "operations.db")) + require.NoError(t, err) + t.Cleanup(func() { _ = repo.Close() }) + op := &server.Operation{WorldName: "altis", MissionName: "Renamed", Filename: "renamed", Date: "2026-01-01", ConversionStatus: server.ConversionStatusCompleted} + require.NoError(t, repo.Store(t.Context(), op)) + NewWorker(repo, Config{DataDir: dir}).BackfillStats(t.Context()) + + found, err := repo.SearchPlayers(t.Context(), "raven", 10) + require.NoError(t, err) + require.Len(t, found, 1) + assert.Equal(t, 1, found[0].Missions) + profile, err := repo.GetPlayerProfile(t.Context(), "76561190000000001", "") + require.NoError(t, err) + assert.Equal(t, "Nosey", profile.Name) + assert.Equal(t, []string{"Raven"}, profile.Aliases) +} + +// A player's connection can carry another name than their unit. That name +// finds them and is listed as an alias, without another participation; a +// connection alone indexes no one. +func TestPlayerIndexKeepsConnectionNames(t *testing.T) { + dir := t.TempDir() + writeRecording(t, dir, "joined", `{ + "worldName": "altis", "missionName": "Joined", "captureDelay": 1, "endFrame": 10, + "entities": [ + {"id": 1, "type": "unit", "name": "Raven", "side": "WEST", "isPlayer": 1, "playerUid": "76561190000000001", "startFrameNum": 0, "positions": [], "framesFired": []} + ], + "events": [ + [0, "connected", "Nosey", "76561190000000001"], + [0, "connected", "Watcher", "76561190000000009"], + [9, "disconnected", "Nosey", "76561190000000001"] + ], + "times": [] + }`) + repo, err := server.NewRepoOperation(filepath.Join(dir, "operations.db")) + require.NoError(t, err) + t.Cleanup(func() { _ = repo.Close() }) + op := &server.Operation{WorldName: "altis", MissionName: "Joined", Filename: "joined", Date: "2026-01-01", ConversionStatus: server.ConversionStatusCompleted} + require.NoError(t, repo.Store(t.Context(), op)) + NewWorker(repo, Config{DataDir: dir}).BackfillStats(t.Context()) + + found, err := repo.SearchPlayers(t.Context(), "nosey", 10) + require.NoError(t, err) + require.Len(t, found, 1) + assert.Equal(t, server.PlayerSummary{UID: "76561190000000001", Name: "Raven", Missions: 1, LastPlayed: "2026-01-01"}, found[0]) + profile, err := repo.GetPlayerProfile(t.Context(), "76561190000000001", "") + require.NoError(t, err) + assert.Equal(t, []string{"Nosey"}, profile.Aliases) + assert.Equal(t, []string{"Nosey"}, profile.Recordings[0].OtherNames) + + found, err = repo.SearchPlayers(t.Context(), "watcher", 10) + require.NoError(t, err) + assert.Empty(t, found, "a connection alone takes no part") + ops, err := repo.Select(t.Context(), server.Filter{Player: "Nosey"}) + require.NoError(t, err) + assert.Len(t, ops, 1) +} + +// TestPlayerIndexEndToEnd indexes a JSON recording into a real repository and +// finds it through player search. +func TestPlayerIndexEndToEnd(t *testing.T) { + dir := t.TempDir() + writeRecording(t, dir, "synthetic", playersRecording) + repo, err := server.NewRepoOperation(filepath.Join(dir, "operations.db")) + require.NoError(t, err) + t.Cleanup(func() { _ = repo.Close() }) + op := &server.Operation{WorldName: "altis", MissionName: "Synthetic players", Filename: "synthetic", Date: "2026-01-01", ConversionStatus: server.ConversionStatusCompleted} + require.NoError(t, repo.Store(t.Context(), op)) + + w := NewWorker(repo, Config{DataDir: dir}) + w.BackfillStats(t.Context()) + + profile, err := repo.GetPlayerProfile(t.Context(), "", "nosey") + require.NoError(t, err) + assert.Equal(t, 1, profile.Missions) + assert.Equal(t, 2, profile.Kills) + assert.Equal(t, 1, profile.TeamKills) + assert.Equal(t, 1, profile.Deaths) + assert.Equal(t, "Rifleman", profile.Recordings[0].Role) + + nomad, err := repo.GetPlayerProfile(t.Context(), "", "Nomad") + require.NoError(t, err) + assert.Equal(t, 1, nomad.VehicleKills) + assert.Equal(t, 2, nomad.Deaths, "killed once and once by their own grenade") + assert.Equal(t, 1, nomad.Kills) + + pending, err := repo.SelectPlayerIndexBackfill(t.Context()) + require.NoError(t, err) + assert.Empty(t, pending, "computing the stats indexed the players") +} + +func TestIndexPlayersFor(t *testing.T) { + dir := t.TempDir() + writeRecording(t, dir, "synthetic", playersRecording) + + repo := newMockRepo() + w := NewWorker(repo, Config{DataDir: dir}) + require.NoError(t, w.IndexPlayersFor(t.Context(), 7, "synthetic")) + assert.Len(t, repo.players[7], 2) + + assert.ErrorContains(t, w.IndexPlayersFor(t.Context(), 8, "missing"), "read manifest for players") + + failing := newErrorMockRepo() + failing.replacePlayersErr = errors.New("index boom") + w = NewWorker(failing, Config{DataDir: dir}) + assert.ErrorContains(t, w.IndexPlayersFor(t.Context(), 7, "synthetic"), "index boom") + assert.ErrorContains(t, w.ComputeStatsFor(t.Context(), 7, "synthetic"), "index players") +} + +func TestConvertOperationIndexesPlayers(t *testing.T) { + dir := t.TempDir() + writeRecording(t, dir, "synthetic", uidRecording) + + repo := newMockRepo() + w := NewWorker(repo, Config{DataDir: dir}) + require.NoError(t, w.convertOperation(t.Context(), server.Operation{ID: 1, Filename: "synthetic"})) + assert.Equal(t, []server.OperationPlayer{ + {UID: "76561190000000001", Name: "Nosey", Side: "WEST", Kills: 1}, + {UID: "76561190000000002", Name: "Nomad", Side: "EAST", Deaths: 1}, + }, repo.players[1], "the Steam UIDs come from the JSON source, which the v1 protobuf lacks") + + // A failed index does not fail the conversion. + dir2 := t.TempDir() + writeRecording(t, dir2, "synthetic", playersRecording) + failing := newErrorMockRepo() + failing.replacePlayersErr = errors.New("index boom") + w = NewWorker(failing, Config{DataDir: dir2}) + require.NoError(t, w.convertOperation(t.Context(), server.Operation{ID: 2, Filename: "synthetic"})) + assert.Equal(t, server.ConversionStatusCompleted, failing.status[2]) +} + +// TestReadManifestSources reads a native v2 manifest as it is, a v1 recording +// from its JSON whenever that is there, and the converted v1 protobuf only +// without it. +func TestReadManifestSources(t *testing.T) { + dir := t.TempDir() + w := NewWorker(newMockRepo(), Config{DataDir: dir}) + uidsOf := func(m *storage.Manifest) []string { + var uids []string + for _, ent := range m.Entities { + uids = append(uids, ent.PlayerUID) + } + return uids + } + + writeRecording(t, dir, "converted", uidRecording) + require.NoError(t, w.engine.Convert(t.Context(), filepath.Join(dir, "converted.json.gz"), filepath.Join(dir, "converted"))) + m, err := w.readManifest(t.Context(), "converted") + require.NoError(t, err) + assert.Equal(t, []string{"76561190000000001", ""}, uidsOf(m), "the JSON source wins over the converted protobuf") + assert.Equal(t, "connected", m.Events[0].Type) + assert.Equal(t, "76561190000000002", m.Events[0].PlayerUID) + + require.NoError(t, os.Remove(filepath.Join(dir, "converted.json.gz"))) + m, err = w.readManifest(t.Context(), "converted") + require.NoError(t, err) + assert.Equal(t, "Synthetic UIDs", m.MissionName) + assert.Equal(t, []string{"", ""}, uidsOf(m), "without its JSON the converted protobuf has no UIDs") + + writeRecording(t, dir, "unconverted", uidRecording) + m, err = w.readManifest(t.Context(), "unconverted") + require.NoError(t, err) + assert.Equal(t, []string{"76561190000000001", ""}, uidsOf(m)) + + require.NoError(t, os.MkdirAll(filepath.Join(dir, "native"), 0o755)) + data, err := proto.Marshal(&pbv2.Manifest{Version: 2, FrameCount: 5, Soldiers: []*pbv2.SoldierDef{ + {Id: 1, Name: "Viper", IsPlayer: true, PlayerUid: "76561190000000005"}, + }}) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, "native", "manifest.pb"), data, 0o644)) + // A stray JSON next to a native recording is not read. + writeRecording(t, dir, "native", uidRecording) + m, err = w.readManifest(t.Context(), "native") + require.NoError(t, err) + assert.Equal(t, uint32(2), m.Version) + assert.Equal(t, []string{"76561190000000005"}, uidsOf(m)) + + _, err = w.readManifest(t.Context(), "missing") + assert.EqualError(t, err, "recording not found: missing") +} + +// playerBackfillRepo serves a player index backfill. +type playerBackfillRepo struct { + *mockRepo + ops []server.Operation + err error +} + +func (r *playerBackfillRepo) SelectPlayerIndexBackfill(context.Context) ([]server.Operation, error) { + return r.ops, r.err +} + +func TestBackfillPlayerIndex(t *testing.T) { + dir := t.TempDir() + writeRecording(t, dir, "synthetic", playersRecording) + + t.Run("indexes readable recordings and skips the rest", func(t *testing.T) { + repo := &playerBackfillRepo{mockRepo: newMockRepo(), ops: []server.Operation{ + {ID: 1, Filename: "synthetic"}, + {ID: 2, Filename: "missing"}, + }} + NewWorker(repo, Config{DataDir: dir}).backfillPlayerIndex(t.Context()) + assert.Len(t, repo.players[1], 2) + assert.NotContains(t, repo.players, int64(2)) + }) + + t.Run("nothing readable", func(t *testing.T) { + repo := &playerBackfillRepo{mockRepo: newMockRepo(), ops: []server.Operation{{ID: 2, Filename: "missing"}}} + NewWorker(repo, Config{DataDir: dir}).backfillPlayerIndex(t.Context()) + assert.Empty(t, repo.players) + }) + + t.Run("select failure", func(t *testing.T) { + repo := &playerBackfillRepo{mockRepo: newMockRepo(), err: errors.New("select boom")} + NewWorker(repo, Config{DataDir: dir}).backfillPlayerIndex(t.Context()) + assert.Empty(t, repo.players) + }) + + t.Run("cancelled", func(t *testing.T) { + repo := &playerBackfillRepo{mockRepo: newMockRepo(), ops: []server.Operation{{ID: 1, Filename: "synthetic"}}} + ctx, cancel := context.WithCancel(t.Context()) + cancel() + NewWorker(repo, Config{DataDir: dir}).backfillPlayerIndex(ctx) + assert.Empty(t, repo.players) + }) +} diff --git a/internal/conversion/worker.go b/internal/conversion/worker.go index 268689d7..732a9434 100644 --- a/internal/conversion/worker.go +++ b/internal/conversion/worker.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" "path/filepath" + "strings" "time" "github.com/OCAP2/web/internal/server" @@ -26,6 +27,8 @@ type OperationRepo interface { UpdateSchemaVersion(ctx context.Context, id int64, version uint32) error UpdateChunkCount(ctx context.Context, id int64, count int) error UpdateOperationStats(ctx context.Context, id int64, playerCount, killCount, playerKillCount int, sideComposition server.SideComposition) error + ReplaceOperationPlayers(ctx context.Context, id int64, players []server.OperationPlayer) error + SelectPlayerIndexBackfill(ctx context.Context) ([]server.Operation, error) } // Worker handles background conversion of JSON recordings to protobuf format @@ -212,6 +215,11 @@ func (w *Worker) convertOperation(ctx context.Context, op server.Operation) erro if err := w.repo.UpdateOperationStats(ctx, op.ID, playerCount, killCount, playerKillCount, sides); err != nil { slog.Warn("failed to update operation stats", "error", err) } + // The v1 protobuf manifest has no Steam UIDs, so players are indexed + // from the JSON source instead. + if err := w.IndexPlayersFor(ctx, op.ID, op.Filename); err != nil { + slog.Warn("failed to index operation players", "error", err) + } } // Update database format @@ -323,36 +331,226 @@ func computeStats(manifest *storage.Manifest) (playerCount, killCount, playerKil return } -// ComputeStatsFor derives and stores the dashboard stats for one operation -// without converting it. +// computePlayers derives each player's part in a recording from its manifest. +// A player is their Steam UID when the recording has one and their name +// otherwise (see server.PlayerKey), one player across respawns; side, role and +// group come from their first unit, and every other name they used is kept, +// on a unit, a Zeus slot or a connection. Kills count like the playback stats tab: +// a team kill is also a kill, a vehicle kill is not, and a suicide is a death +// but no kill. Zeus operators take part on the VIRTUAL side. +func computePlayers(manifest *storage.Manifest) []server.OperationPlayer { + var players []*server.OperationPlayer + byKey := make(map[string]*server.OperationPlayer) + player := func(uid, name, side, role, group string) *server.OperationPlayer { + key := server.PlayerKey(uid, name) + p := byKey[key] + if p == nil { + p = &server.OperationPlayer{UID: uid, Name: strings.TrimSpace(name), Side: side, Role: role, Group: group} + byKey[key] = p + players = append(players, p) + } else { + p.AddName(name) + } + return p + } + + // Player units, connections and Zeus slots each may carry the Steam UID. + // A name seen with a single UID anywhere in the recording takes it, so a + // unit or Zeus slot recorded without one still joins its player. A name + // two UIDs share stays ambiguous and is kept by name. + uids := make(map[string]string) + ambiguous := make(map[string]bool) + learn := func(name, uid string) { + key, uid := server.NameKey(name), strings.TrimSpace(uid) + if key == "" || uid == "" { + return + } + if known, ok := uids[key]; ok && known != uid { + ambiguous[key] = true + } + uids[key] = uid + } + uidOf := func(name, uid string) string { + if uid = strings.TrimSpace(uid); uid != "" { + return uid + } + key := server.NameKey(name) + if ambiguous[key] { + return "" + } + return uids[key] + } + + type zeusSlot struct{ name, uid string } + var zeus []zeusSlot + for _, ent := range manifest.Entities { + if ent.Type == "unit" && ent.IsPlayer { + learn(ent.Name, ent.PlayerUID) + } + } + for _, evt := range manifest.Events { + switch evt.Type { + case "connected", "disconnected": + learn(evt.Message, evt.PlayerUID) + case "zeusEntity": + var payload struct { + Name string `json:"name"` + PlayerUID string `json:"playerUid"` + } + if json.Unmarshal([]byte(evt.Message), &payload) == nil && server.NameKey(payload.Name) != "" { + learn(payload.Name, payload.PlayerUID) + zeus = append(zeus, zeusSlot{payload.Name, payload.PlayerUID}) + } + } + } + + owner := make(map[uint32]*server.OperationPlayer) // player unit id -> player + unitSide := make(map[uint32]string) + vehicles := make(map[uint32]bool) + for _, ent := range manifest.Entities { + if ent.Type != "unit" { + vehicles[ent.ID] = true + continue + } + unitSide[ent.ID] = ent.Side + if ent.IsPlayer && server.NameKey(ent.Name) != "" { + owner[ent.ID] = player(uidOf(ent.Name, ent.PlayerUID), ent.Name, ent.Side, ent.Role, ent.Group) + } + } + for _, slot := range zeus { + player(uidOf(slot.name, slot.uid), slot.name, "VIRTUAL", "Zeus", "") + } + // A connection can carry another name of a player who took part. It adds + // that name, but takes no part on its own: a connection alone is an + // observer, or someone who left before taking a slot. + for _, evt := range manifest.Events { + if evt.Type == "connected" || evt.Type == "disconnected" { + if p := byKey[server.PlayerKey(uidOf(evt.Message, evt.PlayerUID), evt.Message)]; p != nil { + p.AddName(evt.Message) + } + } + } + + for _, evt := range manifest.Events { + switch evt.Type { + case "killed": + if victim := owner[evt.TargetID]; victim != nil { + victim.Deaths++ + } + killer := owner[evt.SourceID] + if killer == nil || evt.SourceID == evt.TargetID { + continue + } + if vehicles[evt.TargetID] { + killer.VehicleKills++ + } else if victimSide, ok := unitSide[evt.TargetID]; ok { + killer.Kills++ + if victimSide != "" && victimSide == unitSide[evt.SourceID] { + killer.TeamKills++ + } + } + } + } + + result := make([]server.OperationPlayer, len(players)) + for i, p := range players { + result[i] = *p + } + return result +} + +// readManifest reads an operation's manifest for stats and the player index. +// A native v2 manifest has everything. A v1 recording is streamed from its +// JSON whenever that is still there, converted or not: the converted v1 +// protobuf manifest has no Steam UIDs, and streaming keeps a large recording +// out of memory. Without the JSON the v1 protobuf manifest still serves, with +// players identified by name. +func (w *Worker) readManifest(ctx context.Context, filename string) (*storage.Manifest, error) { + manifest, err := w.engine.GetManifest(ctx, filename) + if err == nil && manifest.Version >= 2 { + return manifest, nil + } + streamed, jsonErr := storage.NewJSONEngine(w.dataDir).StreamManifest(ctx, filename) + if jsonErr == nil { + return streamed, nil + } + if err != nil { + return nil, jsonErr + } + return manifest, nil +} + +// ComputeStatsFor derives and stores the dashboard stats and the player index +// for one operation without converting it. // -// The stats are read out of the manifest and have nothing to do with the -// protobuf format, so this deliberately works on an unconverted recording too: -// the protobuf engine is tried first and a plain `.json.gz` falls back to the -// JSON engine. That is what lets a deployment with conversion switched off still -// show force composition and kill counts. +// Both are read out of the manifest and have nothing to do with the protobuf +// format, so this deliberately works on an unconverted recording too. That is +// what lets a deployment with conversion switched off still show force +// composition, kill counts and player profiles. func (w *Worker) ComputeStatsFor(ctx context.Context, id int64, filename string) error { - manifest, err := w.engine.GetManifest(ctx, filename) + manifest, err := w.readManifest(ctx, filename) if err != nil { - jsonEngine := storage.NewJSONEngine(w.dataDir) - manifest, err = jsonEngine.GetManifest(ctx, filename) - if err != nil { - return fmt.Errorf("read manifest for stats: %w", err) - } + return fmt.Errorf("read manifest for stats: %w", err) } playerCount, killCount, playerKillCount, sides := computeStats(manifest) if err := w.repo.UpdateOperationStats(ctx, id, playerCount, killCount, playerKillCount, sides); err != nil { return fmt.Errorf("store stats: %w", err) } + if err := w.repo.ReplaceOperationPlayers(ctx, id, computePlayers(manifest)); err != nil { + return fmt.Errorf("index players: %w", err) + } + return nil +} + +// IndexPlayersFor indexes the players of one operation for player search and +// profiles. +func (w *Worker) IndexPlayersFor(ctx context.Context, id int64, filename string) error { + manifest, err := w.readManifest(ctx, filename) + if err != nil { + return fmt.Errorf("read manifest for players: %w", err) + } + if err := w.repo.ReplaceOperationPlayers(ctx, id, computePlayers(manifest)); err != nil { + return fmt.Errorf("index players: %w", err) + } return nil } -// BackfillStats populates stats for completed operations that don't have them -// yet. Exported because it has to run whether or not conversion is enabled -- -// with conversion off it is the only thing that ever fills in stats for -// recordings uploaded before the fix that added the upload-time path. +// backfillPlayerIndex indexes the players of completed operations stored +// before the player index existed or by an older revision of it. +func (w *Worker) backfillPlayerIndex(ctx context.Context) { + ops, err := w.repo.SelectPlayerIndexBackfill(ctx) + if err != nil { + slog.Error("failed to select operations for player index backfill", "error", err) + return + } + indexed := 0 + for _, op := range ops { + if ctx.Err() != nil { + return + } + if err := w.IndexPlayersFor(ctx, op.ID, op.Filename); err != nil { + slog.Debug("skipping player index backfill", "operation_id", op.ID, "error", err) + continue + } + indexed++ + } + if indexed > 0 { + slog.Info("player index backfill completed", "indexed", indexed, "total", len(ops)) + } +} + +// BackfillStats populates stats and the player index for completed operations +// that don't have them yet. Exported because it has to run whether or not +// conversion is enabled -- with conversion off it is the only thing that ever +// fills in stats for recordings uploaded before the fix that added the +// upload-time path. Stats go first: computing them indexes players too. func (w *Worker) BackfillStats(ctx context.Context) { + w.backfillStats(ctx) + w.backfillPlayerIndex(ctx) +} + +func (w *Worker) backfillStats(ctx context.Context) { ops, err := w.repo.SelectStatsBackfill(ctx) if err != nil { slog.Error("failed to select operations for stats backfill", "error", err) diff --git a/internal/conversion/worker_test.go b/internal/conversion/worker_test.go index 249247e0..9e2c5ae3 100644 --- a/internal/conversion/worker_test.go +++ b/internal/conversion/worker_test.go @@ -26,6 +26,7 @@ type mockRepo struct { chunkCount map[int64]int byStatus map[string][]server.Operation stats map[int64][3]string // playerCount, killCount, sideComposition + players map[int64][]server.OperationPlayer } func newMockRepo() *mockRepo { @@ -38,6 +39,7 @@ func newMockRepo() *mockRepo { chunkCount: make(map[int64]int), byStatus: make(map[string][]server.Operation), stats: make(map[int64][3]string), + players: make(map[int64][]server.OperationPlayer), } } @@ -86,6 +88,15 @@ func (m *mockRepo) SelectStatsBackfill(ctx context.Context) ([]server.Operation, return nil, nil } +func (m *mockRepo) ReplaceOperationPlayers(ctx context.Context, id int64, players []server.OperationPlayer) error { + m.players[id] = players + return nil +} + +func (m *mockRepo) SelectPlayerIndexBackfill(ctx context.Context) ([]server.Operation, error) { + return nil, nil +} + func (m *mockRepo) ResetConversionStatus(ctx context.Context, fromStatus, toStatus string) (int64, error) { ops := m.byStatus[fromStatus] delete(m.byStatus, fromStatus) @@ -420,6 +431,7 @@ type errorMockRepo struct { updateDurationErr error updateChunkCountErr error updateOperationStatsErr error + replacePlayersErr error statsBackfill []server.Operation failStatusUpdateOnID int64 // only fail for this ID failStatusUpdateAfter string // only fail when setting this status @@ -503,6 +515,14 @@ func (m *errorMockRepo) SelectStatsBackfill(ctx context.Context) ([]server.Opera return m.statsBackfill, nil } +func (m *errorMockRepo) ReplaceOperationPlayers(ctx context.Context, id int64, players []server.OperationPlayer) error { + return m.replacePlayersErr +} + +func (m *errorMockRepo) SelectPlayerIndexBackfill(ctx context.Context) ([]server.Operation, error) { + return nil, nil +} + func (m *errorMockRepo) ResetConversionStatus(ctx context.Context, fromStatus, toStatus string) (int64, error) { if m.resetConversionStatusErr != nil { return 0, m.resetConversionStatusErr diff --git a/internal/ingestion/chat_login_test.go b/internal/ingestion/chat_login_test.go new file mode 100644 index 00000000..fa5165b4 --- /dev/null +++ b/internal/ingestion/chat_login_test.go @@ -0,0 +1,35 @@ +package ingestion + +import ( + "testing" + + "github.com/OCAP2/extension/v5/pkg/core" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestHandleChatEventMasksLoginPassword(t *testing.T) { + s := NewSession() + s.HandleChatEvent(core.ChatEvent{CaptureFrame: 3, Channel: "Global", FromName: "Nosey", Message: " #login synthetic-password"}) + s.HandleChatEvent(core.ChatEvent{CaptureFrame: 4, Channel: "Side", FromName: "Nosey", Message: "moving up"}) + require.Len(t, s.events, 2) + assert.Equal(t, "#login ********", s.events[0].chat.Message, "the stored message must not carry the password") + + events := s.ToV1JSON()["events"] + assert.Contains(t, events, []any{core.Frame(3), "chat", "#login ********", "Nosey", "Global"}) + assert.Contains(t, events, []any{core.Frame(4), "chat", "moving up", "Nosey", "Side"}) + assert.NotContains(t, events, []any{core.Frame(3), "chat", " #login synthetic-password", "Nosey", "Global"}) +} + +func TestAppendV2EventMasksStoredLoginPassword(t *testing.T) { + s := NewSession() + appendV2Event(s, &pbv2.Event{FrameNum: 2, Event: &pbv2.Event_Chat{Chat: &pbv2.ChatEvent{Message: "#LOGIN synthetic-password", FromName: "Nosey", Channel: "Global"}}}) + appendV2Event(s, &pbv2.Event{FrameNum: 2, Event: &pbv2.Event_Chat{Chat: &pbv2.ChatEvent{Message: "contact", FromName: "Nosey", Channel: "Group"}}}) + require.Len(t, s.events, 2) + + events := s.ToV1JSON()["events"] + assert.Contains(t, events, []any{core.Frame(2), "chat", "#LOGIN ********", "Nosey", "Global"}, + "a recording stored before masking must not leak the password into the v1 export") + assert.Contains(t, events, []any{core.Frame(2), "chat", "contact", "Nosey", "Group"}) +} diff --git a/internal/ingestion/export_v1_from_v2.go b/internal/ingestion/export_v1_from_v2.go index 65199a8a..aa880370 100644 --- a/internal/ingestion/export_v1_from_v2.go +++ b/internal/ingestion/export_v1_from_v2.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/OCAP2/extension/v5/pkg/core" + "github.com/OCAP2/web/internal/redact" pbv1 "github.com/OCAP2/web/pkg/schemas/protobuf/v1" pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" "google.golang.org/protobuf/proto" @@ -222,7 +223,8 @@ func appendV2Event(s *Session, e *pbv2.Event) { case *pbv2.Event_Chat: c := ev.Chat id := uint(c.SoldierId) - s.events = append(s.events, eventRecord{eventType: "chat", frame: frame, chat: &core.ChatEvent{CaptureFrame: frame, SoldierID: &id, Channel: c.Channel, FromName: c.FromName, Message: c.Message, PlayerUID: c.PlayerUid}}) + // Recordings saved before ingestion masked #login still hold the password. + s.events = append(s.events, eventRecord{eventType: "chat", frame: frame, chat: &core.ChatEvent{CaptureFrame: frame, SoldierID: &id, Channel: c.Channel, FromName: c.FromName, Message: redact.LoginCommand(c.Message), PlayerUID: c.PlayerUid}}) case *pbv2.Event_General: g := ev.General var extra map[string]any diff --git a/internal/ingestion/redact_json.go b/internal/ingestion/redact_json.go new file mode 100644 index 00000000..da0c6b40 --- /dev/null +++ b/internal/ingestion/redact_json.go @@ -0,0 +1,485 @@ +package ingestion + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + + "github.com/OCAP2/web/internal/redact" +) + +// maxJSONDepth is how deeply a recording may nest, the limit encoding/json +// applies. +const maxJSONDepth = 10000 + +// jsonChunk is how much read JSON is collected before it is written on. +const jsonChunk = 32 << 10 + +// errJSONTooDeep is returned for a recording nested deeper than maxJSONDepth. +var errJSONTooDeep = errors.New("JSON nested too deeply") + +// maskJSONChat copies a v1 recording from r to w with the passwords of #login +// chat commands masked, and reports whether there were any. It streams: each +// byte is checked as JSON and passed on as it was read, and only the element +// of the top-level events array being read is held, so a position history of +// any length passes through in a few buffers. A chat event that changed is the +// only value encoded again. Anything after the recording's object is dropped. +// With w io.Discard nothing is kept for it. +func maskJSONChat(r io.Reader, w io.Writer) (bool, error) { + s := &jsonStream{in: bufio.NewReaderSize(r, 64<<10)} + if w != io.Discard { + s.w = w + } + changed, err := s.recording() + if err == nil { + s.flush() + err = s.err + } + if err != nil { + return false, err + } + return changed, nil +} + +// jsonStream reads JSON a byte at a time and passes each byte it reads on to +// w, or to held while an event or key is held back. +type jsonStream struct { + in *bufio.Reader + w io.Writer // nil keeps nothing + out []byte // read and not yet written to w + held []byte + holding bool + err error // the first error writing to w +} + +// recording reads the recording's top-level object. +func (s *jsonStream) recording() (bool, error) { + c, err := s.token() + if err != nil { + return false, err + } + if c != '{' { + return false, syntaxError(c, "the object a recording is") + } + return s.object(1) +} + +// object reads the rest of an object at depth, its brace already read. Depth +// 1 is the recording itself, whose events are masked; it reports whether any +// changed. +func (s *jsonStream) object(depth int) (bool, error) { + if depth > maxJSONDepth { + return false, errJSONTooDeep + } + c, err := s.token() + if err != nil || c == '}' { + return false, err + } + changed := false + for { + if c != '"' { + return false, syntaxError(c, "an object key") + } + events := false + if depth == 1 { + events, err = s.key() + } else { + err = s.str() + } + if err != nil { + return false, err + } + if c, err = s.token(); err != nil { + return false, err + } + if c != ':' { + return false, syntaxError(c, "a colon after an object key") + } + if events { + masked, err := s.events() + if err != nil { + return false, err + } + changed = changed || masked + } else if err := s.value(depth); err != nil { + return false, err + } + if c, err = s.token(); err != nil { + return false, err + } + if c == '}' { + return changed, nil + } + if c != ',' { + return false, syntaxError(c, "a comma or the end of an object") + } + if c, err = s.token(); err != nil { + return false, err + } + } +} + +// key reads the rest of a key of the recording, its quote already read, and +// reports whether it is "events", however its letters are spelled. +func (s *jsonStream) key() (bool, error) { + s.held, s.holding = append(s.held[:0], '"'), true + err := s.str() + s.holding = false + if err != nil { + return false, err + } + var key string + _ = json.Unmarshal(s.held, &key) // str checked the string + s.write(s.held[1:]) // the quote went on before it + return key == "events", nil +} + +// events reads the value of the recording's events key and masks the message +// of each chat event in it, reporting whether any changed. Each event array is +// held while it is read, to be written again if it changed; anything else +// streams through. +func (s *jsonStream) events() (bool, error) { + c, err := s.space() + if err != nil { + return false, err + } + if c != '[' { + return false, s.value(1) + } + s.advance(c) + if c, err = s.space(); err != nil { + return false, err + } + if c == ']' { + s.advance(c) + return false, nil + } + changed := false + for { + if c == '[' { + s.held, s.holding = s.held[:0], true + s.advance(c) + err := s.array(3) + s.holding = false + if err != nil { + return false, err + } + event, masked := maskChatEvent(s.held) + changed = changed || masked + s.write(event) + } else if err := s.value(2); err != nil { + return false, err + } + if c, err = s.token(); err != nil { + return false, err + } + if c == ']' { + return changed, nil + } + if c != ',' { + return false, syntaxError(c, "a comma or the end of the events") + } + if c, err = s.space(); err != nil { + return false, err + } + } +} + +// value reads one value inside a container at depth. +func (s *jsonStream) value(depth int) error { + c, err := s.token() + if err != nil { + return err + } + switch c { + case '{': + _, err := s.object(depth + 1) + return err + case '[': + return s.array(depth + 1) + case '"': + return s.str() + case 't': + return s.literal("rue") + case 'f': + return s.literal("alse") + case 'n': + return s.literal("ull") + } + if c == '-' || isDigit(c) { + return s.number(c) + } + return syntaxError(c, "the start of a value") +} + +// array reads the rest of an array at depth, its bracket already read. +func (s *jsonStream) array(depth int) error { + if depth > maxJSONDepth { + return errJSONTooDeep + } + c, err := s.space() + if err != nil { + return err + } + if c == ']' { + s.advance(c) + return nil + } + for { + if err := s.value(depth); err != nil { + return err + } + if c, err = s.token(); err != nil { + return err + } + if c == ']' { + return nil + } + if c != ',' { + return syntaxError(c, "a comma or the end of an array") + } + } +} + +// str reads the rest of a string, its quote already read, and checks it as +// encoding/json does: no control character left raw and only valid escapes. +func (s *jsonStream) str() error { + for { + c, err := s.take() + if err != nil { + return err + } + switch { + case c == '"': + return nil + case c == '\\': + if err := s.escape(); err != nil { + return err + } + case c < 0x20: + return syntaxError(c, "a string character") + } + } +} + +// escape reads the rest of an escape in a string, its backslash already read. +func (s *jsonStream) escape() error { + c, err := s.take() + if err != nil { + return err + } + switch c { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + return nil + case 'u': + for range 4 { + if c, err = s.take(); err != nil { + return err + } + if !isHex(c) { + return syntaxError(c, "a hexadecimal digit of a \\u escape") + } + } + return nil + } + return syntaxError(c, "an escape character") +} + +// number reads the rest of a number whose first byte, c, was read. +func (s *jsonStream) number(c byte) error { + var err error + if c == '-' { + if c, err = s.take(); err != nil { + return err + } + if !isDigit(c) { + return syntaxError(c, "a digit") + } + } + var next byte + if c == '0' { + next, err = s.peek() // a leading zero stands alone + } else { + next, err = s.digits() + } + if err == nil && next == '.' { + s.advance(next) + next, err = s.someDigits() + } + if err == nil && (next == 'e' || next == 'E') { + s.advance(next) + if next, err = s.peek(); err == nil && (next == '+' || next == '-') { + s.advance(next) + } + if err == nil { + _, err = s.someDigits() + } + } + return err +} + +// digits reads the digits that come next and returns the byte after them, +// unread. +func (s *jsonStream) digits() (byte, error) { + for { + c, err := s.peek() + if err != nil || !isDigit(c) { + return c, err + } + s.advance(c) + } +} + +// someDigits is digits where at least one has to come. +func (s *jsonStream) someDigits() (byte, error) { + c, err := s.take() + if err != nil { + return 0, err + } + if !isDigit(c) { + return 0, syntaxError(c, "a digit") + } + return s.digits() +} + +// literal reads the rest of true, false or null, its first letter read. +func (s *jsonStream) literal(rest string) error { + for i := range len(rest) { + c, err := s.take() + if err != nil { + return err + } + if c != rest[i] { + return syntaxError(c, "the rest of a literal") + } + } + return nil +} + +// token passes the whitespace that comes next and reads the byte after it. +func (s *jsonStream) token() (byte, error) { + if _, err := s.space(); err != nil { + return 0, err + } + return s.take() +} + +// space passes the whitespace that comes next and returns the byte after it, +// unread. +func (s *jsonStream) space() (byte, error) { + for { + c, err := s.peek() + if err != nil || (c != ' ' && c != '\t' && c != '\n' && c != '\r') { + return c, err + } + s.advance(c) + } +} + +// peek returns the next byte without reading it. +func (s *jsonStream) peek() (byte, error) { + next, err := s.in.Peek(1) + if err != nil { + return 0, unexpectedEnd(err) + } + return next[0], nil +} + +// take reads the next byte and passes it on. It stops at a failed write, so a +// rewrite that cannot be stored does not read on to the end. +func (s *jsonStream) take() (byte, error) { + if s.err != nil { + return 0, s.err + } + c, err := s.in.ReadByte() + if err != nil { + return 0, unexpectedEnd(err) + } + s.keep(c) + return c, nil +} + +// advance reads c, the byte peek returned, and passes it on. +func (s *jsonStream) advance(c byte) { + _, _ = s.in.Discard(1) // peek buffered it + s.keep(c) +} + +// keep passes a byte read on: to the held bytes, or towards w. +func (s *jsonStream) keep(c byte) { + switch { + case s.holding: + s.held = append(s.held, c) + case s.w != nil: + s.out = append(s.out, c) + if len(s.out) >= jsonChunk { + s.flush() + } + } +} + +// write passes data on towards w as if it had been read. +func (s *jsonStream) write(data []byte) { + if s.w != nil { + s.out = append(s.out, data...) + if len(s.out) >= jsonChunk { + s.flush() + } + } +} + +// flush writes what was passed on so far to w. +func (s *jsonStream) flush() { + if s.err == nil && len(s.out) > 0 { + _, s.err = s.w.Write(s.out) + } + s.out = s.out[:0] +} + +// maskChatEvent masks the message of a [frame, "chat", message, ...] event, +// which is valid JSON. Anything else, or a chat event with no password, is +// returned as it is. The kind is written "chat" or with an escape in it, so +// an event with neither is not decoded at all. +func maskChatEvent(event []byte) ([]byte, bool) { + if !bytes.Contains(event, []byte(`"chat"`)) && bytes.IndexByte(event, '\\') < 0 { + return event, false + } + var fields []json.RawMessage + var kind, message string + if json.Unmarshal(event, &fields) != nil || len(fields) < 3 || + json.Unmarshal(fields[1], &kind) != nil || kind != "chat" || + json.Unmarshal(fields[2], &message) != nil { + return event, false + } + masked := redact.LoginCommand(message) + if masked == message { + return event, false + } + // Values decoded from valid JSON encode again without error. + fields[2], _ = json.Marshal(masked) + encoded, _ := json.Marshal(fields) + return encoded, true +} + +// unexpectedEnd reports the end of the input inside a recording as the error +// it is there. +func unexpectedEnd(err error) error { + if err == io.EOF { + return io.ErrUnexpectedEOF + } + return err +} + +// syntaxError describes byte c where JSON wanted something else. +func syntaxError(c byte, want string) error { + return fmt.Errorf("invalid character %q where JSON wants %s", c, want) +} + +func isDigit(c byte) bool { return c >= '0' && c <= '9' } + +func isHex(c byte) bool { + return isDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') +} diff --git a/internal/ingestion/redact_json_test.go b/internal/ingestion/redact_json_test.go new file mode 100644 index 00000000..c0a5a968 --- /dev/null +++ b/internal/ingestion/redact_json_test.go @@ -0,0 +1,344 @@ +package ingestion + +import ( + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A clean recording passes through byte for byte, whatever JSON it is written +// in. +func TestMaskJSONChatCopiesCleanRecordingsAsTheyAre(t *testing.T) { + for name, input := range map[string]string{ + "empty object": `{}`, + "whitespace everywhere": " \t\r\n{ \"a\" : [ 1 , { } , [ ] , \"x\" ] ,\n\"events\" : [ ] , \"b\" :\tnull }", + "every kind of value": `{"n":[0,-0,12,-3.25,1e5,1E-5,2.5e+10,-0.0e0],"lit":[true,false,null],` + + `"s":["","\"\\\/\b\f\n\r\t","\u00e9\u20AC\uD83D\uDE00","é€😀"],"o":{"a":{"b":{"c":[{}]}}}}`, + "events that are not an array": `{"events":{"not":"an array"}}`, + "events of every other kind": `{"events":[1,"chat",{"chat":"#login x"},[],[1],[1,"chat"],[1,"chat",7],[1,"killed","#login x"],[1,"chat","#login"],[1,"chat","moving up"]]}`, + "chat keyed deeper than events": `{"entities":[{"events":[[1,"chat","#login nested"]]}]}`, + "a chat event spelled with escapes": `{"events":[[1,"\u0063hat","no command \u0021"]]}`, + } { + t.Run(name, func(t *testing.T) { + require.True(t, json.Valid([]byte(input)), "the fixture is JSON") + var out bytes.Buffer + changed, err := maskJSONChat(strings.NewReader(input), &out) + require.NoError(t, err) + assert.False(t, changed) + assert.Equal(t, input, out.String()) + + changed, err = maskJSONChat(strings.NewReader(input), io.Discard) + require.NoError(t, err) + assert.False(t, changed) + }) + } +} + +// Only a chat event holding a password is written again; every other byte is +// copied as read. +func TestMaskJSONChatMasksOnlyTheChatThatNeedsIt(t *testing.T) { + input := `{"worldName":"altis", "events": [ [1,"connected","Nosey"], ` + + `[ 2 , "chat" , "#login synthetic-password" , "Nosey" , "Global" ],` + + `[3,"\u0063hat","\u0023LOGIN\u00a0synthetic-password"],[4,"chat","moving up"]],` + + `"\u0065vents":[[5,"chat"," #login synthetic-password"]],"entities":[{"id":1}]}` + want := `{"worldName":"altis", "events": [ [1,"connected","Nosey"], ` + + `[2,"chat","#login ********","Nosey","Global"],` + + `[3,"\u0063hat","#LOGIN ********"],[4,"chat","moving up"]],` + + `"\u0065vents":[[5,"chat","#login ********"]],"entities":[{"id":1}]}` + + var out bytes.Buffer + changed, err := maskJSONChat(strings.NewReader(input), &out) + require.NoError(t, err) + assert.True(t, changed) + assert.Equal(t, want, out.String()) + + changed, err = maskJSONChat(strings.NewReader(input), io.Discard) + require.NoError(t, err) + assert.True(t, changed, "checking alone finds it too") + + t.Run("an unchanged event longer than a write", func(t *testing.T) { + input := `{"events":[[1,"chat","` + strings.Repeat("x", 2*jsonChunk) + `"]]}` + var out bytes.Buffer + changed, err := maskJSONChat(strings.NewReader(input), &out) + require.NoError(t, err) + assert.False(t, changed) + assert.Equal(t, input, out.String()) + }) + + t.Run("an event longer than a write", func(t *testing.T) { + long := strings.Repeat("x", 2*jsonChunk) + input := `{"events":[[1,"chat","#login ` + long + `"]]}` + var out bytes.Buffer + changed, err := maskJSONChat(strings.NewReader(input), &out) + require.NoError(t, err) + assert.True(t, changed) + assert.Equal(t, `{"events":[[1,"chat","#login ********"]]}`, out.String()) + }) +} + +// Whatever encoding/json refuses is refused, so a file that is not a JSON +// recording is never passed as clean. +func TestMaskJSONChatRefusesWhatIsNotJSON(t *testing.T) { + for _, input := range []string{`[1]`, `"x"`, `1`, `null`} { + require.True(t, json.Valid([]byte(input))) + _, err := maskJSONChat(strings.NewReader(input), io.Discard) + assert.Error(t, err, "%q is JSON but no recording", input) + } + + for _, input := range []string{ + ``, ` `, "\xef\xbb\xbf{}", `{`, `{"a"`, `{"a":`, `{"a" 1}`, `{1:2}`, `{"a":1,}`, + `{"a":1 "b":2}`, `{"a":1]`, `{"a":[1,]}`, `{"a":[1 2]}`, `{"a":[`, `{"a":{"b" 1}}`, `{"a":{"b":1,}}`, + `{"a":{"b":1 "c":2}}`, `{"a":{1:2}}`, `{"a":@}`, `{"a":tru}`, `{"a":nul}`, `{"a":fals}`, `{"a":t`, + `{"a":-}`, `{"a":-a}`, `{"a":-`, `{"a":01}`, `{"a":1.}`, `{"a":1.e3}`, `{"a":1e}`, `{"a":1e+}`, + `{"a":1E-x}`, `{"a":.5}`, `{"a":+1}`, `{"a":0`, `{"a":1`, `{"a":1.5`, `{"a":1e5`, `{"a":1e`, + "{\"a\":\"\x01\"}", `{"a":"\q"}`, `{"a":"\u12G4"}`, `{"a":"\u12"}`, `{"a":"\`, `{"a":"\u`, `{"a":"abc`, + `{"\q":1}`, `{"events"`, `{"events":`, `{"events":[`, `{"events":[[`, `{"events":[[1,"chat"]`, + `{"events":[[1] [2]]}`, `{"events":[1,]}`, `{"events":[[1,]]}`, `{"events" 1}`, `{"events":[],}`, + `{"events":[] "a":1}`, `{"events":@}`, + // The input ends right after a value, a comma, a decimal point or an + // exponent's sign. + `{"a":"x"`, `{"a":true`, `{"a":1,`, `{"a":["x"`, `{"a":1.`, `{"a":1e+`, `{"events":[1,`, + } { + require.False(t, json.Valid([]byte(input)), "encoding/json refuses %q", input) + _, err := maskJSONChat(strings.NewReader(input), io.Discard) + assert.Error(t, err, "%q", input) + } + + t.Run("nesting as deep as encoding/json allows", func(t *testing.T) { + for _, open := range []string{"[", `{"a":`} { + closer := map[string]string{"[": "]", `{"a":`: "}"}[open] + deep := func(n int) string { + return `{"a":` + strings.Repeat(open, n) + "1" + strings.Repeat(closer, n) + "}" + } + // The recording is one level, so this many more is the most there may be. + limit := maxJSONDepth - 1 + require.True(t, json.Valid([]byte(deep(limit)))) + _, err := maskJSONChat(strings.NewReader(deep(limit)), io.Discard) + assert.NoError(t, err, open) + + require.False(t, json.Valid([]byte(deep(limit+1)))) + _, err = maskJSONChat(strings.NewReader(deep(limit+1)), io.Discard) + assert.ErrorIs(t, err, errJSONTooDeep, open) + } + }) + + t.Run("the end of the input inside the recording", func(t *testing.T) { + _, err := maskJSONChat(strings.NewReader(`{"a":[1,2`), io.Discard) + assert.ErrorIs(t, err, io.ErrUnexpectedEOF) + }) + + t.Run("a read error", func(t *testing.T) { + broken := io.MultiReader(strings.NewReader(`{"a":`), iotestErrReader{errors.New("bad sector")}) + _, err := maskJSONChat(broken, io.Discard) + assert.ErrorContains(t, err, "bad sector") + }) +} + +type iotestErrReader struct{ err error } + +func (r iotestErrReader) Read([]byte) (int, error) { return 0, r.err } + +// A failed write stops the copy and is the error. +func TestMaskJSONChatWriteFailures(t *testing.T) { + t.Run("at the end", func(t *testing.T) { + _, err := maskJSONChat(strings.NewReader(`{"a":1}`), &failingTemp{}) + assert.ErrorContains(t, err, "disk full") + }) + + t.Run("part way, without reading on", func(t *testing.T) { + big := strings.NewReader(`{"a":"` + strings.Repeat("x", 4*jsonChunk) + `"}`) + _, err := maskJSONChat(big, &failingTemp{}) + assert.ErrorContains(t, err, "disk full") + assert.Positive(t, big.Len(), "the rest is left unread") + }) + + t.Run("writing an event again", func(t *testing.T) { + input := `{"events":[[1,"chat","#login ` + strings.Repeat("x", 2*jsonChunk) + `"]]}` + _, err := maskJSONChat(strings.NewReader(input), &failingTemp{}) + assert.ErrorContains(t, err, "disk full") + }) +} + +// synthRecording streams a v1 recording of count entities, each with its own +// position history, without holding more than one entity: it stands in for a +// recording far larger than any buffer the check may keep. +type synthRecording struct { + head, body, tail string + count int + seg, pos int +} + +func newSynthRecording(count int, chat string) *synthRecording { + var positions strings.Builder + for frame := range 40 { + if frame > 0 { + positions.WriteByte(',') + } + positions.WriteString(`[[12345.678,6789.125],271,1,0,"Rifleman \"Alpha\" 1-1",1]`) + } + entity := `{"id":7,"name":"Rifleman \"Alpha\"","side":"WEST","group":"Alpha 1-1","isPlayer":1,` + + `"type":"unit","startFrameNum":0,"positions":[` + positions.String() + `],"framesFired":[[12,[1.5,2.5]]]}` + return &synthRecording{ + head: `{"worldName":"altis","missionName":"Synthetic","endFrame":5000,"captureDelay":1,"entities":[` + entity, + body: "," + entity, + tail: `],"events":[[1,"connected","Nosey"],[2,"chat",` + chat + `,"Nosey","Global"],[3,"killed",7,[8,"rifle"],120]],"Markers":[]}`, + count: count - 1, + } +} + +func (r *synthRecording) segment() (string, bool) { + switch { + case r.seg == 0: + return r.head, true + case r.seg <= r.count: + return r.body, true + case r.seg == r.count+1: + return r.tail, true + } + return "", false +} + +func (r *synthRecording) Read(p []byte) (int, error) { + n := 0 + for n < len(p) { + seg, ok := r.segment() + if !ok { + if n == 0 { + return 0, io.EOF + } + break + } + copied := copy(p[n:], seg[r.pos:]) + n += copied + r.pos += copied + if r.pos == len(seg) { + r.seg, r.pos = r.seg+1, 0 + } + } + return n, nil +} + +// synthEntities makes the synthetic recording about 32 MiB. +const synthEntities = 13000 + +// allocatedBy returns the bytes allocated while run ran. +func allocatedBy(run func()) uint64 { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + run() + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc +} + +// boundedAlloc is what checking or rewriting a recording of any size may +// allocate: a few buffers, the gzip state and one event. +const boundedAlloc = 4 << 20 + +// A recording far larger than any buffer passes through the check, and a +// rewrite, without the check holding its position history: memory stays a +// few buffers whatever its length. +func TestMaskJSONChatStreamsLargeRecordings(t *testing.T) { + clean := newSynthRecording(synthEntities, `"moving up"`) + size, err := io.Copy(io.Discard, newSynthRecording(synthEntities, `"moving up"`)) + require.NoError(t, err) + require.Greater(t, size, int64(30<<20), "the fixture is large") + + t.Run("clean", func(t *testing.T) { + var changed bool + var err error + alloc := allocatedBy(func() { changed, err = maskJSONChat(clean, io.Discard) }) + require.NoError(t, err) + assert.False(t, changed) + assert.Less(t, alloc, uint64(boundedAlloc), "allocated %d bytes checking %d", alloc, size) + }) + + t.Run("rewritten", func(t *testing.T) { + want := sha256.New() + _, err := io.Copy(want, newSynthRecording(synthEntities, `"#login ********"`)) + require.NoError(t, err) + + got := sha256.New() + var changed bool + alloc := allocatedBy(func() { + changed, err = maskJSONChat(newSynthRecording(synthEntities, `"#login synthetic-password"`), got) + }) + require.NoError(t, err) + assert.True(t, changed) + assert.Less(t, alloc, uint64(boundedAlloc), "allocated %d bytes rewriting %d", alloc, size) + assert.Equal(t, want.Sum(nil), got.Sum(nil), "everything but the password is copied as it was") + }) +} + +// The same holds for a stored recording, gzipped on disk, as the server +// checks it before serving and rewrites it when it must. +func TestRedactStoredChatStreamsLargeRecordings(t *testing.T) { + write := func(t *testing.T, chat string) string { + path := filepath.Join(t.TempDir(), "large.json.gz") + f, err := os.Create(path) + require.NoError(t, err) + gz, err := gzip.NewWriterLevel(f, gzip.BestSpeed) + require.NoError(t, err) + _, err = io.Copy(gz, newSynthRecording(synthEntities, chat)) + require.NoError(t, err) + require.NoError(t, gz.Close()) + require.NoError(t, f.Close()) + return path + } + + t.Run("clean", func(t *testing.T) { + path := write(t, `"moving up"`) + before, err := os.ReadFile(path) + require.NoError(t, err) + var changed bool + alloc := allocatedBy(func() { changed, err = RedactStoredChat(filepath.Dir(path), "large", ChatJSONGzip) }) + require.NoError(t, err) + assert.False(t, changed) + assert.Less(t, alloc, uint64(boundedAlloc), "allocated %d bytes", alloc) + after, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, before, after) + }) + + t.Run("rewritten", func(t *testing.T) { + path := write(t, `"#login synthetic-password"`) + var changed bool + var err error + alloc := allocatedBy(func() { changed, err = RedactStoredChat(filepath.Dir(path), "large", ChatJSONGzip) }) + require.NoError(t, err) + assert.True(t, changed) + assert.Less(t, alloc, uint64(boundedAlloc), "allocated %d bytes", alloc) + + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + gz, err := gzip.NewReader(f) + require.NoError(t, err) + got := sha256.New() + _, err = io.Copy(got, gz) + require.NoError(t, err) + want := sha256.New() + _, err = io.Copy(want, newSynthRecording(synthEntities, `"#login ********"`)) + require.NoError(t, err) + assert.Equal(t, want.Sum(nil), got.Sum(nil)) + }) +} + +func TestMaskChatEventSkipsWhatCannotBeChat(t *testing.T) { + for _, event := range []string{`[1,"killed",2]`, `[1,"chatter","#login x"]`, `[1,"Chat","#login x"]`} { + got, changed := maskChatEvent([]byte(event)) + assert.False(t, changed, event) + assert.Equal(t, event, string(got)) + } +} diff --git a/internal/ingestion/redact_stored.go b/internal/ingestion/redact_stored.go new file mode 100644 index 00000000..26960a34 --- /dev/null +++ b/internal/ingestion/redact_stored.go @@ -0,0 +1,280 @@ +package ingestion + +import ( + "bufio" + "compress/gzip" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + + "github.com/OCAP2/web/internal/redact" + "github.com/OCAP2/web/internal/storage" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "google.golang.org/protobuf/proto" +) + +// Replaceable in tests, to reach the failures a real disk rarely produces. +var ( + marshalStoredManifest = proto.Marshal + replaceStoredArtifact = storage.ReplaceArtifact + rewriteStoredSidecars = storage.WriteSidecars + createStoredTemp = func(dir, pattern string) (storedTemp, error) { return os.CreateTemp(dir, pattern) } + replaceStoredFile = replaceFile +) + +// ErrUnreadableRecording is returned for a v1 recording that is not a JSON +// object, or not gzipped JSON, so its chat cannot be checked. +var ErrUnreadableRecording = errors.New("not a readable JSON recording") + +// storedTemp is the temporary file a rewritten JSON recording is written to. +type storedTemp interface { + io.Writer + Close() error + Name() string +} + +// A ChatPart is one form of a recording, served under names of its own, that +// can hold chat. Each part is checked on its own and served once it is clean, +// so a damaged copy in one form does not keep the other from playing. +type ChatPart int + +const ( + // ChatManifest is the manifest in the recording's directory, with its + // precompressed sidecars. + ChatManifest ChatPart = iota + // ChatJSONGzip is the v1 JSON named .json.gz, gzipped or plain: + // the copy of a v2 recording, or an upload. + ChatJSONGzip + // ChatJSON is the v1 JSON named .json. + ChatJSON + // NumChatParts is the number of parts. + NumChatParts +) + +// errUnknownManifest is a manifest of no schema this server writes, such as +// one damaged before its version: nothing about its chat is known. +var errUnknownManifest = errors.New("not a manifest of a known schema") + +// RedactStoredChat masks the password of #login chat commands in one part of +// a recording stored before ingestion masked them. It reports whether a file +// changed, and fails unless the part is known to be clean; a part with no file +// is. A file is replaced by a rename, so a request reads the old bytes or the +// new ones. +// +// Chunks hold no chat, and a converted v1 manifest holds none from before +// conversion carried chat, which masks it on the way since. +func RedactStoredChat(dataDir, filename string, part ChatPart) (bool, error) { + var name string + var redactPart func(string) (bool, error) + switch part { + case ChatManifest: + name, redactPart = filepath.Join(filename, "manifest.pb"), redactManifestChat + case ChatJSONGzip: + name, redactPart = filename+".json.gz", redactStoredJSON + case ChatJSON: + name, redactPart = filename+".json", redactStoredJSON + default: + return false, fmt.Errorf("no chat part %d", part) + } + changed, err := redactPart(filepath.Join(dataDir, name)) + if err != nil { + return false, fmt.Errorf("mask chat in %s: %w", filepath.ToSlash(name), err) + } + return changed, nil +} + +// redactManifestChat masks chat passwords in a recording's manifest, and +// makes sure each precompressed sidecar of it decodes to the manifest: a +// sidecar can be asked for by name, so one from before masking, or one a +// replacement left half done, is written again. A sidecar with no manifest to +// check it against fails, and so does a manifest of no known schema. +func redactManifestChat(path string) (bool, error) { + data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + return false, sidecarsWithoutManifest(path) + } + if err != nil { + return false, err + } + switch storage.ManifestVersion(data) { + case uint64(storage.SchemaVersionV1): + // Converted: its chat was masked on the way, if it carried any. + case uint64(storage.SchemaVersionV2): + masked, changed, err := maskManifestChat(data) + if err != nil { + return false, err + } + if changed { + if err := replaceStoredArtifact(path, masked); err != nil { + return false, err + } + return true, nil + } + default: + return false, errUnknownManifest + } + match, err := storage.SidecarsMatch(path, data) + if err != nil || match { + return false, err + } + if err := rewriteStoredSidecars(path, data); err != nil { + return false, err + } + return true, nil +} + +// maskManifestChat masks the chat passwords in an encoded v2 manifest, and +// reports whether any was there. +func maskManifestChat(data []byte) ([]byte, bool, error) { + var manifest pbv2.Manifest + if err := proto.Unmarshal(data, &manifest); err != nil { + return nil, false, err + } + changed := false + for _, event := range manifest.Events { + if chat := event.GetChat(); chat != nil { + if masked := redact.LoginCommand(chat.Message); masked != chat.Message { + chat.Message = masked + changed = true + } + } + } + if !changed { + return data, false, nil + } + masked, err := marshalStoredManifest(&manifest) + if err != nil { + return nil, false, err + } + return masked, true, nil +} + +// sidecarsWithoutManifest fails if a precompressed sidecar of a missing +// manifest is there, as one a partial restore left behind would be: it can be +// asked for by name, and with no manifest there is nothing to check it +// against or write it again from. +func sidecarsWithoutManifest(path string) error { + for _, encoding := range storage.PrecompressEncodings { + sidecar := path + storage.PrecompressSuffix[encoding] + if _, err := os.Lstat(sidecar); !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("%s may hold chat with no manifest to check it against", filepath.Base(sidecar)) + } + } + return nil +} + +// redactStoredJSON masks chat passwords in a v1 JSON recording if there is one +// at path. +func redactStoredJSON(path string) (bool, error) { + if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { + return false, nil + } else if err != nil { + return false, err + } + return RedactJSONFile(path) +} + +// RedactJSONFile masks the passwords of #login chat commands in a v1 JSON +// recording, gzipped or plain, and reports whether it changed. Messages are +// matched as decoded: a JSON writer may spell any letter as a \u escape, so +// the raw text proves nothing. A clean file is only read, and a changed one +// replaced by a rename. A file that is not a JSON object is +// ErrUnreadableRecording: nothing about its chat is known. +func RedactJSONFile(path string) (bool, error) { + needed, err := jsonNeedsMasking(path) + if err != nil || !needed { + return false, err + } + tmpPath, changed, err := writeMaskedJSON(path) + if err != nil || !changed { + return false, err + } + if err := replaceStoredFile(tmpPath, path); err != nil { + os.Remove(tmpPath) + return false, err + } + return true, nil +} + +// jsonNeedsMasking reads a v1 JSON recording through, decoding its chat, and +// reports whether any message holds a #login password. +func jsonNeedsMasking(path string) (bool, error) { + r, _, closeFile, err := openRecordingJSON(path) + if errors.Is(err, fs.ErrNotExist) { + return false, err + } + if err != nil { + return false, fmt.Errorf("%w: %w", ErrUnreadableRecording, err) + } + defer closeFile() + needed, err := maskJSONChat(r, io.Discard) + if err != nil { + return false, fmt.Errorf("%w: %w", ErrUnreadableRecording, err) + } + return needed, nil +} + +// openRecordingJSON opens a v1 recording for reading, gzipped or plain: +// legacy uploads may hold plain JSON under a .json.gz name. +func openRecordingJSON(path string) (io.Reader, bool, func(), error) { + f, err := os.Open(path) + if err != nil { + return nil, false, nil, err + } + buffered := bufio.NewReader(f) + if magic, _ := buffered.Peek(2); len(magic) == 2 && magic[0] == 0x1f && magic[1] == 0x8b { + gz, err := gzip.NewReader(buffered) + if err != nil { + f.Close() + return nil, false, nil, err + } + return gz, true, func() { gz.Close(); f.Close() }, nil + } + return buffered, false, func() { f.Close() }, nil +} + +// writeMaskedJSON writes a recording, with chat passwords masked, to a +// temporary file beside it in the same encoding. The file is removed again +// when nothing changed or anything failed. +func writeMaskedJSON(path string) (tmpPath string, changed bool, err error) { + src, gzipped, closeSrc, err := openRecordingJSON(path) + if err != nil { + return "", false, err + } + defer closeSrc() + tmp, err := createStoredTemp(filepath.Dir(path), "."+filepath.Base(path)+".tmp*") + if err != nil { + return "", false, err + } + tmpPath = tmp.Name() + + var sink io.Writer = tmp + var gz *gzip.Writer + if gzipped { + gz = gzip.NewWriter(tmp) + sink = gz + } + changed, err = maskJSONChat(src, sink) + if err == nil && changed && gz != nil { + err = gz.Close() + } + if closeErr := tmp.Close(); err == nil { + err = closeErr + } + if err != nil || !changed { + os.Remove(tmpPath) + return "", false, err + } + return tmpPath, true, nil +} + +// replaceFile moves a finished temporary file over the recording it replaces. +func replaceFile(tmpPath, path string) error { + if err := os.Chmod(tmpPath, 0o644); err != nil { + return err + } + return os.Rename(tmpPath, path) +} diff --git a/internal/ingestion/redact_stored_test.go b/internal/ingestion/redact_stored_test.go new file mode 100644 index 00000000..728195ba --- /dev/null +++ b/internal/ingestion/redact_stored_test.go @@ -0,0 +1,521 @@ +package ingestion + +import ( + "bytes" + "compress/gzip" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/OCAP2/web/internal/storage" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +const storedPassword = "synthetic-password" + +// storedV1JSON is a v1 copy as ingestion wrote it before masking. +const storedV1JSON = `{"worldName":"altis","missionName":"Stored chat","events":[` + + `[1,"connected","Nosey"],` + + `[2,"chat"," #LOGIN synthetic-password","Nosey","Global"],` + + `[3,"chat","moving up","Nosey","Side"],` + + `[4,"chat"],[5,"chat",7,"Nosey"],[6,"chat","#login"],"not an event",[7,8,9]` + + `],"entities":[{"id":1,"name":"Nosey"}]}` + +// storedV2Manifest is a native manifest saved before masking, big enough to +// carry precompressed sidecars. +func storedV2Manifest() *pbv2.Manifest { + m := &pbv2.Manifest{Version: 2, FrameCount: 10, Events: []*pbv2.Event{ + {FrameNum: 2, Event: &pbv2.Event_Chat{Chat: &pbv2.ChatEvent{Message: "#login " + storedPassword, FromName: "Nosey", Channel: "Global"}}}, + {FrameNum: 3, Event: &pbv2.Event_Chat{Chat: &pbv2.ChatEvent{Message: "moving up", FromName: "Nosey", Channel: "Side"}}}, + {FrameNum: 4, Event: &pbv2.Event_General{General: &pbv2.GeneralEvent{Name: "connected", Message: "Nosey"}}}, + }} + for i := range 200 { + m.Soldiers = append(m.Soldiers, &pbv2.SoldierDef{Id: uint32(i), Name: "Rifleman"}) + } + return m +} + +func writeStoredManifest(t *testing.T, dir string, m *pbv2.Manifest) string { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "rec"), 0o755)) + data, err := proto.Marshal(m) + require.NoError(t, err) + path := filepath.Join(dir, "rec", "manifest.pb") + require.NoError(t, storage.WriteArtifact(path, data)) + return path +} + +func writeGzip(t *testing.T, path, content string) { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + _, err := gz.Write([]byte(content)) + require.NoError(t, err) + require.NoError(t, gz.Close()) + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o644)) +} + +func readGzipFile(t *testing.T, path string) string { + t.Helper() + f, err := os.Open(path) + require.NoError(t, err) + defer f.Close() + gz, err := gzip.NewReader(f) + require.NoError(t, err) + data, err := io.ReadAll(gz) + require.NoError(t, err) + return string(data) +} + +// redactAll checks every part of a recording, as the server does, and joins +// what failed. +func redactAll(dataDir, filename string) (bool, error) { + changed := false + var errs []error + for part := range NumChatParts { + partChanged, err := RedactStoredChat(dataDir, filename, part) + changed = changed || partChanged + errs = append(errs, err) + } + return changed, errors.Join(errs...) +} + +func readManifestFile(t *testing.T, path string) *pbv2.Manifest { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + var m pbv2.Manifest + require.NoError(t, proto.Unmarshal(data, &m)) + return &m +} + +func TestRedactStoredChatMasksV2ManifestAndCopy(t *testing.T) { + dir := t.TempDir() + manifestPath := writeStoredManifest(t, dir, storedV2Manifest()) + require.FileExists(t, manifestPath+".gz", "the fixture has a sidecar to replace") + writeGzip(t, filepath.Join(dir, "rec.json.gz"), storedV1JSON) + + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.True(t, changed) + + m := readManifestFile(t, manifestPath) + assert.Equal(t, "#login ********", m.Events[0].GetChat().Message) + assert.Equal(t, "Nosey", m.Events[0].GetChat().FromName) + assert.Equal(t, "moving up", m.Events[1].GetChat().Message) + assert.Equal(t, "connected", m.Events[2].GetGeneral().Name) + assert.Len(t, m.Soldiers, 200) + assert.NotContains(t, readGzipFile(t, manifestPath+".gz"), storedPassword, "the sidecar is replaced too") + + copyJSON := readGzipFile(t, filepath.Join(dir, "rec.json.gz")) + assert.NotContains(t, copyJSON, storedPassword) + assert.Contains(t, copyJSON, `[2,"chat","#LOGIN ********","Nosey","Global"]`) + assert.Contains(t, copyJSON, `[3,"chat","moving up","Nosey","Side"]`, "other events are copied as they were") + assert.Contains(t, copyJSON, `"entities":[{"id":1,"name":"Nosey"}]`) + assert.True(t, strings.HasPrefix(copyJSON, `{"worldName":"altis","missionName":"Stored chat",`), "keys keep their order") + + changed, err = redactAll(dir, "rec") + require.NoError(t, err) + assert.False(t, changed, "a masked recording has nothing left to change") +} + +func TestRedactStoredChatJSONEncodings(t *testing.T) { + t.Run("plain JSON", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec.json"), []byte(storedV1JSON), 0o644)) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.True(t, changed) + data, err := os.ReadFile(filepath.Join(dir, "rec.json")) + require.NoError(t, err) + assert.NotContains(t, string(data), storedPassword) + assert.Contains(t, string(data), `"#LOGIN ********"`) + }) + + t.Run("plain JSON under a .json.gz name stays plain", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec.json.gz"), []byte(storedV1JSON), 0o644)) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.True(t, changed) + data, err := os.ReadFile(filepath.Join(dir, "rec.json.gz")) + require.NoError(t, err) + assert.True(t, strings.HasPrefix(string(data), "{")) + assert.NotContains(t, string(data), storedPassword) + }) + + t.Run("mentions login but holds no password", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "rec.json.gz") + writeGzip(t, path, `{"missionName":"Login practice","events":[[1,"chat","#login"]]}`) + before, err := os.ReadFile(path) + require.NoError(t, err) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.False(t, changed) + after, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, before, after, "nothing to mask leaves the file alone") + leftovers, err := filepath.Glob(filepath.Join(dir, ".*tmp*")) + require.NoError(t, err) + assert.Empty(t, leftovers) + }) + + t.Run("never mentions login", func(t *testing.T) { + dir := t.TempDir() + writeGzip(t, filepath.Join(dir, "rec.json.gz"), `{"events":[[1,"chat","moving up"]]}`) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.False(t, changed) + }) + + t.Run("a command spelled with JSON escapes is masked", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "rec.json.gz") + writeGzip(t, path, `{"events":[[2,"chat","\u0023\u006C\u006f\u0067\u0069\u006e synthetic-\u0070assword","Nosey","Global"]]}`) + require.NotContains(t, strings.ToLower(readGzipFile(t, path)), "login", "the raw text never spells the command") + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.True(t, changed) + masked := readGzipFile(t, path) + assert.NotContains(t, masked, "synthetic-") + assert.Contains(t, masked, `"#login ********"`) + }) + + t.Run("both names of the JSON are masked", func(t *testing.T) { + dir := t.TempDir() + writeGzip(t, filepath.Join(dir, "rec.json.gz"), storedV1JSON) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec.json"), []byte(storedV1JSON), 0o644)) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.True(t, changed) + assert.NotContains(t, readGzipFile(t, filepath.Join(dir, "rec.json.gz")), storedPassword) + data, err := os.ReadFile(filepath.Join(dir, "rec.json")) + require.NoError(t, err) + assert.NotContains(t, string(data), storedPassword) + }) + + t.Run("a file that is not a JSON recording is not passed as clean", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec.json"), []byte("not json"), 0o644)) + _, err := redactAll(dir, "rec") + assert.ErrorIs(t, err, ErrUnreadableRecording) + assert.ErrorContains(t, err, "rec.json") + }) + + t.Run("no files", func(t *testing.T) { + changed, err := redactAll(t.TempDir(), "missing") + require.NoError(t, err) + assert.False(t, changed) + }) +} + +func TestRedactStoredChatManifestCases(t *testing.T) { + t.Run("converted v1 manifest is left alone", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "rec"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec", "manifest.pb"), []byte{0x08, 0x01}, 0o644)) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.False(t, changed) + }) + + t.Run("manifest without a password", func(t *testing.T) { + dir := t.TempDir() + m := storedV2Manifest() + m.Events = m.Events[1:] + writeStoredManifest(t, dir, m) + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.False(t, changed) + }) + + t.Run("unreadable manifest", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "rec", "manifest.pb"), 0o755)) + _, err := redactAll(dir, "rec") + assert.ErrorContains(t, err, "rec/manifest.pb") + }) + + t.Run("corrupt manifest", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "rec"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec", "manifest.pb"), []byte{0x08, 0x02, 0xff}, 0o644)) + _, err := redactAll(dir, "rec") + assert.ErrorContains(t, err, "rec/manifest.pb") + }) + + t.Run("a manifest of no known schema is not passed as clean", func(t *testing.T) { + for name, data := range map[string][]byte{ + "no version": {0x12, 0x05, '#', 'l', 'o', 'g', 'i'}, + "a later version": {0x08, 0x03}, + "damaged up front": {0xff, 0xff, 0xff}, + } { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "rec"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec", "manifest.pb"), data, 0o644)) + changed, err := RedactStoredChat(dir, "rec", ChatManifest) + assert.ErrorIs(t, err, errUnknownManifest, name) + assert.False(t, changed, name) + } + }) + + t.Run("marshal failure", func(t *testing.T) { + dir := t.TempDir() + writeStoredManifest(t, dir, storedV2Manifest()) + orig := marshalStoredManifest + t.Cleanup(func() { marshalStoredManifest = orig }) + marshalStoredManifest = func(proto.Message) ([]byte, error) { return nil, errors.New("marshal failed") } + _, err := redactAll(dir, "rec") + assert.ErrorContains(t, err, "marshal failed") + }) + + t.Run("replace failure", func(t *testing.T) { + dir := t.TempDir() + writeStoredManifest(t, dir, storedV2Manifest()) + orig := replaceStoredArtifact + t.Cleanup(func() { replaceStoredArtifact = orig }) + replaceStoredArtifact = func(string, []byte) error { return errors.New("replace failed") } + _, err := redactAll(dir, "rec") + assert.ErrorContains(t, err, "replace failed") + }) + + t.Run("each part is checked on its own", func(t *testing.T) { + dir := t.TempDir() + manifestPath := writeStoredManifest(t, dir, storedV2Manifest()) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec.json.gz"), []byte("\x1f\x8bnot gzip"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rec.json"), []byte(storedV1JSON), 0o644)) + + changed, err := RedactStoredChat(dir, "rec", ChatJSONGzip) + assert.ErrorContains(t, err, "rec.json.gz") + assert.ErrorIs(t, err, ErrUnreadableRecording) + assert.False(t, changed) + + changed, err = RedactStoredChat(dir, "rec", ChatManifest) + require.NoError(t, err, "a damaged copy does not fail the manifest") + assert.True(t, changed) + assert.Equal(t, "#login ********", readManifestFile(t, manifestPath).Events[0].GetChat().Message) + + changed, err = RedactStoredChat(dir, "rec", ChatJSON) + require.NoError(t, err, "nor the other name of the JSON") + assert.True(t, changed) + data, err := os.ReadFile(filepath.Join(dir, "rec.json")) + require.NoError(t, err) + assert.NotContains(t, string(data), storedPassword) + }) + + t.Run("no such part", func(t *testing.T) { + _, err := RedactStoredChat(t.TempDir(), "rec", NumChatParts) + assert.ErrorContains(t, err, "no chat part") + }) +} + +// A sidecar asked for by name is served as it is, so one the manifest does not +// vouch for is never passed as clean. +func TestRedactStoredChatChecksSidecarsWithoutAManifest(t *testing.T) { + leakySidecar := func(t *testing.T) []byte { + t.Helper() + data, err := proto.Marshal(storedV2Manifest()) + require.NoError(t, err) + return data + } + + for _, encoding := range storage.PrecompressEncodings { + t.Run(encoding+" sidecar left without its manifest", func(t *testing.T) { + dir := t.TempDir() + path := writeStoredManifest(t, dir, storedV2Manifest()) + require.FileExists(t, path+storage.PrecompressSuffix[encoding]) + for _, other := range storage.PrecompressEncodings { + if other != encoding { + require.NoError(t, os.Remove(path+storage.PrecompressSuffix[other])) + } + } + require.NoError(t, os.Remove(path)) + + changed, err := RedactStoredChat(dir, "rec", ChatManifest) + assert.ErrorContains(t, err, "manifest.pb"+storage.PrecompressSuffix[encoding]+" may hold chat with no manifest") + assert.False(t, changed) + assert.FileExists(t, path+storage.PrecompressSuffix[encoding], "nothing is deleted on a guess") + }) + } + + t.Run("the sidecars of a converted manifest are checked too", func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "rec", "manifest.pb") + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte{0x08, 0x01}, 0o644)) + writeGzip(t, path+".gz", string(leakySidecar(t))) + + changed, err := RedactStoredChat(dir, "rec", ChatManifest) + require.NoError(t, err) + assert.True(t, changed) + assert.NoFileExists(t, path+".gz", "a manifest this small carries none") + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, []byte{0x08, 0x01}, data, "the converted manifest itself is left alone") + }) +} + +// A replacement that stopped after the manifest was masked, or any other +// sidecar out of step with it, is caught on the next check: the raw manifest +// alone no longer certifies a sidecar that can be requested by name. +func TestRedactStoredChatRewritesStaleSidecars(t *testing.T) { + leakySidecar := func(t *testing.T) (string, []byte) { + t.Helper() + dir := t.TempDir() + path := writeStoredManifest(t, dir, storedV2Manifest()) + leaky, err := os.ReadFile(path + ".zst") + require.NoError(t, err) + masked := storedV2Manifest() + masked.Events[0].GetChat().Message = "#login ********" + data, err := proto.Marshal(masked) + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, data, 0o644)) + require.NoError(t, os.WriteFile(path+".zst", leaky, 0o644)) + return dir, data + } + + t.Run("a sidecar of the unmasked manifest is written again", func(t *testing.T) { + dir, data := leakySidecar(t) + path := filepath.Join(dir, "rec", "manifest.pb") + changed, err := redactAll(dir, "rec") + require.NoError(t, err) + assert.True(t, changed) + match, err := storage.SidecarsMatch(path, data) + require.NoError(t, err) + assert.True(t, match) + + changed, err = redactAll(dir, "rec") + require.NoError(t, err) + assert.False(t, changed, "matching sidecars are left alone") + }) + + t.Run("a failed rewrite is reported", func(t *testing.T) { + dir, _ := leakySidecar(t) + orig := rewriteStoredSidecars + t.Cleanup(func() { rewriteStoredSidecars = orig }) + rewriteStoredSidecars = func(string, []byte) error { return errors.New("sidecar write failed") } + _, err := redactAll(dir, "rec") + assert.ErrorContains(t, err, "sidecar write failed") + }) + + t.Run("an unreadable sidecar is reported", func(t *testing.T) { + dir := t.TempDir() + m := storedV2Manifest() + m.Events = m.Events[1:] + path := writeStoredManifest(t, dir, m) + require.NoError(t, os.Remove(path+".zst")) + require.NoError(t, os.MkdirAll(path+".zst", 0o755)) + _, err := redactAll(dir, "rec") + assert.ErrorContains(t, err, "rec/manifest.pb") + }) +} + +// failingTemp stands in for the temporary file: writes succeed until limit +// bytes have been written, and Close returns closeErr. +type failingTemp struct { + limit int + written int + closeErr error +} + +func (f *failingTemp) Write(p []byte) (int, error) { + if f.written+len(p) > f.limit { + return 0, errors.New("disk full") + } + f.written += len(p) + return len(p), nil +} +func (f *failingTemp) Close() error { return f.closeErr } +func (f *failingTemp) Name() string { return "synthetic-temp" } + +func TestRedactStoredChatJSONFailures(t *testing.T) { + withTemp := func(t *testing.T, temp storedTemp, err error) { + orig := createStoredTemp + t.Cleanup(func() { createStoredTemp = orig }) + createStoredTemp = func(string, string) (storedTemp, error) { return temp, err } + } + gzipped := func(t *testing.T) string { + path := filepath.Join(t.TempDir(), "rec.json.gz") + writeGzip(t, path, storedV1JSON) + return path + } + plain := func(t *testing.T) string { + path := filepath.Join(t.TempDir(), "rec.json") + require.NoError(t, os.WriteFile(path, []byte(storedV1JSON), 0o644)) + return path + } + + t.Run("stat", func(t *testing.T) { + _, err := redactStoredJSON("bad\x00path") + assert.Error(t, err) + }) + t.Run("open", func(t *testing.T) { + _, err := RedactJSONFile(filepath.Join(t.TempDir(), "missing.json")) + assert.ErrorIs(t, err, os.ErrNotExist) + assert.NotErrorIs(t, err, ErrUnreadableRecording, "a missing file is not a bad recording") + _, _, err = writeMaskedJSON(filepath.Join(t.TempDir(), "missing.json")) + assert.Error(t, err) + }) + t.Run("read", func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "rec.json") + require.NoError(t, os.MkdirAll(dir, 0o755)) + _, err := RedactJSONFile(dir) + assert.Error(t, err) + }) + t.Run("temporary file", func(t *testing.T) { + withTemp(t, nil, errors.New("no temp")) + _, err := RedactJSONFile(gzipped(t)) + assert.ErrorContains(t, err, "no temp") + }) + t.Run("malformed JSON", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "rec.json") + require.NoError(t, os.WriteFile(path, []byte(`{"login":`), 0o644)) + _, err := RedactJSONFile(path) + assert.ErrorIs(t, err, ErrUnreadableRecording) + }) + t.Run("flush", func(t *testing.T) { + withTemp(t, &failingTemp{}, nil) + _, err := RedactJSONFile(plain(t)) + assert.ErrorContains(t, err, "disk full") + }) + t.Run("gzip close", func(t *testing.T) { + withTemp(t, &failingTemp{limit: 10}, nil) + _, err := RedactJSONFile(gzipped(t)) + assert.ErrorContains(t, err, "disk full") + }) + t.Run("close", func(t *testing.T) { + withTemp(t, &failingTemp{limit: 1 << 20, closeErr: errors.New("close failed")}, nil) + _, err := RedactJSONFile(plain(t)) + assert.ErrorContains(t, err, "close failed") + }) + t.Run("replace", func(t *testing.T) { + path := plain(t) + orig := replaceStoredFile + t.Cleanup(func() { replaceStoredFile = orig }) + replaceStoredFile = func(string, string) error { return errors.New("rename failed") } + _, err := RedactJSONFile(path) + assert.ErrorContains(t, err, "rename failed") + leftovers, err := filepath.Glob(filepath.Join(filepath.Dir(path), ".*tmp*")) + require.NoError(t, err) + assert.Empty(t, leftovers, "the temporary file is removed") + data, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, storedV1JSON, string(data)) + }) +} + +func TestReplaceFile(t *testing.T) { + dir := t.TempDir() + assert.Error(t, replaceFile(filepath.Join(dir, "missing"), filepath.Join(dir, "target")), "chmod of a missing file") + + tmp := filepath.Join(dir, "tmp") + require.NoError(t, os.WriteFile(tmp, []byte("x"), 0o600)) + assert.Error(t, replaceFile(tmp, filepath.Join(dir, "no-such-dir", "target")), "rename into a missing directory") +} diff --git a/internal/ingestion/session.go b/internal/ingestion/session.go index 49acb796..7bc0911a 100644 --- a/internal/ingestion/session.go +++ b/internal/ingestion/session.go @@ -18,6 +18,7 @@ import ( "time" "github.com/OCAP2/extension/v5/pkg/core" + "github.com/OCAP2/web/internal/redact" ) // soldierRecord tracks a soldier and their accumulated states/events. @@ -461,8 +462,10 @@ func (s *Session) HandleGeneralEvent(evt core.GeneralEvent) { s.trackFrame(evt.CaptureFrame) } -// HandleChatEvent stores a chat event. +// HandleChatEvent stores a chat event. The password in a #login command is +// masked first, so it never reaches a recording. func (s *Session) HandleChatEvent(evt core.ChatEvent) { + evt.Message = redact.LoginCommand(evt.Message) s.events = append(s.events, eventRecord{ eventType: "chat", frame: evt.CaptureFrame, @@ -972,7 +975,7 @@ func (s *Session) eventsToV1() []any { } } else if e.chat != nil { events = append(events, []any{ - e.chat.CaptureFrame, "chat", e.chat.Message, + e.chat.CaptureFrame, "chat", e.chat.Message, e.chat.FromName, e.chat.Channel, }) } } diff --git a/internal/redact/redact.go b/internal/redact/redact.go new file mode 100644 index 00000000..559eac4f --- /dev/null +++ b/internal/redact/redact.go @@ -0,0 +1,40 @@ +// Package redact masks secrets that players type into chat before a recording +// keeps them. +package redact + +import ( + "strings" + "unicode" +) + +// loginCommand starts the chat command that logs a player in as server admin. +const loginCommand = "#login" + +// LoginMask stands in for everything typed after #login. It is fixed, so it +// does not reveal the password's length; the OCAP addon and the UI mask the +// same way. +const LoginMask = "********" + +// IsSpace reports whether r is whitespace around a #login command: Unicode +// White_Space, as unicode.IsSpace has it, and U+FEFF, which JavaScript's trim +// removes too. The addon and the UI skip exactly this set, so a non-breaking +// space or a byte-order mark cannot hide the command from one of them. +func IsSpace(r rune) bool { + return unicode.IsSpace(r) || r == '\ufeff' +} + +// LoginCommand masks the server admin password in an Arma #login chat command. +// The command, matched in any case and ignoring surrounding whitespace, is +// kept, so playback still shows the login, and everything typed after it +// becomes LoginMask. Any other message is returned unchanged. +func LoginCommand(message string) string { + m := strings.TrimFunc(message, IsSpace) + if len(m) < len(loginCommand) || !strings.EqualFold(m[:len(loginCommand)], loginCommand) { + return message + } + command := m[:len(loginCommand)] + if strings.TrimFunc(m[len(loginCommand):], IsSpace) == "" { + return command + } + return command + " " + LoginMask +} diff --git a/internal/redact/redact_test.go b/internal/redact/redact_test.go new file mode 100644 index 00000000..06451912 --- /dev/null +++ b/internal/redact/redact_test.go @@ -0,0 +1,53 @@ +package redact + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestLoginCommand(t *testing.T) { + for _, tc := range []struct { + message string + want string + }{ + {"#login synthetic-password", "#login ********"}, + {" #LOGIN synthetic-password ", "#LOGIN ********"}, + {"#Login\tsynthetic password with spaces", "#Login ********"}, + {"#loginsynthetic", "#login ********"}, + {"\u00a0#login synthetic-password", "#login ********"}, + {"\ufeff\u3000\u0085\u2028#LOGIN synthetic-password", "#LOGIN ********"}, + {"#login\u00a0synthetic-password", "#login ********"}, + {"#login", "#login"}, + {" #login ", "#login"}, + {"#login\u00a0\u3000", "#login"}, + {"#login ********", "#login ********"}, + {"#logout", "#logout"}, + {"#log", "#log"}, + {"say #login later", "say #login later"}, + {"\u00a0say #login later", "\u00a0say #login later"}, + {"\u200b#login not whitespace", "\u200b#login not whitespace"}, + {"", ""}, + {" moving up ", " moving up "}, + } { + t.Run(tc.message, func(t *testing.T) { + assert.Equal(t, tc.want, LoginCommand(tc.message)) + }) + } +} + +// The addon lists these code points, and the UI's pattern matches the same. +func TestIsSpaceMatchesTheAddonSet(t *testing.T) { + addon := []rune{ + 9, 10, 11, 12, 13, 32, 133, 160, 5760, + 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, + 8232, 8233, 8239, 8287, 12288, 65279, + } + inAddon := map[rune]bool{} + for _, r := range addon { + inAddon[r] = true + } + for r := rune(0); r <= 0xFFFF; r++ { + assert.Equal(t, inAddon[r], IsSpace(r), "U+%04X", r) + } +} diff --git a/internal/server/chat_redaction.go b/internal/server/chat_redaction.go new file mode 100644 index 00000000..7d5e3537 --- /dev/null +++ b/internal/server/chat_redaction.go @@ -0,0 +1,240 @@ +package server + +import ( + "context" + "database/sql" + "errors" + "hash/fnv" + "log/slog" + "path" + "strings" + "sync" + + "github.com/OCAP2/web/internal/ingestion" + "github.com/OCAP2/web/internal/storage" +) + +// CurrentChatRedactionRevision is stored on a recording once its files are +// known to hold no #login password. Bump it to check every recording again. +const CurrentChatRedactionRevision = 1 + +// ChatRedactor masks #login passwords in recordings stored before ingestion +// masked them. Ensure runs before a file that can hold chat is served, so no +// request ever receives one, and Backfill sweeps the rest once in the +// background. A recording is marked when every part of it is done, and not +// read again. +type ChatRedactor struct { + repo *RepoOperation + dataDir string + redact func(dataDir, filename string, part ingestion.ChatPart) (bool, error) + + locks [64]sync.Mutex +} + +// NewChatRedactor returns a redactor for the recordings in dataDir. +func NewChatRedactor(repo *RepoOperation, dataDir string) *ChatRedactor { + return &ChatRedactor{repo: repo, dataDir: dataDir, redact: ingestion.RedactStoredChat} +} + +// WithChatRedactor sets the redactor GetData runs before serving a recording. +// Without it, the handler makes its own. +func WithChatRedactor(redactor *ChatRedactor) HandlerOption { + return func(h *Handler) { + h.chatRedactor = redactor + } +} + +// lock returns the lock of one recording, so concurrent requests mask its +// files once and none is served while that happens. Recordings share a fixed +// set of locks, so the names requests ask for cannot grow it. +func (c *ChatRedactor) lock(filename string) *sync.Mutex { + hash := fnv.New32a() + hash.Write([]byte(filename)) + return &c.locks[hash.Sum32()%uint32(len(c.locks))] +} + +// Ensure masks the #login passwords in a recording's files unless it is +// marked as done, and returns nil when the given part of it is clean and can +// be served. Every part is checked, and the recording marked once all are +// clean; a part that cannot be checked keeps only itself from being served. +// A name no recording has is ErrNotFound, and nothing is read or written by +// it: on a disk that ignores case it may be another spelling of a stored +// recording, which a rewrite by that name would rename. +func (c *ChatRedactor) Ensure(ctx context.Context, filename string, part ingestion.ChatPart) error { + failed, err := c.check(ctx, filename) + if err != nil { + return err + } + return failed[part] +} + +// check masks the passwords in every part of a recording not marked as done, +// and marks it once all are clean. It returns the error of each part that is +// not. +func (c *ChatRedactor) check(ctx context.Context, filename string) ([ingestion.NumChatParts]error, error) { + var failed [ingestion.NumChatParts]error + l := c.lock(filename) + l.Lock() + defer l.Unlock() + + revision, found, err := c.repo.ChatRedactionRevision(ctx, filename) + if err != nil { + return failed, err + } + if !found { + return failed, ErrNotFound + } + if revision >= CurrentChatRedactionRevision { + return failed, nil + } + clean := true + for part := range ingestion.NumChatParts { + changed, err := c.redact(c.dataDir, filename, part) + if changed { + slog.Info("masked #login passwords in a stored recording", "filename", filename) + } + failed[part] = err + clean = clean && err == nil + } + if !clean { + return failed, nil + } + return failed, c.repo.MarkChatRedacted(ctx, filename, CurrentChatRedactionRevision) +} + +// Backfill checks every recording not yet marked, oldest first. A failure is +// logged and retried at the next start, or when the recording is requested. +func (c *ChatRedactor) Backfill(ctx context.Context) { + ops, err := c.repo.SelectChatRedactionBackfill(ctx) + if err != nil { + slog.Error("failed to select recordings to check for #login passwords", "error", err) + return + } + for _, op := range ops { + if ctx.Err() != nil { + return + } + failed, err := c.check(ctx, op.Filename) + if err = errors.Join(err, errors.Join(failed[:]...)); err != nil { + slog.Warn("failed to mask #login passwords in a stored recording", "filename", op.Filename, "error", err) + } + } +} + +// A chatFile is a data file that can hold chat. +type chatFile struct { + recording string // the recording it belongs to + part ingestion.ChatPart // the part of the recording it is + checked bool // whether the check of its part reads it + sidecars bool // whether its precompressed sidecars are checked with it +} + +// chatFileAt returns what a data path is when the file can hold chat: a v1 +// JSON at the top level, or a manifest.* file in a recording's directory. +// Chunks hold no chat. Of the manifest files, the check reads the manifest and +// its precompressed sidecars, and no other; and only the manifest's own +// sidecars are checked with it, as the .json.gz beside a .json is another +// part. Names are matched as a disk may open them: in any case, and, at the +// end of a file name, with the dots and spaces Windows drops. +func chatFileAt(urlPath string) (chatFile, bool) { + dir, base := path.Split(strings.TrimPrefix(urlPath, "/")) + base = strings.TrimRight(base, ". ") + if dir == "" { + for _, v1 := range []struct { + ext string + part ingestion.ChatPart + }{{".json.gz", ingestion.ChatJSONGzip}, {".json", ingestion.ChatJSON}} { + if name, found := cutSuffixFold(base, v1.ext); found && name != "" { + return chatFile{recording: name, part: v1.part, checked: true}, true + } + } + return chatFile{}, false + } + dir = strings.TrimSuffix(dir, "/") + if strings.Contains(dir, "/") || len(base) < len("manifest.") || !strings.EqualFold(base[:len("manifest.")], "manifest.") { + return chatFile{}, false + } + file := chatFile{recording: dir, part: ingestion.ChatManifest} + for _, checked := range checkedManifestFiles { + if strings.EqualFold(base, checked) { + file.checked = true + file.sidecars = checked == "manifest.pb" + } + } + return file, true +} + +// checkedManifestFiles are the files of a recording's directory the check of +// its manifest reads. +var checkedManifestFiles = func() []string { + names := []string{"manifest.pb"} + for _, encoding := range storage.PrecompressEncodings { + names = append(names, "manifest.pb"+storage.PrecompressSuffix[encoding]) + } + return names +}() + +// isTemporaryFile reports whether a data file's name is one the server writes +// a file under before renaming it into place. One a crash left behind may be +// a copy of a recording from before chat was masked, which no check reads, so +// none is served. +func isTemporaryFile(name string) bool { + name = strings.ToLower(strings.TrimRight(name, ". ")) + if rest, ok := strings.CutPrefix(name, ".stream-"); ok && isDigits(strings.TrimPrefix(rest, "json-")) { + return true // a recording being ingested + } + if i := strings.LastIndex(name, ".tmp"); i > 0 && name[0] == '.' && isDigits(name[i+len(".tmp"):]) { + return true // a file being replaced, written beside it + } + return strings.HasSuffix(name, ".json.gz.tmp") // an upload, before uploads were staged apart +} + +// isDigits reports whether s is a run of decimal digits, as os.CreateTemp +// puts in a name. +func isDigits(s string) bool { + return s != "" && strings.Trim(s, "0123456789") == "" +} + +// cutSuffixFold is strings.CutSuffix ignoring the case of an ASCII suffix. +func cutSuffixFold(s, suffix string) (string, bool) { + if len(s) < len(suffix) || !strings.EqualFold(s[len(s)-len(suffix):], suffix) { + return s, false + } + return s[:len(s)-len(suffix)], true +} + +// ChatRedactionRevision returns the chat redaction revision of the recording +// stored under filename, and whether there is one. +func (r *RepoOperation) ChatRedactionRevision(ctx context.Context, filename string) (int, bool, error) { + var revision int + err := r.db.QueryRowContext(ctx, + `SELECT chat_redaction_revision FROM operations WHERE filename = ? ORDER BY id DESC LIMIT 1`, filename, + ).Scan(&revision) + if errors.Is(err, sql.ErrNoRows) { + return 0, false, nil + } + if err != nil { + return 0, false, err + } + return revision, true, nil +} + +// MarkChatRedacted records that a recording's files hold no #login password. +func (r *RepoOperation) MarkChatRedacted(ctx context.Context, filename string, revision int) error { + _, err := r.db.ExecContext(ctx, `UPDATE operations SET chat_redaction_revision = ? WHERE filename = ?`, revision, filename) + return err +} + +// SelectChatRedactionBackfill returns the recordings not yet checked for +// #login passwords at the current revision, oldest first. +func (r *RepoOperation) SelectChatRedactionBackfill(ctx context.Context) ([]Operation, error) { + rows, err := r.db.QueryContext(ctx, + `SELECT `+operationColumns+` FROM operations WHERE chat_redaction_revision < ? ORDER BY id ASC`, + CurrentChatRedactionRevision) + if err != nil { + return nil, err + } + defer rows.Close() + + return r.scan(ctx, rows) +} diff --git a/internal/server/chat_redaction_test.go b/internal/server/chat_redaction_test.go new file mode 100644 index 00000000..8926d35b --- /dev/null +++ b/internal/server/chat_redaction_test.go @@ -0,0 +1,934 @@ +package server + +import ( + "bytes" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "os" + "path" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/OCAP2/web/internal/ingestion" + "github.com/OCAP2/web/internal/storage" + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/go-fuego/fuego" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +const leakedPassword = "synthetic-password" + +func TestChatFileAt(t *testing.T) { + manifest := chatFile{recording: "rec", part: ingestion.ChatManifest, checked: true, sidecars: true} + sidecar := chatFile{recording: "rec", part: ingestion.ChatManifest, checked: true} + unchecked := chatFile{recording: "rec", part: ingestion.ChatManifest} + jsonGzip := chatFile{recording: "rec", part: ingestion.ChatJSONGzip, checked: true} + json := chatFile{recording: "rec", part: ingestion.ChatJSON, checked: true} + for urlPath, want := range map[string]chatFile{ + "/rec.json.gz": jsonGzip, + "/rec.json": json, + "/rec/manifest.pb": manifest, + "/rec/manifest.pb.zst": sidecar, + "/rec/manifest.pb.gz": sidecar, + "/rec/manifest.json": unchecked, + "/rec/manifest.pb.bak": unchecked, + "/rec/manifest.pb.gz.zst": unchecked, + "/rec/chunks/0000.pb": {}, + "/rec/players/1.pb": {}, + "/a/b/manifest.pb": {}, + "/.json": {}, + "/rec.pb": {}, + "/rec/snapshot_manifest.x": {}, + "/rec/.manifest.pb.tmp1": {}, + "/rec.JSON.GZ": jsonGzip, + "/Rec.Json": {recording: "Rec", part: ingestion.ChatJSON, checked: true}, + "/rec/MANIFEST.PB.ZST": sidecar, + "/rec/Manifest.pb": manifest, + "/rec/manifes": {}, + "/x": {}, + "/rec.json.gz.": jsonGzip, + "/rec.json . ": json, + "/rec./manifest.pb": {recording: "rec.", part: ingestion.ChatManifest, checked: true, sidecars: true}, + "/rec/manifest.pb. ": manifest, + "/rec/manifest. ": {}, + "/.json.": {}, + } { + file, ok := chatFileAt(urlPath) + assert.Equal(t, want, file, urlPath) + assert.Equal(t, want != chatFile{}, ok, urlPath) + } +} + +// The names the server writes a file under before renaming it into place are +// never served, and no name a stored file has is taken for one. +func TestIsTemporaryFile(t *testing.T) { + dir := t.TempDir() + for _, pattern := range []string{".stream-*", ".stream-json-*", ".rec.json.gz.tmp*", ".manifest.pb.zst.tmp*", ".0001.pb.tmp*"} { + f, err := os.CreateTemp(dir, pattern) + require.NoError(t, err) + require.NoError(t, f.Close()) + assert.True(t, isTemporaryFile(filepath.Base(f.Name())), "%s from %s", filepath.Base(f.Name()), pattern) + } + for name, want := range map[string]bool{ + "rec.json.gz.tmp": true, + "REC.JSON.GZ.TMP": true, + ".STREAM-123": true, + ".stream-123. ": true, + ".rec.json.gz.tmp42.": true, + "rec.json.gz": false, + "rec.json": false, + "manifest.pb": false, + "manifest.pb.zst": false, + "0001.pb": false, + ".stream-": false, + ".stream-json-": false, + ".stream-abc": false, + ".stream-12_20260101": false, + ".tmp123": false, + "rec.tmp123": false, + ".rec.json.gz.tmp": true, + ".manifest.pb.tmp": false, + ".rec.json.gz.tmp1x": false, + ".hidden.json.gz": false, + "rec.tmp": false, + "rec.json.gz.tmp.json": false, + "": false, + "/": false, + } { + assert.Equal(t, want, isTemporaryFile(name), name) + } +} + +func TestChatRedactionRepo(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + first := storePlayerOp(t, repo, "first", "First", "altis", "2026-01-01") + storePlayerOp(t, repo, "second", "Second", "altis", "2026-01-02") + + revision, found, err := repo.ChatRedactionRevision(ctx, "first") + require.NoError(t, err) + assert.True(t, found) + assert.Zero(t, revision, "a stored recording starts unchecked") + + require.NoError(t, repo.MarkChatRedacted(ctx, "first", CurrentChatRedactionRevision)) + revision, _, err = repo.ChatRedactionRevision(ctx, "first") + require.NoError(t, err) + assert.Equal(t, CurrentChatRedactionRevision, revision) + + _, found, err = repo.ChatRedactionRevision(ctx, "orphan") + require.NoError(t, err) + assert.False(t, found) + + ops, err := repo.SelectChatRedactionBackfill(ctx) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "second", ops[0].Filename) + assert.NotEqual(t, first, ops[0].ID) + + require.NoError(t, repo.Close()) + _, _, err = repo.ChatRedactionRevision(ctx, "first") + assert.Error(t, err) + _, err = repo.SelectChatRedactionBackfill(ctx) + assert.Error(t, err) +} + +// recordingRedactor counts the parts of recordings it is asked to mask. +func recordingRedactor(t *testing.T, repo *RepoOperation, changed bool, err error) (*ChatRedactor, *[]string) { + t.Helper() + var calls []string + c := NewChatRedactor(repo, t.TempDir()) + c.redact = func(_ string, filename string, part ingestion.ChatPart) (bool, error) { + calls = append(calls, fmt.Sprintf("%s:%d", filename, part)) + return changed, err + } + return c, &calls +} + +// everyPart lists the calls a check of one recording makes. +func everyPart(filename string) []string { + var calls []string + for part := range ingestion.NumChatParts { + calls = append(calls, fmt.Sprintf("%s:%d", filename, part)) + } + return calls +} + +func TestChatRedactorEnsure(t *testing.T) { + ctx := t.Context() + + t.Run("masks once, then trusts the mark", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "rec", "Rec", "altis", "2026-01-01") + c, calls := recordingRedactor(t, repo, true, nil) + require.NoError(t, c.Ensure(ctx, "rec", ingestion.ChatManifest)) + require.NoError(t, c.Ensure(ctx, "rec", ingestion.ChatJSONGzip)) + assert.Equal(t, everyPart("rec"), *calls, "every part is checked once") + }) + + t.Run("a part that cannot be checked keeps only itself from being served", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "rec", "Rec", "altis", "2026-01-01") + c, calls := recordingRedactor(t, repo, false, nil) + c.redact = func(_ string, filename string, part ingestion.ChatPart) (bool, error) { + *calls = append(*calls, fmt.Sprintf("%s:%d", filename, part)) + if part == ingestion.ChatJSONGzip { + return false, errors.New("truncated copy") + } + return part == ingestion.ChatManifest, nil + } + assert.NoError(t, c.Ensure(ctx, "rec", ingestion.ChatManifest)) + assert.NoError(t, c.Ensure(ctx, "rec", ingestion.ChatJSON)) + assert.ErrorContains(t, c.Ensure(ctx, "rec", ingestion.ChatJSONGzip), "truncated copy") + assert.Len(t, *calls, 3*int(ingestion.NumChatParts), "a recording not marked is checked again") + revision, _, err := repo.ChatRedactionRevision(ctx, "rec") + require.NoError(t, err) + assert.Zero(t, revision, "it is not marked while a part is not clean") + }) + + t.Run("a name no recording has is neither read nor written", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "rec", "Rec", "altis", "2026-01-01") + c, calls := recordingRedactor(t, repo, false, nil) + assert.ErrorIs(t, c.Ensure(ctx, "orphan", ingestion.ChatManifest), ErrNotFound) + assert.ErrorIs(t, c.Ensure(ctx, "REC", ingestion.ChatJSON), ErrNotFound, "another spelling of a recording is none") + assert.Empty(t, *calls) + }) + + t.Run("recordings share a fixed set of locks", func(t *testing.T) { + c, _ := recordingRedactor(t, newPlayersRepo(t), false, nil) + assert.Same(t, c.lock("rec"), c.lock("rec")) + seen := map[*sync.Mutex]bool{} + for i := range 1000 { + seen[c.lock(fmt.Sprintf("name-%d", i))] = true + } + assert.LessOrEqual(t, len(seen), len(c.locks)) + }) + + t.Run("a failed mask is not marked", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "rec", "Rec", "altis", "2026-01-01") + c, _ := recordingRedactor(t, repo, false, errors.New("disk failed")) + assert.ErrorContains(t, c.Ensure(ctx, "rec", ingestion.ChatManifest), "disk failed") + revision, _, err := repo.ChatRedactionRevision(ctx, "rec") + require.NoError(t, err) + assert.Zero(t, revision) + }) + + t.Run("the database cannot be read", func(t *testing.T) { + repo := newPlayersRepo(t) + c, calls := recordingRedactor(t, repo, false, nil) + require.NoError(t, repo.Close()) + assert.Error(t, c.Ensure(ctx, "rec", ingestion.ChatManifest)) + assert.Empty(t, *calls, "nothing is masked or served on a guess") + }) +} + +func TestChatRedactorBackfill(t *testing.T) { + t.Run("checks every unmarked recording and goes on after a failure", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "first", "First", "altis", "2026-01-01") + storePlayerOp(t, repo, "second", "Second", "altis", "2026-01-02") + c, calls := recordingRedactor(t, repo, false, nil) + c.redact = func(_ string, filename string, part ingestion.ChatPart) (bool, error) { + *calls = append(*calls, fmt.Sprintf("%s:%d", filename, part)) + if filename == "first" && part == ingestion.ChatJSON { + return false, errors.New("unreadable") + } + return false, nil + } + c.Backfill(t.Context()) + assert.Equal(t, append(everyPart("first"), everyPart("second")...), *calls) + ops, err := repo.SelectChatRedactionBackfill(t.Context()) + require.NoError(t, err) + require.Len(t, ops, 1, "the failed one is left for the next start") + assert.Equal(t, "first", ops[0].Filename) + }) + + t.Run("cancelled stops before the next recording", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "first", "First", "altis", "2026-01-01") + storePlayerOp(t, repo, "second", "Second", "altis", "2026-01-02") + ctx, cancel := context.WithCancel(t.Context()) + c, calls := recordingRedactor(t, repo, false, nil) + c.redact = func(_ string, filename string, part ingestion.ChatPart) (bool, error) { + *calls = append(*calls, fmt.Sprintf("%s:%d", filename, part)) + cancel() + return false, nil + } + c.Backfill(ctx) + assert.Equal(t, everyPart("first"), *calls) + }) + + t.Run("select failure", func(t *testing.T) { + repo := newPlayersRepo(t) + c, calls := recordingRedactor(t, repo, false, nil) + require.NoError(t, repo.Close()) + c.Backfill(t.Context()) + assert.Empty(t, *calls) + }) +} + +// leakyManifest is a native v2 manifest saved before ingestion masked chat, +// big enough to carry precompressed sidecars. +func leakyManifest() *pbv2.Manifest { + manifest := &pbv2.Manifest{Version: 2, FrameCount: 10, Events: []*pbv2.Event{ + {FrameNum: 2, Event: &pbv2.Event_Chat{Chat: &pbv2.ChatEvent{Message: "#login " + leakedPassword, FromName: "Nosey", Channel: "Global"}}}, + }} + for i := range 200 { + manifest.Soldiers = append(manifest.Soldiers, &pbv2.SoldierDef{Id: uint32(i), Name: "Rifleman"}) + } + return manifest +} + +// leakyJSON is a v1 recording whose chat holds a #login password. +const leakyJSON = `{"worldName":"altis","events":[[2,"chat","#login ` + leakedPassword + `","Nosey","Global"]]}` + +func gzipBytes(t *testing.T, content string) []byte { + t.Helper() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + _, err := gz.Write([]byte(content)) + require.NoError(t, err) + require.NoError(t, gz.Close()) + return buf.Bytes() +} + +// storeLeakyRecording lays out a native v2 recording saved before ingestion +// masked chat: a manifest with precompressed sidecars and its v1 copy, both +// holding a #login password. +func storeLeakyRecording(t *testing.T, dataDir, filename string) { + t.Helper() + data, err := proto.Marshal(leakyManifest()) + require.NoError(t, err) + require.NoError(t, os.MkdirAll(filepath.Join(dataDir, filename), 0o755)) + require.NoError(t, storage.WriteArtifact(filepath.Join(dataDir, filename, "manifest.pb"), data)) + require.NoError(t, os.WriteFile(filepath.Join(dataDir, filename+".json.gz"), gzipBytes(t, leakyJSON), 0o644)) +} + +// redactionServer is the registered mux under a non-root prefix, with the +// chat redactor GetData runs and a viewer's token. +type redactionServer struct { + dataDir string + repo *RepoOperation + redactor *ChatRedactor + srv *fuego.Server + viewer string +} + +const redactionSecret = "synthetic-test-secret" + +func newRedactionServer(t *testing.T) *redactionServer { + t.Helper() + dir := t.TempDir() + dataDir := filepath.Join(dir, "data") + require.NoError(t, os.MkdirAll(dataDir, 0o755)) + repo, err := NewRepoOperation(filepath.Join(dir, "operations.db")) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, repo.Close()) }) + + for _, sub := range []string{"markers", "ammo"} { + require.NoError(t, os.MkdirAll(filepath.Join(dir, sub), 0o755)) + } + repoMarker, err := NewRepoMarker(filepath.Join(dir, "markers")) + require.NoError(t, err) + repoAmmo, err := NewRepoAmmo(filepath.Join(dir, "ammo")) + require.NoError(t, err) + setting := Setting{ + PrefixURL: "/ocap", Secret: redactionSecret, Data: dataDir, + Auth: Auth{Mode: "password", SessionTTL: time.Hour}, + } + redactor := NewChatRedactor(repo, dataDir) + srv := fuego.NewServer(fuego.WithoutStartupMessages(), fuego.WithoutAutoGroupTags(), fuego.WithSecurity(OpenAPISecuritySchemes)) + NewHandler(srv, repo, repoMarker, repoAmmo, setting, WithChatRedactor(redactor)) + viewer, err := NewJWTManager(setting.Secret, setting.Auth.SessionTTL).Create("synthetic-viewer", WithRole("viewer")) + require.NoError(t, err) + return &redactionServer{dataDir: dataDir, repo: repo, redactor: redactor, srv: srv, viewer: viewer} +} + +func (s *redactionServer) get(path, encoding string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("Authorization", "Bearer "+s.viewer) + if encoding != "" { + req.Header.Set("Accept-Encoding", encoding) + } + rec := httptest.NewRecorder() + s.srv.Mux.ServeHTTP(rec, req) + return rec +} + +// upload posts a recording the way the addon does. +func (s *redactionServer) upload(t *testing.T, filename string, content []byte) *httptest.ResponseRecorder { + t.Helper() + return s.serve(s.uploadRequest(t, filename, content)) +} + +// uploadRequest is the request the addon uploads a recording with. +func (s *redactionServer) uploadRequest(t *testing.T, filename string, content []byte) *http.Request { + t.Helper() + body := new(bytes.Buffer) + form := multipart.NewWriter(body) + for field, value := range map[string]string{ + "secret": redactionSecret, "filename": filename + ".json", "worldName": "altis", + "missionName": "Synthetic upload", "missionDuration": "60", + } { + require.NoError(t, form.WriteField(field, value)) + } + part, err := form.CreateFormFile("file", filename+".json") + require.NoError(t, err) + _, err = part.Write(content) + require.NoError(t, err) + require.NoError(t, form.Close()) + req := httptest.NewRequest(http.MethodPost, "/ocap/api/v1/operations/add", body) + req.Header.Set("Content-Type", form.FormDataContentType()) + return req +} + +func (s *redactionServer) serve(req *http.Request) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + s.srv.Mux.ServeHTTP(rec, req) + return rec +} + +// leaks reports whether a response carries the password, however its body is +// compressed. +func leaks(t *testing.T, rec *httptest.ResponseRecorder) bool { + t.Helper() + body := responseBody(t, rec) + switch { + case bytes.HasPrefix(body, []byte{0x1f, 0x8b}): + body = decodeGzip(t, body) + case bytes.HasPrefix(body, []byte{0x28, 0xb5, 0x2f, 0xfd}): + body = decodeZstd(t, body) + } + return bytes.Contains(body, []byte(leakedPassword)) +} + +// body returns a response's payload, decoded from its content coding. +func responseBody(t *testing.T, rec *httptest.ResponseRecorder) []byte { + t.Helper() + switch rec.Header().Get("Content-Encoding") { + case "gzip": + return decodeGzip(t, rec.Body.Bytes()) + case "zstd": + return decodeZstd(t, rec.Body.Bytes()) + } + return rec.Body.Bytes() +} + +func manifestChat(t *testing.T, data []byte) string { + t.Helper() + var m pbv2.Manifest + require.NoError(t, proto.Unmarshal(data, &m)) + return m.Events[0].GetChat().Message +} + +// A recording stored before masking never reaches a client with its password, +// in any of the files and encodings that carry its chat. +func TestStoredPasswordsNeverLeaveTheServer(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "leaky") + require.NoError(t, os.MkdirAll(filepath.Join(s.dataDir, "broken"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "broken", "manifest.pb"), []byte{0x08, 0x02, 0xff}, 0o644)) + storePlayerOp(t, s.repo, "leaky", "Leaky", "altis", "2026-01-01") + + rec := s.get("/ocap/data/leaky.json.gz", "") + require.Equal(t, http.StatusOK, rec.Code) + copyJSON := string(responseBody(t, rec)) + assert.NotContains(t, copyJSON, leakedPassword, "the stored v1 copy is served masked") + assert.Contains(t, copyJSON, `"#login ********"`) + + for _, encoding := range []string{"", "gzip", "zstd"} { + rec = s.get("/ocap/data/leaky/manifest.pb", encoding) + require.Equal(t, http.StatusOK, rec.Code, encoding) + assert.Equal(t, "#login ********", manifestChat(t, responseBody(t, rec)), "manifest with Accept-Encoding %q", encoding) + } + rec = s.get("/ocap/data/leaky/manifest.pb.zst", "") + require.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "#login ********", manifestChat(t, decodeZstd(t, rec.Body.Bytes())), "a sidecar asked for by name") + + revision, _, err := s.repo.ChatRedactionRevision(t.Context(), "leaky") + require.NoError(t, err) + assert.Equal(t, CurrentChatRedactionRevision, revision) + + storePlayerOp(t, s.repo, "broken", "Broken", "altis", "2026-01-01") + assert.Equal(t, http.StatusServiceUnavailable, s.get("/ocap/data/broken/manifest.pb", "").Code, + "a recording that cannot be checked is not served") + + t.Run("files of no recording", func(t *testing.T) { + storeLeakyRecording(t, s.dataDir, "orphan") + before, err := os.ReadFile(filepath.Join(s.dataDir, "orphan.json.gz")) + require.NoError(t, err) + for _, name := range []string{"orphan.json.gz", "orphan/manifest.pb", "orphan/manifest.pb.zst"} { + rec := s.get("/ocap/data/"+name, "") + assert.Equal(t, http.StatusNotFound, rec.Code, name) + assert.False(t, leaks(t, rec), name) + } + after, err := os.ReadFile(filepath.Join(s.dataDir, "orphan.json.gz")) + require.NoError(t, err) + assert.Equal(t, before, after, "a request never writes by a name no recording has") + }) + + t.Run("a command spelled with JSON escapes", func(t *testing.T) { + escaped := `{"events":[[2,"chat","#\u006c\u006f\u0067\u0069\u006e ` + leakedPassword + `","Nosey","Global"]]}` + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "escaped.json.gz"), gzipBytes(t, escaped), 0o644)) + storePlayerOp(t, s.repo, "escaped", "Escaped", "altis", "2026-01-02") + rec := s.get("/ocap/data/escaped.json.gz", "") + require.Equal(t, http.StatusOK, rec.Code) + body := string(responseBody(t, rec)) + assert.NotContains(t, body, leakedPassword) + assert.Contains(t, body, `"#login ********"`) + }) + + t.Run("both names of a v1 JSON", func(t *testing.T) { + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "both.json.gz"), gzipBytes(t, leakyJSON), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "both.json"), []byte(leakyJSON), 0o644)) + storePlayerOp(t, s.repo, "both", "Both", "altis", "2026-01-03") + for _, name := range []string{"both.json.gz", "both.json"} { + rec := s.get("/ocap/data/"+name, "") + require.Equal(t, http.StatusOK, rec.Code, name) + assert.NotContains(t, string(responseBody(t, rec)), leakedPassword, name) + } + }) +} + +// A check that failed after masking the manifest but before its sidecars +// leaves the recording unmarked; the next request finds the stale sidecar and +// writes it again, and no request ever receives it. +func TestStaleSidecarAfterAFailedMaskIsNotServed(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "half") + storePlayerOp(t, s.repo, "half", "Half", "altis", "2026-01-01") + + failed := false + s.redactor.redact = func(dataDir, filename string, part ingestion.ChatPart) (bool, error) { + if failed || part != ingestion.ChatManifest { + return ingestion.RedactStoredChat(dataDir, filename, part) + } + failed = true + masked := leakyManifest() + masked.Events[0].GetChat().Message = "#login ********" + data, err := proto.Marshal(masked) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dataDir, filename, "manifest.pb"), data, 0o644)) + return false, errors.New("disk full before the sidecars") + } + + assert.Equal(t, http.StatusServiceUnavailable, s.get("/ocap/data/half/manifest.pb.zst", "").Code) + leftover, err := os.ReadFile(filepath.Join(s.dataDir, "half", "manifest.pb.zst")) + require.NoError(t, err) + require.Contains(t, string(decodeZstd(t, leftover)), leakedPassword, "the failure left a stale sidecar") + + for _, path := range []string{"/ocap/data/half/manifest.pb.zst", "/ocap/data/half/manifest.pb.gz"} { + rec := s.get(path, "") + require.Equal(t, http.StatusOK, rec.Code, path) + data := rec.Body.Bytes() + if path[len(path)-3:] == "zst" { + data = decodeZstd(t, data) + } else { + data = decodeGzip(t, data) + } + assert.Equal(t, "#login ********", manifestChat(t, data), path) + } +} + +// truncatedLeakyGzip is a v1 copy cut off part way, as an interrupted copy or +// a full disk leaves one: its password can still be read from it, but it +// cannot be read through, so it cannot be checked. +func truncatedLeakyGzip(t *testing.T) []byte { + t.Helper() + full := gzipBytes(t, `{"worldName":"altis","events":[[2,"chat","#login `+leakedPassword+`","Nosey","Global"]`+ + strings.Repeat(`,[3,"chat","moving up","Nosey","Side"]`, 5000)+`]}`) + cut := full[:len(full)/2] + zr, err := gzip.NewReader(bytes.NewReader(cut)) + require.NoError(t, err) + prefix, err := io.ReadAll(zr) + require.Error(t, err, "the copy cannot be read through") + require.Contains(t, string(prefix), leakedPassword, "but its password can be read") + return cut +} + +// damagedLeakyManifest is a native manifest whose last field was cut off part +// way: its password can still be read from it, but it does not decode. +func damagedLeakyManifest(t *testing.T) []byte { + t.Helper() + data, err := proto.Marshal(leakyManifest()) + require.NoError(t, err) + damaged := append(data, 0x7a, 0x64, 0x00, 0x00) // field 15: 100 bytes, of which 2 are there + require.Contains(t, string(damaged), leakedPassword) + require.Error(t, proto.Unmarshal(damaged, &pbv2.Manifest{})) + return damaged +} + +// requireUnmarked checks a recording is still to be checked again. +func requireUnmarked(t *testing.T, s *redactionServer, filename string) { + t.Helper() + revision, found, err := s.repo.ChatRedactionRevision(t.Context(), filename) + require.NoError(t, err) + require.True(t, found) + assert.Zero(t, revision, "a recording with a part that is not clean is not marked") +} + +var everyEncoding = []string{"", "gzip", "zstd", "gzip, zstd"} + +// A part of a recording that cannot be checked is not served, and does not +// keep the others from being served: a damaged legacy copy leaves the native +// recording playable, a damaged native manifest leaves the legacy copy +// playable, and the .json and .json.gz names of a v1 JSON stand apart. +func TestADamagedPartKeepsOnlyItselfFromBeingServed(t *testing.T) { + t.Run("a damaged legacy copy beside a native recording", func(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "native") + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "native.json.gz"), truncatedLeakyGzip(t), 0o644)) + storePlayerOp(t, s.repo, "native", "Native", "altis", "2026-01-01") + + for _, encoding := range everyEncoding { + rec := s.get("/ocap/data/native.json.gz", encoding) + assert.Equal(t, http.StatusServiceUnavailable, rec.Code, encoding) + assert.NotContains(t, rec.Body.String(), leakedPassword, encoding) + + rec = s.get("/ocap/data/native/manifest.pb", encoding) + require.Equal(t, http.StatusOK, rec.Code, encoding) + assert.Equal(t, "#login ********", manifestChat(t, responseBody(t, rec)), encoding) + } + rec := s.get("/ocap/data/native/manifest.pb.zst", "") + require.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "#login ********", manifestChat(t, decodeZstd(t, rec.Body.Bytes())), "a sidecar asked for by name") + requireUnmarked(t, s, "native") + }) + + t.Run("a damaged native manifest beside a legacy copy", func(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "legacy") + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "legacy", "manifest.pb"), damagedLeakyManifest(t), 0o644)) + storePlayerOp(t, s.repo, "legacy", "Legacy", "altis", "2026-01-01") + + for _, encoding := range everyEncoding { + for _, name := range []string{"legacy/manifest.pb", "legacy/manifest.pb.gz", "legacy/manifest.pb.zst"} { + rec := s.get("/ocap/data/"+name, encoding) + assert.Equal(t, http.StatusServiceUnavailable, rec.Code, "%s with Accept-Encoding %q", name, encoding) + assert.NotContains(t, rec.Body.String(), leakedPassword, name) + } + + rec := s.get("/ocap/data/legacy.json.gz", encoding) + require.Equal(t, http.StatusOK, rec.Code, encoding) + body := string(responseBody(t, rec)) + assert.NotContains(t, body, leakedPassword, encoding) + assert.Contains(t, body, `"#login ********"`, encoding) + } + requireUnmarked(t, s, "legacy") + }) + + t.Run("the two names of a v1 JSON", func(t *testing.T) { + s := newRedactionServer(t) + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "both.json"), []byte(leakyJSON), 0o644)) + gzipped := filepath.Join(s.dataDir, "both.json.gz") + require.NoError(t, os.WriteFile(gzipped, truncatedLeakyGzip(t), 0o644)) + // Newer than the .json, even once that is rewritten, as a sidecar of it + // would have to be. + later := time.Now().Add(time.Hour) + require.NoError(t, os.Chtimes(gzipped, later, later)) + storePlayerOp(t, s.repo, "both", "Both", "altis", "2026-01-01") + + for _, encoding := range everyEncoding { + rec := s.get("/ocap/data/both.json.gz", encoding) + assert.Equal(t, http.StatusServiceUnavailable, rec.Code, encoding) + assert.NotContains(t, rec.Body.String(), leakedPassword, encoding) + + rec = s.get("/ocap/data/both.json", encoding) + require.Equal(t, http.StatusOK, rec.Code, encoding) + assert.Empty(t, rec.Header().Get("Content-Encoding"), "the .json.gz is not served in place of the .json") + assert.NotContains(t, rec.Body.String(), leakedPassword, encoding) + assert.Contains(t, rec.Body.String(), `"#login ********"`, encoding) + } + requireUnmarked(t, s, "both") + }) +} + +// A precompressed manifest left without its manifest, as a partial restore +// can leave one, holds chat nothing can check it against: it is served neither +// by name nor as a coding of the manifest, and is left on disk, while the +// recording's legacy copy is still served. +func TestSidecarWithoutItsManifestIsNotServed(t *testing.T) { + for _, encoding := range storage.PrecompressEncodings { + t.Run(encoding, func(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "restored") + manifest := filepath.Join(s.dataDir, "restored", "manifest.pb") + sidecar := manifest + storage.PrecompressSuffix[encoding] + for _, other := range storage.PrecompressEncodings { + if other != encoding { + require.NoError(t, os.Remove(manifest+storage.PrecompressSuffix[other])) + } + } + require.NoError(t, os.Remove(manifest)) + storePlayerOp(t, s.repo, "restored", "Restored", "altis", "2026-01-01") + + for _, accept := range []string{"", encoding} { + for _, name := range []string{"restored/manifest.pb" + storage.PrecompressSuffix[encoding], "restored/manifest.pb"} { + rec := s.get("/ocap/data/"+name, accept) + assert.Equal(t, http.StatusServiceUnavailable, rec.Code, "%s with Accept-Encoding %q", name, accept) + assert.False(t, leaks(t, rec), name) + } + } + rec := s.get("/ocap/data/restored.json.gz", "") + require.Equal(t, http.StatusOK, rec.Code, "the legacy copy is checked on its own") + assert.False(t, leaks(t, rec)) + assert.FileExists(t, sidecar, "nothing is deleted on a guess") + requireUnmarked(t, s, "restored") + }) + } +} + +// Copies of a recording's chat that no check reads are not served: a +// manifest.* file other than the manifest and its sidecars, and a file under +// the temporary name it was written under, which a crash from before chat was +// masked may have left with a password in it. +func TestCopiesNoCheckReadsAreNotServed(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "leaky") + storePlayerOp(t, s.repo, "leaky", "Leaky", "altis", "2026-01-01") + recDir := filepath.Join(s.dataDir, "leaky") + manifestData, err := proto.Marshal(leakyManifest()) + require.NoError(t, err) + zstdManifest, err := os.ReadFile(filepath.Join(recDir, "manifest.pb.zst")) + require.NoError(t, err) + jsonGzip := gzipBytes(t, leakyJSON) + + // Newer than anything the check writes, as a sidecar would have to be. + later := time.Now().Add(time.Hour) + var names []string + plant := func(path string, data []byte) { + require.NoError(t, os.WriteFile(path, data, 0o644)) + require.NoError(t, os.Chtimes(path, later, later)) + rel, err := filepath.Rel(s.dataDir, path) + require.NoError(t, err) + names = append(names, filepath.ToSlash(rel)) + } + // Each under the name its writer gives it. + for _, temp := range []struct { + dir, pattern string + data []byte + }{ + {s.dataDir, ".stream-json-*", jsonGzip}, // ingestion's v1 copy + {recDir, ".stream-*", manifestData}, // ingestion's manifest + {s.dataDir, ".leaky.json.gz.tmp*", jsonGzip}, // a masked JSON + {recDir, ".manifest.pb.zst.tmp*", zstdManifest}, // a sidecar + } { + f, err := os.CreateTemp(temp.dir, temp.pattern) + require.NoError(t, err) + require.NoError(t, f.Close()) + plant(f.Name(), temp.data) + } + plant(filepath.Join(s.dataDir, "leaky.json.gz.tmp"), jsonGzip) // an upload before uploads were staged apart + plant(filepath.Join(recDir, "manifest.json"), []byte(leakyJSON)) + plant(filepath.Join(recDir, "manifest.pb.bak"), manifestData) + plant(filepath.Join(recDir, "manifest.pb.gz.zst"), zstdManifest) + + for _, name := range names { + for _, encoding := range []string{"", "gzip, zstd"} { + rec := s.get("/ocap/data/"+name, encoding) + assert.Equal(t, http.StatusNotFound, rec.Code, name) + assert.False(t, leaks(t, rec), name) + } + } + + rec := s.get("/ocap/data/leaky/manifest.pb.gz", "zstd") + require.Equal(t, http.StatusOK, rec.Code) + assert.Empty(t, rec.Header().Get("Content-Encoding"), "a sidecar asked for by name has none of its own") + assert.False(t, leaks(t, rec)) + for _, name := range []string{"leaky.json.gz", "leaky/manifest.pb", "leaky/manifest.pb.zst"} { + rec := s.get("/ocap/data/"+name, "") + require.Equal(t, http.StatusOK, rec.Code, name) + assert.False(t, leaks(t, rec), name) + } +} + +// An upload is masked before it is published. Replacing a recording already +// marked as checked leaves the old mark in place until the new row is +// written, and for good when that write fails, so the file itself has to be +// clean. +func TestReplacingUploadIsMaskedBeforeItIsPublished(t *testing.T) { + t.Run("the metadata write fails", func(t *testing.T) { + s := newRedactionServer(t) + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "replaced.json.gz"), gzipBytes(t, `{"events":[]}`), 0o644)) + storePlayerOp(t, s.repo, "replaced", "Replaced", "altis", "2026-01-01") + require.NoError(t, s.repo.MarkChatRedacted(t.Context(), "replaced", CurrentChatRedactionRevision)) + _, err := s.repo.db.Exec(`CREATE TRIGGER fail_insert BEFORE INSERT ON operations BEGIN SELECT RAISE(FAIL, 'metadata write failed'); END`) + require.NoError(t, err) + + rec := s.upload(t, "replaced", []byte(leakyJSON)) + require.Equal(t, http.StatusInternalServerError, rec.Code) + revision, _, err := s.repo.ChatRedactionRevision(t.Context(), "replaced") + require.NoError(t, err) + require.Equal(t, CurrentChatRedactionRevision, revision, "the old row is still marked as checked") + + rec = s.get("/ocap/data/replaced.json.gz", "") + require.Equal(t, http.StatusOK, rec.Code) + body := string(responseBody(t, rec)) + assert.NotContains(t, body, leakedPassword) + assert.Contains(t, body, `"#login ********"`, "the published upload is the new one") + }) + + t.Run("the replacement succeeds", func(t *testing.T) { + s := newRedactionServer(t) + rec := s.upload(t, "fresh", gzipBytes(t, leakyJSON)) + require.Equal(t, http.StatusOK, rec.Code) + stored, err := os.ReadFile(filepath.Join(s.dataDir, "fresh.json.gz")) + require.NoError(t, err) + assert.NotContains(t, string(decodeGzip(t, stored)), leakedPassword, "the file on disk was never unmasked") + }) + + t.Run("an upload that is not a JSON recording is refused", func(t *testing.T) { + s := newRedactionServer(t) + require.NoError(t, os.WriteFile(filepath.Join(s.dataDir, "kept.json.gz"), gzipBytes(t, `{"events":[]}`), 0o644)) + rec := s.upload(t, "kept", []byte("#login "+leakedPassword)) + assert.Equal(t, http.StatusBadRequest, rec.Code) + assert.NotContains(t, rec.Body.String(), leakedPassword) + stored, err := os.ReadFile(filepath.Join(s.dataDir, "kept.json.gz")) + require.NoError(t, err) + assert.Equal(t, `{"events":[]}`, string(decodeGzip(t, stored)), "the recording it would replace is kept") + leftovers, err := filepath.Glob(filepath.Join(s.dataDir, "*.tmp*")) + require.NoError(t, err) + assert.Empty(t, leftovers) + staged, err := os.ReadDir(filepath.Join(s.dataDir, uploadStagingDir)) + require.NoError(t, err) + assert.Empty(t, staged, "the refused upload is not left staged") + }) + + t.Run("masking fails", func(t *testing.T) { + s := newRedactionServer(t) + orig := redactUpload + t.Cleanup(func() { redactUpload = orig }) + redactUpload = func(string) (bool, error) { return false, errors.New("disk full") } + assert.Equal(t, http.StatusInternalServerError, s.upload(t, "failed", []byte(leakyJSON)).Code) + assert.NoFileExists(t, filepath.Join(s.dataDir, "failed.json.gz")) + }) + + t.Run("the staging file cannot be created", func(t *testing.T) { + s := newRedactionServer(t) + orig := createUploadFile + t.Cleanup(func() { createUploadFile = orig }) + createUploadFile = func(string) (uploadTempFile, error) { return nil, errors.New("no space for the upload") } + assert.Equal(t, http.StatusInternalServerError, s.upload(t, "uncreated", []byte(leakyJSON)).Code) + staged, err := os.ReadDir(filepath.Join(s.dataDir, uploadStagingDir)) + require.NoError(t, err) + assert.Empty(t, staged, "the upload's staging directory is removed") + }) +} + +// An upload waits in a staging directory of its own until it is masked. While +// it waits, no viewer can fetch it, by its path or by any other name the disk +// resolves to it, and another upload of the same recording waits apart. +func TestStagedUploadIsNeverServed(t *testing.T) { + s := newRedactionServer(t) + staged := make(chan string, 2) + release := make(chan struct{}) + orig := redactUpload + t.Cleanup(func() { redactUpload = orig }) + redactUpload = func(file string) (bool, error) { + staged <- file + <-release + return orig(file) + } + + codes := make(chan int, 2) + for range 2 { + req := s.uploadRequest(t, "pending", []byte(leakyJSON)) + go func() { codes <- s.serve(req).Code }() + } + waiting := []string{<-staged, <-staged} + assert.NotEqual(t, filepath.Dir(waiting[0]), filepath.Dir(waiting[1]), "each upload is staged apart") + + for _, file := range waiting { + data, err := os.ReadFile(file) + require.NoError(t, err) + require.Contains(t, string(decodeGzip(t, data)), leakedPassword, "the staged upload is not masked yet") + + rel, err := filepath.Rel(s.dataDir, file) + require.NoError(t, err) + rel = filepath.ToSlash(rel) + inside := strings.TrimPrefix(rel, uploadStagingDir) + for _, target := range []string{ + rel, + path.Dir(rel), + uploadStagingDir, + path.Dir(rel) + "/RECORDING.JSON.GZ", + strings.ToUpper(uploadStagingDir) + inside, + uploadStagingDir + "." + inside, + uploadStagingDir + "%20" + inside, + uploadStagingDir + "::$INDEX_ALLOCATION" + inside, + strings.ReplaceAll(rel, "/", "%5C"), + uploadStagingDir + "%2F" + strings.TrimPrefix(inside, "/"), + } { + for _, encoding := range []string{"", "gzip"} { + rec := s.get("/ocap/data/"+target, encoding) + assert.Equal(t, http.StatusNotFound, rec.Code, target) + assert.False(t, leaks(t, rec), target) + } + } + listing := s.get("/ocap/data/", "") + assert.NotContains(t, listing.Body.String(), path.Base(path.Dir(rel)), "no listing names an upload") + } + + close(release) + assert.Equal(t, http.StatusOK, <-codes) + assert.Equal(t, http.StatusOK, <-codes) + left, err := os.ReadDir(filepath.Join(s.dataDir, uploadStagingDir)) + require.NoError(t, err) + assert.Empty(t, left, "published uploads leave nothing staged") + rec := s.get("/ocap/data/pending.json.gz", "") + require.Equal(t, http.StatusOK, rec.Code) + assert.False(t, leaks(t, rec), "only the masked upload is published") +} + +// A stored recording is served only by the names it is stored under, or by a +// name the chat check recognises as its own. Any other name the disk resolves +// to it (another case, dots or spaces after it, a stream after a colon, a +// backslash) is refused before its chat could leave unmasked. Each name is +// asked for first, while the files still hold the password. +func TestStoredRecordingIsNotServedByAnotherName(t *testing.T) { + for _, alias := range []string{ + "leaky.JSON.GZ", "LEAKY.json.gz", "Leaky.Json", "leaky.json.gz.", "leaky.json.gz%20", "leaky.json.gz::$DATA", + "leaky/MANIFEST.PB", "leaky/manifest.pb.", "leaky/manifest.pb%20", "leaky/manifest.pb::$DATA", "LEAKY/manifest.pb", + "leaky./manifest.pb", "leaky/MANIFEST.PB.ZST", "leaky/manifest.pb.zst.", "leaky/manifest.pb.zst%20", + "leaky%5Cmanifest.pb", + } { + for _, encoding := range []string{"", "gzip, zstd"} { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "leaky") + storePlayerOp(t, s.repo, "leaky", "Leaky", "altis", "2026-01-01") + rec := s.get("/ocap/data/"+alias, encoding) + assert.False(t, leaks(t, rec), "%s with Accept-Encoding %q answered %d", alias, encoding, rec.Code) + + for _, name := range []string{"leaky.json.gz", "leaky/manifest.pb", "leaky/manifest.pb.zst"} { + rec := s.get("/ocap/data/"+name, "") + require.Equal(t, http.StatusOK, rec.Code, "%s after %s", name, alias) + assert.False(t, leaks(t, rec), name) + } + } + } + + t.Run("a recording whose name ends in a dot", func(t *testing.T) { + // Windows stores its directory without the dot; it is still served, + // masked, by the name it was given. + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "Trail.") + storePlayerOp(t, s.repo, "Trail.", "Trail", "altis", "2026-01-01") + for _, name := range []string{"Trail./manifest.pb", "Trail..json.gz"} { + rec := s.get("/ocap/data/"+name, "") + require.Equal(t, http.StatusOK, rec.Code, name) + assert.False(t, leaks(t, rec), name) + } + }) +} diff --git a/internal/server/datapath_other.go b/internal/server/datapath_other.go new file mode 100644 index 00000000..d77a1144 --- /dev/null +++ b/internal/server/datapath_other.go @@ -0,0 +1,10 @@ +//go:build !windows + +package server + +// namedAsStored reports whether each element of urlPath, under root, names +// its file as the disk stores it. Here a file has the one name; a disk that +// ignores case is left to the checks that go by name, which ignore it too. +func namedAsStored(root, urlPath string) bool { + return true +} diff --git a/internal/server/datapath_windows.go b/internal/server/datapath_windows.go new file mode 100644 index 00000000..9e27d987 --- /dev/null +++ b/internal/server/datapath_windows.go @@ -0,0 +1,77 @@ +//go:build windows + +package server + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + "syscall" +) + +// namedAsStored reports whether each element of urlPath, under root, names +// its file as the disk stores it. Windows also opens a file by another case, +// by its 8.3 short name or with a stream after a colon, and a request by any +// of those would get past the checks that go by name. It drops dots and +// spaces from the end of an element, and so did the disk when the file was +// made: a recording named "Op." has its directory stored as "Op", so the name +// without them is the one that has to match, and the checks by name allow for +// them. A path that resolves to nothing has nothing to alias. +func namedAsStored(root, urlPath string) bool { + path, err := filepath.Abs(root) + if err != nil { + return false + } + for _, elem := range strings.Split(strings.TrimPrefix(urlPath, "/"), "/") { + if elem == "" { + continue // the data directory itself + } + name := strings.TrimRight(elem, ". ") + if name == "" { + return false // the directory it is in + } + path = filepath.Join(path, name) + stored, err := storedName(path) + if err != nil { + // Windows could not look the name up as given: fine if nothing + // is there, not if it still opens something by that name. + _, statErr := os.Lstat(path) + return errors.Is(statErr, fs.ErrNotExist) + } + if stored != name { + return false + } + } + return true +} + +// storedName returns the name the disk stores the last element of path +// under. The path is passed on as written, past the normalization and the +// length limit, so that element is looked up as it is; case and 8.3 names +// still resolve, and the stored name tells them apart. +func storedName(path string) (string, error) { + name, err := syscall.UTF16PtrFromString(verbatimPath(path)) + if err != nil { + return "", err + } + var found syscall.Win32finddata + handle, err := syscall.FindFirstFile(name, &found) + if err != nil { + return "", err + } + syscall.FindClose(handle) + return syscall.UTF16ToString(found.FileName[:]), nil +} + +// verbatimPath returns an absolute path in the form Windows takes as written. +func verbatimPath(path string) string { + switch { + case strings.HasPrefix(path, `\\?\`): + return path + case strings.HasPrefix(path, `\\`): + return `\\?\UNC\` + path[2:] + } + return `\\?\` + path +} diff --git a/internal/server/datapath_windows_test.go b/internal/server/datapath_windows_test.go new file mode 100644 index 00000000..f37cdb5c --- /dev/null +++ b/internal/server/datapath_windows_test.go @@ -0,0 +1,123 @@ +//go:build windows + +package server + +import ( + "net/http" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Windows opens a file by more names than the one it is stored under; only +// that one passes, with or without the dots and spaces Windows drops. +func TestNamedAsStored(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(root, "Rec", "chunks"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(root, "Rec.json.gz"), []byte("x"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(root, "Rec", "manifest.pb"), []byte("x"), 0o644)) + + for urlPath, want := range map[string]bool{ + "/": true, + "/Rec.json.gz": true, + "/Rec/manifest.pb": true, + "/Rec/chunks": true, + "/missing.json.gz": true, + "/Rec/missing/x.pb": true, + "/rec.json.gz": false, + "/REC/manifest.pb": false, + "/Rec/Manifest.pb": false, + "/Rec.json.gz.": true, + "/Rec.json.gz . ": true, + "/Rec./manifest.pb": true, + "/REC.json.gz.": false, + "/Rec.json.gz::$DATA": false, + "/Rec::$INDEX_ALLOCATION/manifest.pb": false, + "/R*": false, + "/Rec?json.gz": false, + "/...": false, + "/nul\x00": false, + } { + assert.Equal(t, want, namedAsStored(root, urlPath), "%q", urlPath) + } + + t.Run("an 8.3 short name", func(t *testing.T) { + long := filepath.Join(root, "a long recording name.json.gz") + require.NoError(t, os.WriteFile(long, []byte("x"), 0o644)) + short := shortPathName(t, long) + if strings.EqualFold(filepath.Base(short), filepath.Base(long)) { + t.Skip("this disk keeps no 8.3 names") + } + assert.False(t, namedAsStored(root, "/"+filepath.Base(short)), filepath.Base(short)) + assert.True(t, namedAsStored(root, "/"+filepath.Base(long))) + }) + + t.Run("a path past the old length limit", func(t *testing.T) { + deep := root + for len(deep) < 300 { + deep = filepath.Join(deep, "a-rather-long-directory-name") + } + require.NoError(t, os.MkdirAll(deep, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(deep, "manifest.pb"), []byte("x"), 0o644)) + rel, err := filepath.Rel(root, deep) + require.NoError(t, err) + assert.True(t, namedAsStored(root, "/"+filepath.ToSlash(rel)+"/manifest.pb")) + assert.False(t, namedAsStored(root, "/"+filepath.ToSlash(rel)+"/MANIFEST.PB")) + }) + + t.Run("a data directory Windows cannot resolve", func(t *testing.T) { + assert.False(t, namedAsStored("bad\x00root", "/Rec.json.gz")) + }) + + t.Run("a data directory given verbatim", func(t *testing.T) { + sep := string(filepath.Separator) + verbatim := sep + sep + "?" + sep + root + assert.True(t, namedAsStored(verbatim, "/Rec.json.gz")) + assert.False(t, namedAsStored(verbatim, "/rec.json.gz")) + }) + +} + +func TestVerbatimPath(t *testing.T) { + for path, want := range map[string]string{ + `C:\data\rec.json.gz`: `\\?\C:\data\rec.json.gz`, + `\\host\share\rec.json.gz`: `\\?\UNC\host\share\rec.json.gz`, + `\\?\C:\data\rec.json.gz`: `\\?\C:\data\rec.json.gz`, + } { + assert.Equal(t, want, verbatimPath(path)) + } +} + +// A disk that keeps 8.3 names opens a stored recording by its short name too, +// which no check by name recognises; it is refused before its chat could leave +// unmasked. +func TestStoredRecordingIsNotServedByItsShortName(t *testing.T) { + s := newRedactionServer(t) + storeLeakyRecording(t, s.dataDir, "a long recording name") + storePlayerOp(t, s.repo, "a long recording name", "Long", "altis", "2026-01-01") + shortJSON := filepath.Base(shortPathName(t, filepath.Join(s.dataDir, "a long recording name.json.gz"))) + shortDir := filepath.Base(shortPathName(t, filepath.Join(s.dataDir, "a long recording name"))) + if strings.EqualFold(shortDir, "a long recording name") { + t.Skip("this disk keeps no 8.3 names") + } + for _, alias := range []string{shortJSON, shortDir + "/manifest.pb", shortDir + "/manifest.pb.zst"} { + rec := s.get("/ocap/data/"+alias, "gzip, zstd") + assert.Equal(t, http.StatusNotFound, rec.Code, alias) + assert.False(t, leaks(t, rec), alias) + } +} + +func shortPathName(t *testing.T, path string) string { + t.Helper() + long, err := syscall.UTF16PtrFromString(path) + require.NoError(t, err) + buf := make([]uint16, 1024) + n, err := syscall.GetShortPathName(long, &buf[0], uint32(len(buf))) + require.NoError(t, err) + return syscall.UTF16ToString(buf[:n]) +} diff --git a/internal/server/handler.go b/internal/server/handler.go index 1e53f138..3dead636 100644 --- a/internal/server/handler.go +++ b/internal/server/handler.go @@ -23,6 +23,7 @@ import ( "sync" "time" + "github.com/OCAP2/web/internal/ingestion" "github.com/OCAP2/web/internal/maptool" "github.com/getkin/kin-openapi/openapi3" "github.com/go-fuego/fuego" @@ -67,6 +68,13 @@ type StatsComputer interface { ComputeStatsFor(ctx context.Context, id int64, filename string) error } +// PlayerIndexer indexes the players of one recording for player search and +// profiles. Uploads are indexed with their stats or by conversion; this covers +// streamed recordings, which neither touches. +type PlayerIndexer interface { + IndexPlayersFor(ctx context.Context, id int64, filename string) error +} + type Handler struct { repoOperation *RepoOperation repoMarker *RepoMarker @@ -75,6 +83,8 @@ type Handler struct { jwt *JWTManager conversionTrigger ConversionTrigger // optional, nil if conversion disabled statsComputer StatsComputer // optional, set when conversion is disabled + playerIndexer PlayerIndexer // optional, nil leaves streamed recordings to the backfill + chatRedactor *ChatRedactor // masks #login passwords in stored files before serving them staticFS fs.FS // optional, nil disables static file serving maptoolMgr *maptool.JobManager // optional, nil if maptool disabled maptoolCfg *maptoolConfig // optional, nil if maptool disabled @@ -109,6 +119,14 @@ func WithStatsComputer(computer StatsComputer) HandlerOption { } } +// WithPlayerIndexer sets the indexer that adds streamed recordings to player +// search and profiles once they are saved. +func WithPlayerIndexer(indexer PlayerIndexer) HandlerOption { + return func(h *Handler) { + h.playerIndexer = indexer + } +} + // WithStaticFS sets the filesystem used to serve the frontend func WithStaticFS(fsys fs.FS) HandlerOption { return func(h *Handler) { @@ -154,6 +172,9 @@ func NewHandler( for _, opt := range opts { opt(&hdlr) } + if hdlr.chatRedactor == nil { + hdlr.chatRedactor = NewChatRedactor(repoOperation, setting.Data) + } hdlr.jwt = NewJWTManager(setting.Secret, setting.Auth.SessionTTL) hdlr.openIDCache = openid.NewSimpleDiscoveryCache() @@ -179,10 +200,15 @@ func NewHandler( // Viewer-gated endpoints (require valid JWT in non-public modes) viewer := fuego.Group(g, "") fuego.Use(viewer, hdlr.requireViewer) - fuego.Get(viewer, "/api/v1/operations", hdlr.GetOperations, fuego.OptionTags("Recordings")) + fuego.Get(viewer, "/api/v1/operations", hdlr.GetOperations, fuego.OptionTags("Recordings"), + fuego.OptionResponseHeader("X-Total-Count", "Recordings matching the filter, ignoring limit, offset and after"), + fuego.OptionResponseHeader("X-Next-Cursor", "The after of the next page; absent on the last")) + fuego.Get(viewer, "/api/v1/operations/summary", hdlr.GetOperationsSummary, fuego.OptionTags("Recordings")) fuego.Get(viewer, "/api/v1/operations/{id}", hdlr.GetOperation, fuego.OptionTags("Recordings")) fuego.Get(viewer, "/api/v1/operations/{id}/marker-blacklist", hdlr.GetMarkerBlacklist, fuego.OptionTags("Recordings")) fuego.Get(viewer, "/api/v1/worlds", hdlr.GetWorlds, fuego.OptionTags("Recordings")) + fuego.Get(viewer, "/api/v1/players", hdlr.SearchPlayers, fuego.OptionTags("Players")) + fuego.Get(viewer, "/api/v1/players/profile", hdlr.GetPlayerProfile, fuego.OptionTags("Players")) // Assets (static file serving) cacheMiddleware := hdlr.cacheControl(CacheDuration) @@ -287,19 +313,36 @@ func (*Handler) cacheControl(duration time.Duration) func(http.Handler) http.Han } } +// GetOperations lists the recordings matching the query, one page of them when +// limit is set. X-Total-Count carries the number of matches across all pages, +// and X-Next-Cursor, on a full page, the after that continues behind it. func (h *Handler) GetOperations(c fuego.Context[any, Filter]) ([]Operation, error) { ctx := c.Context() - filter := Filter{ - Name: c.QueryParam("name"), - Older: c.QueryParam("older"), - Newer: c.QueryParam("newer"), - Tag: c.QueryParam("tag"), + filter, err := h.operationFilter(c) + if err != nil { + return nil, fuego.BadRequestError{Err: err, Detail: err.Error()} } + total := -1 + if filter.Limit > 0 { + if total, err = h.repoOperation.Count(ctx, filter); err != nil { + return nil, err + } + } ops, err := h.repoOperation.Select(ctx, filter) + if errors.Is(err, ErrInvalidCursor) { + return nil, fuego.BadRequestError{Err: err, Detail: "after is not a cursor this server returned"} + } if err != nil { return nil, err } + if total < 0 { + total = len(ops) + } + c.SetHeader("X-Total-Count", strconv.Itoa(total)) + if next := filter.NextCursor(ops); next != "" { + c.SetHeader("X-Next-Cursor", next) + } return ops, nil } @@ -393,7 +436,7 @@ func (h *Handler) StoreOperation(w http.ResponseWriter, r *http.Request) { // directories. Mirror the cleanup performed by migration v11. filename = decodeFilename(filename) - if isInvalidStorageName(filename) { + if isInvalidStorageName(filename) || inUploadStaging(h.setting.Data, filename) { http.Error(w, "Invalid filename", http.StatusBadRequest) return } @@ -469,8 +512,16 @@ func (h *Handler) StoreOperation(w http.ResponseWriter, r *http.Request) { } isGzipped := header[0] == 0x1f && header[1] == 0x8b - finalPath := filepath.Join(h.setting.Data, filename+".json.gz") - tmpPath := finalPath + ".tmp" + // The upload is staged in a directory of its own that the data route never + // serves: until it is masked below it may hold a #login password. Only the + // masked file is published, by a rename over the recording. + stageDir, err := makeUploadStage(h.setting.Data) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer os.RemoveAll(stageDir) + tmpPath := filepath.Join(stageDir, "recording.json.gz") tmpFile, err := createUploadFile(tmpPath) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -491,13 +542,23 @@ func (h *Handler) StoreOperation(w http.ResponseWriter, r *http.Request) { return gw.Close() }() if writeErr != nil { - os.Remove(tmpPath) http.Error(w, writeErr.Error(), http.StatusInternalServerError) return } - if err := renameUploadFile(tmpPath, finalPath); err != nil { - os.Remove(tmpPath) + // Mask #login passwords before the upload is published: a replaced + // recording stays marked as checked until its row is written below, or + // for good if that fails, and is served without a check in between. + if _, err := redactUpload(tmpPath); err != nil { + status := http.StatusInternalServerError + if errors.Is(err, ingestion.ErrUnreadableRecording) { + status = http.StatusBadRequest + } + http.Error(w, err.Error(), status) + return + } + + if err := renameUploadFile(tmpPath, filepath.Join(h.setting.Data, filename+".json.gz")); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -548,8 +609,42 @@ func (h *Handler) GetData(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } + // An upload waits in the staging area until it is checked, a file being + // written is not served under its temporary name, and a file is served + // only by the name it is stored under: no other name gets past the checks + // that go by name. + if inUploadStaging(h.setting.Data, relativePath) || isTemporaryFile(path.Base(relativePath)) || + !namedAsStored(h.setting.Data, relativePath) { + http.NotFound(w, r) + return + } absolutePath := filepath.Join(h.setting.Data, relativePath) + // A recording stored before chat was masked may still hold a #login + // password; mask it before any of its chat leaves the server. A file that + // can hold chat is served once the check of its part has read it and found + // it clean: neither a file of no recording nor one no check reads is + // served, and a part that cannot be checked keeps only itself from being + // served. Only the manifest's own sidecars may stand in for it. + sidecars := true + if file, ok := chatFileAt(relativePath); ok { + if !file.checked { + http.NotFound(w, r) + return + } + if h.chatRedactor != nil { + if err := h.chatRedactor.Ensure(r.Context(), file.recording, file.part); errors.Is(err, ErrNotFound) { + http.NotFound(w, r) + return + } else if err != nil { + slog.Error("not serving a recording file that could not be checked for #login passwords", "filename", file.recording, "error", err) + http.Error(w, "recording temporarily unavailable", http.StatusServiceUnavailable) + return + } + } + sidecars = file.sidecars + } + // For .json.gz files, check if the content is actually gzipped // before setting Content-Encoding. Legacy uploads may have stored // raw JSON with a .json.gz extension. @@ -587,7 +682,7 @@ func (h *Handler) GetData(w http.ResponseWriter, r *http.Request) { // Accept-Encoding, so caches have to key on it whichever one answers. w.Header().Add("Vary", "Accept-Encoding") contentType := dataContentType(relativePath) - if servePrecompressed(w, r, absolutePath, contentType) { + if sidecars && servePrecompressed(w, r, absolutePath, contentType) { return } if contentType != "" { @@ -789,6 +884,7 @@ type uploadTempFile interface { var ( createUploadFile = func(p string) (uploadTempFile, error) { return os.Create(p) } + redactUpload = ingestion.RedactJSONFile renameUploadFile = os.Rename removeStaleUploadDir = os.RemoveAll ) @@ -829,6 +925,10 @@ func paramPathFromRequest(r *http.Request, param string) (string, error) { if err != nil { return "", fmt.Errorf("path unescape: %w", err) } + // Windows also splits a path at a backslash, which no stored name has. + if strings.ContainsRune(urlPath, '\\') { + return "", ErrInvalidPath + } // Use path.Clean (not filepath.Clean) for URL paths - URLs always use forward slashes cleanPath := path.Clean("/" + urlPath) diff --git a/internal/server/handler_admin.go b/internal/server/handler_admin.go index 51fc172d..0c8bcb5d 100644 --- a/internal/server/handler_admin.go +++ b/internal/server/handler_admin.go @@ -221,8 +221,9 @@ func (h *Handler) DeleteOperation(c ContextNoBody) (any, error) { // Missing paths are not errors; failures are logged and ignored (best-effort). func removeRecordingArtifacts(dataDir, filename string) { // Defense in depth: never let an empty/"."/".."/separator filename turn the - // RemoveAll below into a wipe of the entire data directory. - if isInvalidStorageName(filename) { + // RemoveAll below into a wipe of the entire data directory, or of the + // uploads waiting in its staging area. + if isInvalidStorageName(filename) || inUploadStaging(dataDir, filename) { slog.Warn("refusing to remove recording artifacts for invalid filename", "filename", filename) return } diff --git a/internal/server/handler_admin_test.go b/internal/server/handler_admin_test.go index a360ca2c..a5f10b12 100644 --- a/internal/server/handler_admin_test.go +++ b/internal/server/handler_admin_test.go @@ -873,14 +873,19 @@ func TestRemoveRecordingArtifacts(t *testing.T) { }) t.Run("refuses unsafe filenames and leaves data dir intact", func(t *testing.T) { - for _, name := range []string{"", ".", "..", "/"} { + for _, name := range []string{"", ".", "..", "/", "...", uploadStagingDir, ".UPLOAD-STAGING", uploadStagingDir + "."} { dataDir := t.TempDir() canary := filepath.Join(dataDir, "canary.txt") require.NoError(t, os.WriteFile(canary, []byte("keep"), 0644)) + stage, err := makeUploadStage(dataDir) + require.NoError(t, err) + staged := filepath.Join(stage, "recording.json.gz") + require.NoError(t, os.WriteFile(staged, []byte("in flight"), 0644)) removeRecordingArtifacts(dataDir, name) assert.FileExists(t, canary, "data dir must survive removeRecordingArtifacts(%q)", name) + assert.FileExists(t, staged, "staged uploads must survive removeRecordingArtifacts(%q)", name) assert.DirExists(t, dataDir) } }) diff --git a/internal/server/handler_players.go b/internal/server/handler_players.go new file mode 100644 index 00000000..87edd661 --- /dev/null +++ b/internal/server/handler_players.go @@ -0,0 +1,153 @@ +package server + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math" + "strconv" + "strings" + + "github.com/go-fuego/fuego" +) + +const ( + // maxOperationsPage caps one page of the recording list. + maxOperationsPage = 500 + // maxPlayerResults caps one player search. + maxPlayerResults = 100 + // defaultPlayerResults is the player search size when limit is omitted. + defaultPlayerResults = 20 +) + +// PlayerSearchParams documents the player search query. +type PlayerSearchParams struct { + Query string `query:"q" description:"In-game name contains, any case, or a Steam UID; omitted lists the most active players"` + Limit int `query:"limit" description:"Players to return, at most 100; default 20"` +} + +// PlayerProfileParams documents the player profile query. A player with a +// Steam UID is looked up by it; name finds a player recorded without one. +type PlayerProfileParams struct { + UID string `query:"uid" description:"Steam UID"` + Name string `query:"name" description:"In-game name, any case, of a player recorded without a Steam UID; ignored with uid"` +} + +// queryParams reads query parameters; every fuego context has it. +type queryParams interface { + QueryParam(name string) string +} + +// queryInt parses an optional integer query parameter from 0 to max; an +// omitted one is 0. +func queryInt(c queryParams, name string, max int) (int, error) { + raw := c.QueryParam(name) + if raw == "" { + return 0, nil + } + n, err := strconv.Atoi(raw) + if err != nil || n < 0 || n > max { + return 0, fmt.Errorf("%s must be an integer from 0 to %d", name, max) + } + return n, nil +} + +// operationFilter reads and validates the recording list query. +func (h *Handler) operationFilter(c fuego.Context[any, Filter]) (Filter, error) { + f := Filter{ + Name: c.QueryParam("name"), + Older: c.QueryParam("older"), + Newer: c.QueryParam("newer"), + Tag: c.QueryParam("tag"), + TagExact: c.QueryParam("tagExact"), + Query: strings.TrimSpace(c.QueryParam("q")), + Player: c.QueryParam("player"), + PlayerUID: strings.TrimSpace(c.QueryParam("playerUid")), + Sort: c.QueryParam("sort"), + Dir: c.QueryParam("dir"), + After: c.QueryParam("after"), + } + for _, value := range c.QueryParamArr("world") { + for _, world := range strings.Split(value, ",") { + if world = strings.TrimSpace(world); world != "" { + f.Worlds = append(f.Worlds, world) + } + } + } + if _, ok := operationSorts[f.Sort]; f.Sort != "" && !ok { + return f, errors.New("sort must be date, name or duration") + } + if f.Dir != "" && f.Dir != "asc" && f.Dir != "desc" { + return f, errors.New("dir must be asc or desc") + } + var err error + if f.Limit, err = queryInt(c, "limit", maxOperationsPage); err != nil { + return f, err + } + if f.Offset, err = queryInt(c, "offset", math.MaxInt32); err != nil { + return f, err + } + if f.Query != "" { + f.queryWorlds = h.worldsNamed(f.Query) + } + return f, nil +} + +// worldsNamed returns the installed worlds whose display name contains query, +// so a search for "Chernarus" finds recordings stored as "chernarus_summer". +// Unreadable maps leave the search to the stored world names. +func (h *Handler) worldsNamed(query string) []string { + worlds, _ := ScanWorlds(h.setting.Maps) + q := strings.ToLower(query) + var names []string + for _, w := range worlds { + if strings.Contains(strings.ToLower(w.DisplayName), q) { + names = append(names, strings.ToLower(w.Name)) + } + } + return names +} + +// GetOperationsSummary describes every stored recording for the list header +// and filters. +func (h *Handler) GetOperationsSummary(c ContextNoBody) (*OperationsSummary, error) { + return h.repoOperation.Summary(c.Context()) +} + +// SearchPlayers finds players by in-game name or Steam UID across all indexed +// recordings. +func (h *Handler) SearchPlayers(c fuego.Context[any, PlayerSearchParams]) ([]PlayerSummary, error) { + limit, err := queryInt(c, "limit", maxPlayerResults) + if err != nil { + return nil, fuego.BadRequestError{Err: err, Detail: err.Error()} + } + if limit == 0 { + limit = defaultPlayerResults + } + return h.repoOperation.SearchPlayers(c.Context(), c.QueryParam("q"), limit) +} + +// GetPlayerProfile returns a player's record across all indexed recordings. +func (h *Handler) GetPlayerProfile(c fuego.Context[any, PlayerProfileParams]) (*PlayerProfile, error) { + uid, name := c.QueryParam("uid"), c.QueryParam("name") + if PlayerKey(uid, name) == "" { + return nil, fuego.BadRequestError{Detail: "uid or name is required"} + } + profile, err := h.repoOperation.GetPlayerProfile(c.Context(), uid, name) + if errors.Is(err, ErrNotFound) { + return nil, fuego.NotFoundError{Err: err, Detail: "player not found"} + } + return profile, err +} + +// indexPlayers adds a saved recording to player search when an indexer is +// set. A failure only delays it to the next startup backfill. +func (h *Handler) indexPlayers(ctx context.Context, id int64, filename string) { + if h.playerIndexer == nil { + return + } + if err := h.playerIndexer.IndexPlayersFor(ctx, id, filename); err != nil { + slog.Warn("failed to index recording players", "operation_id", id, "error", err) + } +} diff --git a/internal/server/handler_players_test.go b/internal/server/handler_players_test.go new file mode 100644 index 00000000..c6714730 --- /dev/null +++ b/internal/server/handler_players_test.go @@ -0,0 +1,411 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/OCAP2/extension/v5/pkg/core" + "github.com/OCAP2/web/internal/ingestion" + "github.com/go-fuego/fuego" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// recordingIndexer records the recordings it is asked to index. +type recordingIndexer struct { + calls []string + err error +} + +func (r *recordingIndexer) IndexPlayersFor(_ context.Context, _ int64, filename string) error { + r.calls = append(r.calls, filename) + return r.err +} + +// listContext builds a recording list request with these query parameters. +func listContext(params map[string]string) *fuego.MockContext[any, Filter] { + c := fuego.NewMockContext[any](nil, Filter{}) + for k, v := range params { + c.SetQueryParam(k, v) + } + return c +} + +func TestGetOperationsPaging(t *testing.T) { + repo := newPlayersRepo(t) + for _, op := range []*Operation{ + {WorldName: "altis", MissionName: "One", Filename: "one", Date: "2026-01-01"}, + {WorldName: "stratis", MissionName: "Two", Filename: "two", Date: "2026-01-02"}, + {WorldName: "chernarus_summer", MissionName: "Three", Filename: "three", Date: "2026-01-03"}, + } { + require.NoError(t, repo.Store(t.Context(), op)) + } + mapsDir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(mapsDir, "chernarus_summer"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(mapsDir, "chernarus_summer", "meta.json"), []byte(`{"displayName":"Chernarus (Summer)"}`), 0o644)) + h := &Handler{repoOperation: repo, setting: Setting{Maps: mapsDir}} + + t.Run("without limit every match is returned and counted", func(t *testing.T) { + c := listContext(nil) + ops, err := h.GetOperations(c) + require.NoError(t, err) + assert.Len(t, ops, 3) + assert.Equal(t, "3", c.Header("X-Total-Count")) + }) + + t.Run("a page carries the total of all pages", func(t *testing.T) { + c := listContext(map[string]string{"sort": "date", "dir": "desc", "limit": "2", "offset": "1"}) + ops, err := h.GetOperations(c) + require.NoError(t, err) + require.Len(t, ops, 2) + assert.Equal(t, "two", ops[0].Filename) + assert.Equal(t, "one", ops[1].Filename) + assert.Equal(t, "3", c.Header("X-Total-Count")) + }) + + t.Run("a full page carries the cursor of the next", func(t *testing.T) { + c := listContext(map[string]string{"sort": "date", "dir": "desc", "limit": "2"}) + ops, err := h.GetOperations(c) + require.NoError(t, err) + require.Len(t, ops, 2) + next := c.Header("X-Next-Cursor") + require.NotEmpty(t, next) + + c = listContext(map[string]string{"sort": "date", "dir": "desc", "limit": "2", "after": next}) + ops, err = h.GetOperations(c) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "one", ops[0].Filename) + assert.Equal(t, "3", c.Header("X-Total-Count"), "the total counts every page") + assert.Empty(t, c.Header("X-Next-Cursor"), "the last page has none") + }) + + t.Run("an after that is no cursor is a bad request", func(t *testing.T) { + _, err := h.GetOperations(listContext(map[string]string{"limit": "2", "after": "not a cursor"})) + var bad fuego.BadRequestError + require.ErrorAs(t, err, &bad) + }) + + t.Run("worlds may repeat and be comma-separated", func(t *testing.T) { + c := listContext(map[string]string{"world": "altis, ,"}) + c.UrlValues.Add("world", "STRATIS") + ops, err := h.GetOperations(c) + require.NoError(t, err) + assert.Len(t, ops, 2) + }) + + t.Run("q matches installed world display names", func(t *testing.T) { + c := listContext(map[string]string{"q": " summer) "}) + ops, err := h.GetOperations(c) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "three", ops[0].Filename) + }) + + t.Run("player limits the list to their recordings", func(t *testing.T) { + require.NoError(t, repo.ReplaceOperationPlayers(t.Context(), 2, []OperationPlayer{{Name: "Nosey"}})) + c := listContext(map[string]string{"player": "nosey"}) + ops, err := h.GetOperations(c) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "two", ops[0].Filename) + }) + + t.Run("tagExact selects one tag exactly", func(t *testing.T) { + require.NoError(t, repo.UpdateOperation(t.Context(), 1, "One", "COOP", "2026-01-01", nil, nil)) + require.NoError(t, repo.UpdateOperation(t.Context(), 2, "Two", "COOP-training", "2026-01-02", nil, nil)) + ops, err := h.GetOperations(listContext(map[string]string{"tagExact": "COOP"})) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "one", ops[0].Filename) + }) + + t.Run("playerUid limits the list to that player's recordings", func(t *testing.T) { + require.NoError(t, repo.ReplaceOperationPlayers(t.Context(), 3, []OperationPlayer{{UID: "76561190000000001", Name: "Viper"}})) + c := listContext(map[string]string{"playerUid": " 76561190000000001 "}) + ops, err := h.GetOperations(c) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "three", ops[0].Filename) + }) + + for name, params := range map[string]map[string]string{ + "unknown sort": {"sort": "players"}, + "unknown dir": {"dir": "up"}, + "limit not int": {"limit": "ten"}, + "negative limit": {"limit": "-1"}, + "limit too big": {"limit": "501"}, + "bad offset": {"offset": "-5"}, + } { + t.Run("rejects "+name, func(t *testing.T) { + _, err := h.GetOperations(listContext(params)) + var bad fuego.BadRequestError + assert.ErrorAs(t, err, &bad) + }) + } +} + +func TestGetOperationsPagingFailures(t *testing.T) { + t.Run("count", func(t *testing.T) { + repo := newPlayersRepo(t) + h := &Handler{repoOperation: repo} + require.NoError(t, repo.Close()) + _, err := h.GetOperations(listContext(map[string]string{"limit": "10"})) + assert.Error(t, err) + }) + + t.Run("select after count", func(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + // Counting reads no column; selecting cannot read a player count of "many". + mustExec(t, repo.db, `UPDATE operations SET player_count = 'many'`) + h := &Handler{repoOperation: repo} + _, err := h.GetOperations(listContext(map[string]string{"limit": "10"})) + assert.Error(t, err) + }) +} + +func TestGetOperationsSummaryHandler(t *testing.T) { + repo := newPlayersRepo(t) + storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + h := &Handler{repoOperation: repo} + summary, err := h.GetOperationsSummary(fuego.NewMockContextNoBody()) + require.NoError(t, err) + assert.Equal(t, 1, summary.Total) + assert.Equal(t, []string{"altis"}, summary.Worlds) +} + +func TestPlayerHandlers(t *testing.T) { + repo := newPlayersRepo(t) + id := storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + var players []OperationPlayer + for _, name := range []string{"Nosey", "Nomad"} { + players = append(players, OperationPlayer{Name: name, Side: "WEST"}) + } + for i := range 25 { + players = append(players, OperationPlayer{Name: "Rifleman " + itoa(int64(i))}) + } + players = append(players, OperationPlayer{UID: "76561190000000001", Name: "Viper", Side: "EAST"}) + require.NoError(t, repo.ReplaceOperationPlayers(t.Context(), id, players)) + h := &Handler{repoOperation: repo} + + search := func(params map[string]string) ([]PlayerSummary, error) { + c := fuego.NewMockContext[any](nil, PlayerSearchParams{}) + for k, v := range params { + c.SetQueryParam(k, v) + } + return h.SearchPlayers(c) + } + profile := func(params map[string]string) (*PlayerProfile, error) { + c := fuego.NewMockContext[any](nil, PlayerProfileParams{}) + for k, v := range params { + c.SetQueryParam(k, v) + } + return h.GetPlayerProfile(c) + } + + t.Run("search defaults to 20 results", func(t *testing.T) { + found, err := search(nil) + require.NoError(t, err) + assert.Len(t, found, defaultPlayerResults) + }) + + t.Run("search by name", func(t *testing.T) { + found, err := search(map[string]string{"q": "no", "limit": "100"}) + require.NoError(t, err) + require.Len(t, found, 2) + assert.Equal(t, "Nomad", found[0].Name) + }) + + t.Run("search by Steam UID", func(t *testing.T) { + found, err := search(map[string]string{"q": "76561190000000001"}) + require.NoError(t, err) + require.Len(t, found, 1) + assert.Equal(t, PlayerSummary{UID: "76561190000000001", Name: "Viper", Missions: 1, LastPlayed: "2026-01-01"}, found[0]) + }) + + t.Run("search rejects a bad limit", func(t *testing.T) { + _, err := search(map[string]string{"limit": "101"}) + var bad fuego.BadRequestError + assert.ErrorAs(t, err, &bad) + }) + + t.Run("profile by name", func(t *testing.T) { + p, err := profile(map[string]string{"name": "NOSEY"}) + require.NoError(t, err) + assert.Equal(t, "Nosey", p.Name) + assert.Empty(t, p.UID) + assert.Equal(t, 1, p.Missions) + }) + + t.Run("profile by Steam UID", func(t *testing.T) { + p, err := profile(map[string]string{"uid": "76561190000000001", "name": "Nosey"}) + require.NoError(t, err) + assert.Equal(t, "76561190000000001", p.UID) + assert.Equal(t, "Viper", p.Name, "uid takes precedence over name") + }) + + t.Run("profile needs a uid or a name", func(t *testing.T) { + _, err := profile(map[string]string{"uid": " ", "name": " "}) + var bad fuego.BadRequestError + require.ErrorAs(t, err, &bad) + assert.Equal(t, "uid or name is required", bad.Detail) + }) + + t.Run("profile of an unknown player", func(t *testing.T) { + _, err := profile(map[string]string{"name": "nobody"}) + var notFound fuego.NotFoundError + assert.ErrorAs(t, err, ¬Found) + + _, err = profile(map[string]string{"name": "Viper"}) + assert.ErrorAs(t, err, ¬Found, "a player with a Steam UID is not found by name") + }) + + t.Run("profile database failure", func(t *testing.T) { + require.NoError(t, repo.Close()) + _, err := profile(map[string]string{"name": "nosey"}) + require.Error(t, err) + var notFound fuego.NotFoundError + assert.False(t, errors.As(err, ¬Found)) + }) +} + +func TestIndexPlayers(t *testing.T) { + (&Handler{}).indexPlayers(t.Context(), 1, "no indexer") + + indexer := &recordingIndexer{err: errors.New("manifest unreadable")} + h := &Handler{} + WithPlayerIndexer(indexer)(h) + h.indexPlayers(t.Context(), 1, "failing") + assert.Equal(t, []string{"failing"}, indexer.calls, "a failure is logged, not returned") +} + +func TestFinalizeSessionIndexesPlayers(t *testing.T) { + newSession := func(name string) *ingestion.Session { + s := ingestion.NewSession() + s.SetMission(&core.Mission{MissionName: name, CaptureDelay: 1}, &core.World{WorldName: "altis"}) + s.HandleAddSoldier(core.Soldier{ID: 1, UnitName: "Nosey", IsPlayer: true}) + return s + } + + t.Run("native v2 recording", func(t *testing.T) { + dataDir := t.TempDir() + indexer := &recordingIndexer{} + h := &Handler{setting: Setting{Data: dataDir}, repoOperation: newPlayersRepo(t), playerIndexer: indexer, conversionTrigger: &mockConvTrigger{}} + outputDir := filepath.Join(dataDir, "native_v2") + flusher, err := ingestion.NewChunkFlusher(outputDir, 300) + require.NoError(t, err) + s := newSession("Native") + s.SetChunkFlusher(flusher) + require.NoError(t, h.finalizeSession(s, "", outputDir, 0)) + assert.Equal(t, []string{"native_v2"}, indexer.calls) + }) + + t.Run("v1 recording without conversion", func(t *testing.T) { + indexer := &recordingIndexer{} + h := &Handler{setting: Setting{Data: t.TempDir()}, repoOperation: newPlayersRepo(t), playerIndexer: indexer} + require.NoError(t, h.finalizeSession(newSession("Plain"), "", "", 0)) + require.Len(t, indexer.calls, 1) + }) + + t.Run("v1 recording left to conversion", func(t *testing.T) { + indexer := &recordingIndexer{} + h := &Handler{setting: Setting{Data: t.TempDir()}, repoOperation: newPlayersRepo(t), playerIndexer: indexer, conversionTrigger: &mockConvTrigger{}} + require.NoError(t, h.finalizeSession(newSession("Converted"), "", "", 0)) + assert.Empty(t, indexer.calls) + }) +} + +// mustField returns one top-level field of a JSON object, nil when absent. +func mustField(t *testing.T, body []byte, name string) json.RawMessage { + t.Helper() + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal(body, &fields)) + return fields[name] +} + +func TestPlayerAndSummaryRouteAccess(t *testing.T) { + dir := t.TempDir() + repo, err := NewRepoOperation(filepath.Join(dir, "operations.db")) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, repo.Close()) }) + id := storePlayerOp(t, repo, "summary", "Synthetic", "altis", "2026-01-01") + require.NoError(t, repo.ReplaceOperationPlayers(t.Context(), id, []OperationPlayer{ + {Name: "Nosey"}, {UID: "76561190000000001", Name: "Viper"}, + })) + + require.NoError(t, os.MkdirAll(filepath.Join(dir, "markers"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "ammo"), 0o755)) + repoMarker, err := NewRepoMarker(filepath.Join(dir, "markers")) + require.NoError(t, err) + repoAmmo, err := NewRepoAmmo(filepath.Join(dir, "ammo")) + require.NoError(t, err) + setting := Setting{ + PrefixURL: "/ocap", Secret: "synthetic-test-secret", Data: dir, + Auth: Auth{Mode: "password", SessionTTL: time.Hour}, + } + srv := fuego.NewServer(fuego.WithoutStartupMessages(), fuego.WithoutAutoGroupTags(), fuego.WithSecurity(OpenAPISecuritySchemes)) + NewHandler(srv, repo, repoMarker, repoAmmo, setting) + viewer, err := NewJWTManager(setting.Secret, setting.Auth.SessionTTL).Create("synthetic-viewer", WithRole("viewer")) + require.NoError(t, err) + + get := func(path, token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + rec := httptest.NewRecorder() + srv.Mux.ServeHTTP(rec, req) + return rec + } + + for _, path := range []string{ + "/ocap/api/v1/operations/summary", + "/ocap/api/v1/players?q=nos", + "/ocap/api/v1/players/profile?name=nosey", + "/ocap/api/v1/players/profile?uid=76561190000000001", + "/ocap/api/v1/operations?limit=1", + } { + assert.Equal(t, http.StatusUnauthorized, get(path, "").Code, "anonymous %s", path) + } + + rec := get("/ocap/api/v1/operations/summary", viewer) + require.Equal(t, http.StatusOK, rec.Code) + var summary OperationsSummary + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &summary), "summary must not be read as a recording id") + assert.Equal(t, 1, summary.Total) + + rec = get("/ocap/api/v1/operations?limit=1&sort=date&dir=desc", viewer) + require.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "1", rec.Header().Get("X-Total-Count")) + + rec = get("/ocap/api/v1/players?q=nos", viewer) + require.Equal(t, http.StatusOK, rec.Code) + var found []PlayerSummary + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &found)) + require.Len(t, found, 1) + + rec = get("/ocap/api/v1/players/profile?name=Nosey", viewer) + require.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `[]`, string(mustField(t, rec.Body.Bytes(), "aliases")), "aliases is a list, never null") + assert.Nil(t, mustField(t, rec.Body.Bytes(), "uid"), "a player without a Steam UID has no uid field") + + rec = get("/ocap/api/v1/players/profile?uid=76561190000000001", viewer) + require.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `"76561190000000001"`, string(mustField(t, rec.Body.Bytes(), "uid"))) + + rec = get("/ocap/api/v1/players?q=76561190000000001", viewer) + require.Equal(t, http.StatusOK, rec.Code) + assert.JSONEq(t, `[{"uid":"76561190000000001","name":"Viper","missions":1,"kills":0,"deaths":0,"lastPlayed":"2026-01-01"}]`, rec.Body.String()) + + assert.Equal(t, http.StatusNotFound, get("/ocap/api/v1/players/profile?name=nobody", viewer).Code) + assert.Equal(t, http.StatusBadRequest, get("/ocap/api/v1/players/profile", viewer).Code) + assert.Equal(t, http.StatusBadRequest, get("/ocap/api/v1/operations?sort=players", viewer).Code) +} diff --git a/internal/server/handler_stream.go b/internal/server/handler_stream.go index dece9ad8..f141728b 100644 --- a/internal/server/handler_stream.go +++ b/internal/server/handler_stream.go @@ -1026,6 +1026,10 @@ func (h *Handler) finalizeSession(session *ingestion.Session, tag string, v2Outp stats.PlayerCount, stats.KillCount, stats.PlayerKillCount, sideComp); err != nil { slog.Warn("stream: failed to update operation stats", "error", err) } + // A v1 recording handed to conversion is indexed when it converts. + if hasV2 || h.conversionTrigger == nil { + h.indexPlayers(ctx, op.ID, op.Filename) + } slog.Info("stream: finalized", "id", op.ID, diff --git a/internal/server/handler_test.go b/internal/server/handler_test.go index 88b17d64..88f434f7 100644 --- a/internal/server/handler_test.go +++ b/internal/server/handler_test.go @@ -651,6 +651,12 @@ func TestParamPath(t *testing.T) { wantPath: "", wantError: true, }, + { + name: "backslash blocked, which Windows splits a path at", + param: "rec%5Cmanifest.pb", + wantPath: "", + wantError: true, + }, } for _, tt := range tests { @@ -2082,9 +2088,10 @@ func TestSpaFileServer_FallsBackToIndex(t *testing.T) { func TestStoreOperation_DataDirWriteFailure(t *testing.T) { dir := t.TempDir() dataDir := filepath.Join(dir, "data") - // A directory where the upload's temp file belongs makes creating it fail - // on every OS, unlike permission bits. - require.NoError(t, os.MkdirAll(filepath.Join(dataDir, "test_readonly.json.gz.tmp"), 0755)) + // A file where the upload staging area belongs makes creating it fail on + // every OS, unlike permission bits. + require.NoError(t, os.MkdirAll(dataDir, 0755)) + require.NoError(t, os.WriteFile(filepath.Join(dataDir, uploadStagingDir), nil, 0644)) pathDB := filepath.Join(dir, "test.db") repo, err := NewRepoOperation(pathDB) diff --git a/internal/server/integration_test.go b/internal/server/integration_test.go index f46f0cd7..6627c167 100644 --- a/internal/server/integration_test.go +++ b/internal/server/integration_test.go @@ -584,9 +584,9 @@ func TestIntegration_UploadWriteFailureLeavesNoRow(t *testing.T) { setting: Setting{Data: dataDir, Secret: "test-secret"}, } - // A directory where the upload's temp file belongs makes creating it fail - // on every OS, unlike permission bits. - require.NoError(t, os.Mkdir(filepath.Join(dataDir, "write_fail.json.gz.tmp"), 0755)) + // A file where the upload staging area belongs makes creating it fail on + // every OS, unlike permission bits. + require.NoError(t, os.WriteFile(filepath.Join(dataDir, uploadStagingDir), nil, 0o644)) rec := uploadJSONRecording(t, hdlr, "write_fail", "Write Fail") assert.Equal(t, http.StatusInternalServerError, rec.Code) @@ -598,11 +598,12 @@ func TestIntegration_UploadWriteFailureLeavesNoRow(t *testing.T) { } // TestIntegration_UploadRejectsUnsafeFilename verifies that a filename which -// would resolve to the data directory itself (e.g. empty or ".") is rejected, -// rather than letting the stale-directory cleanup os.RemoveAll the whole data -// dir. A marker file in the data dir must survive a rejected upload. +// would resolve to the data directory itself (e.g. empty or ".") or to the +// upload staging area is rejected, rather than letting the stale-directory +// cleanup os.RemoveAll the whole data dir or the uploads staged in it. A +// marker file in the data dir and a staged upload must survive. func TestIntegration_UploadRejectsUnsafeFilename(t *testing.T) { - for _, name := range []string{"", ".", "..", "/"} { + for _, name := range []string{"", ".", "..", "/", "...", ". .", uploadStagingDir, ".Upload-Staging.", uploadStagingDir + " "} { t.Run("name="+name, func(t *testing.T) { dir := t.TempDir() dbPath := filepath.Join(dir, "test.db") @@ -618,13 +619,19 @@ func TestIntegration_UploadRejectsUnsafeFilename(t *testing.T) { setting: Setting{Data: dataDir, Secret: "test-secret"}, } - // A pre-existing file in the data directory that must not be wiped. + // A pre-existing file in the data directory that must not be wiped, + // and an upload staged by another request. canary := filepath.Join(dataDir, "canary.txt") require.NoError(t, os.WriteFile(canary, []byte("keep"), 0644)) + stage, err := makeUploadStage(dataDir) + require.NoError(t, err) + staged := filepath.Join(stage, "recording.json.gz") + require.NoError(t, os.WriteFile(staged, []byte("in flight"), 0644)) rec := uploadJSONRecording(t, hdlr, name, "Bad Name") assert.Equal(t, http.StatusBadRequest, rec.Code) assert.FileExists(t, canary, "data directory must survive a rejected upload") + assert.FileExists(t, staged, "the staging area must survive a rejected upload") }) } } diff --git a/internal/server/operation.go b/internal/server/operation.go index 75921cf8..f1713958 100644 --- a/internal/server/operation.go +++ b/internal/server/operation.go @@ -3,6 +3,7 @@ package server import ( "context" "database/sql" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -12,9 +13,26 @@ import ( "path/filepath" "strings" - _ "github.com/mattn/go-sqlite3" + "github.com/mattn/go-sqlite3" ) +// operationsDriver is SQLite with the functions the operations queries call. +const operationsDriver = "sqlite3_ocap" + +func init() { + sql.Register(operationsDriver, &sqlite3.SQLiteDriver{ + ConnectHook: func(conn *sqlite3.SQLiteConn) error { + return conn.RegisterFunc("ocap_fold", foldText, true) + }, + }) +} + +// foldText lowercases text for the recording search, in every script: SQLite's +// own lower() and LIKE fold ASCII only, so "évac" would miss "Évacuation". +func foldText(text string) string { + return strings.ToLower(text) +} + // Conversion status constants for operations. const ( ConversionStatusStreaming = "streaming" @@ -64,13 +82,100 @@ type Operation struct { FocusEnd *int64 `json:"focusEnd"` } +// Filter selects, orders and pages recordings. Its zero value returns every +// recording in id order, which is what clients that do not page rely on. type Filter struct { - Name string `query:"name"` - Older string `query:"older"` - Newer string `query:"newer"` - Tag string `query:"tag"` + Name string `query:"name" description:"Mission name contains"` + Older string `query:"older" description:"Recorded on or before this date (YYYY-MM-DD)"` + Newer string `query:"newer" description:"Recorded on or after this date (YYYY-MM-DD)"` + Tag string `query:"tag" description:"Tag contains"` + TagExact string `query:"tagExact" description:"Tag equals, in the same case"` + Query string `query:"q" description:"Mission name, world name or world display name contains"` + Worlds []string `query:"world" description:"Recorded on one of these worlds; repeat or comma-separate"` + Player string `query:"player" description:"Recordings a player of this in-game name, any case, took part in"` + PlayerUID string `query:"playerUid" description:"Recordings the player with this Steam UID took part in"` + Sort string `query:"sort" description:"date, name or duration; omitted keeps id order"` + Dir string `query:"dir" description:"asc (default) or desc"` + Limit int `query:"limit" description:"Page size, at most 500; omitted or 0 returns every match"` + Offset int `query:"offset" description:"Matches to skip before the page"` + After string `query:"after" description:"X-Next-Cursor of the previous page: continues right after its last recording, however the list changed since"` + + // queryWorlds are the worlds whose display name contains Query. Display + // names live in the maps directory, not the database, so the handler + // resolves them. + queryWorlds []string +} + +// operationSort is how one Filter.Sort value orders recordings, by an +// expression of the row, and the id after it. Bound is the same expression of +// a value a page cursor carries, so the next page starts where one ended. +type operationSort struct { + column string + bound string + value func(Operation) any +} + +// operationSorts maps a Filter.Sort value to its order. A date is a calendar +// date or an RFC3339 time with an offset; julianday turns both into the +// instant they name, so they sort by time, not as text. One it cannot read +// sorts first, as NULL would, but compares equal to itself, so a cursor can +// pass it. +var operationSorts = map[string]operationSort{ + "date": { + column: "COALESCE(julianday(date), -1e18)", bound: "COALESCE(julianday(?), -1e18)", + value: func(op Operation) any { return op.Date }, + }, + "name": { + column: "mission_name COLLATE NOCASE", bound: "?", + value: func(op Operation) any { return op.MissionName }, + }, + "duration": { + column: "mission_duration", bound: "?", + value: func(op Operation) any { return op.MissionDuration }, + }, +} + +// ErrInvalidCursor is returned for an After that no page produced. +var ErrInvalidCursor = errors.New("invalid page cursor") + +// pageCursor is the position after the last recording of a page: its sort +// value and id. +type pageCursor struct { + Value any `json:"v"` + ID int64 `json:"id"` } +// NextCursor returns the cursor of the page after ops, a full page of filter, +// or "" when ops is the last page. +func (f Filter) NextCursor(ops []Operation) string { + if f.Limit <= 0 || len(ops) < f.Limit { + return "" + } + last := ops[len(ops)-1] + cursor := pageCursor{ID: last.ID} + if sort, ok := operationSorts[f.Sort]; ok { + cursor.Value = sort.value(last) + } + data, _ := json.Marshal(cursor) // strings, numbers and nil always encode + return base64.RawURLEncoding.EncodeToString(data) +} + +// decodeCursor reads a cursor NextCursor returned. +func decodeCursor(encoded string) (pageCursor, error) { + var cursor pageCursor + data, err := base64.RawURLEncoding.DecodeString(encoded) + if err == nil { + err = json.Unmarshal(data, &cursor) + } + if err != nil { + return cursor, fmt.Errorf("%w: %w", ErrInvalidCursor, err) + } + return cursor, nil +} + +// escapeLike escapes LIKE wildcards so user input matches literally under ESCAPE '\'. +var escapeLike = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace + type RepoOperation struct { db *sql.DB dataDir string @@ -89,7 +194,7 @@ var ( // including filesystem migrations that rename mission data files/directories // under dataDir. If dataDir is empty, filesystem migrations are skipped. func NewRepoOperationWithDataDir(pathDB, dataDir string) (*RepoOperation, error) { - db, err := sqlOpen("sqlite3", pathDB) + db, err := sqlOpen(operationsDriver, pathDB) if err != nil { return nil, err } @@ -302,6 +407,73 @@ func (r *RepoOperation) migration() (err error) { } } + if version < 17 { + // The player index behind player search and profiles. A player is + // keyed by Steam UID when the recording has one and by lower-cased + // in-game name otherwise (see PlayerKey), with one row per recording; + // operation_player_names holds every name they used in it, the first + // being the row's name. player_index_revision makes the conversion + // worker index every completed recording once. + stmts := []string{ + `CREATE TABLE IF NOT EXISTS operation_players ( + operation_id INTEGER NOT NULL, + player_key TEXT NOT NULL, + player_uid TEXT NOT NULL DEFAULT '', + name_key TEXT NOT NULL, + name TEXT NOT NULL, + side TEXT NOT NULL DEFAULT '', + role TEXT NOT NULL DEFAULT '', + group_name TEXT NOT NULL DEFAULT '', + kills INTEGER NOT NULL DEFAULT 0, + vehicle_kills INTEGER NOT NULL DEFAULT 0, + team_kills INTEGER NOT NULL DEFAULT 0, + deaths INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (operation_id, player_key) + )`, + `CREATE INDEX IF NOT EXISTS idx_operation_players_player_key ON operation_players(player_key)`, + `CREATE TABLE IF NOT EXISTS operation_player_names ( + operation_id INTEGER NOT NULL, + player_key TEXT NOT NULL, + ordinal INTEGER NOT NULL, + name_key TEXT NOT NULL, + name TEXT NOT NULL, + PRIMARY KEY (operation_id, player_key, ordinal) + )`, + `CREATE INDEX IF NOT EXISTS idx_operation_player_names_player_key ON operation_player_names(player_key)`, + `CREATE INDEX IF NOT EXISTS idx_operation_player_names_name_key ON operation_player_names(name_key)`, + } + if !r.hasColumn("operations", "player_index_revision") { + stmts = append(stmts, `ALTER TABLE operations ADD COLUMN player_index_revision INTEGER DEFAULT 0`) + } + if err = r.runMigration(17, stmts...); err != nil { + return err + } + } + + if version < 18 { + // Saving a streamed recording kept the world name as the producer sent + // it, so a mixed-case name reached the summary but no world filter. + // Update lowercases it now, as Store always did; this fixes the rows + // saved before, as migration 10 did for older ones. + if err = r.runMigration(18, + `UPDATE operations SET world_name = LOWER(world_name) WHERE world_name != LOWER(world_name)`, + ); err != nil { + return err + } + } + + if version < 19 { + // chat_redaction_revision marks a recording whose files are known to + // hold no #login password; see ChatRedactor. + var stmts []string + if !r.hasColumn("operations", "chat_redaction_revision") { + stmts = append(stmts, `ALTER TABLE operations ADD COLUMN chat_redaction_revision INTEGER NOT NULL DEFAULT 0`) + } + if err = r.runMigration(19, stmts...); err != nil { + return err + } + } + return nil } @@ -372,12 +544,15 @@ func (r *RepoOperation) streamSegments(ctx context.Context, where string, missio // isInvalidStorageName reports whether name is unsafe to use as a recording's // on-disk storage key. Names like "", ".", ".." or any containing a path // separator make filepath.Join(dataDir, name) resolve to the data directory -// itself or its parent — catastrophic for os.RemoveAll. Such names must be -// rejected before any file operation keyed on the filename. +// itself or its parent — catastrophic for os.RemoveAll. Windows drops dots and +// spaces from the end of a path element, so "..." names the data directory +// there too. The upload staging area is no recording's either, in any case. +// Such names must be rejected before any file operation keyed on the filename. func isInvalidStorageName(name string) bool { - return strings.TrimSpace(name) == "" || - name == "." || name == ".." || - strings.ContainsAny(name, `/\`) + trimmed := strings.TrimRight(name, ". ") + return strings.TrimSpace(name) == "" || trimmed == "" || + strings.ContainsAny(name, `/\`) || + strings.EqualFold(trimmed, uploadStagingDir) } // decodeFilename returns the URL-decoded form of name if it contains percent @@ -621,6 +796,9 @@ func (r *RepoOperation) StoreReplacingByFilename(ctx context.Context, operation operation.Filename); err != nil { return err } + if err := deletePlayerIndex(ctx, tx, `IN (SELECT id FROM operations WHERE filename = ?)`, operation.Filename); err != nil { + return err + } if _, err := tx.ExecContext(ctx, `DELETE FROM operations WHERE filename = ?`, operation.Filename); err != nil { return err } @@ -630,37 +808,43 @@ func (r *RepoOperation) StoreReplacingByFilename(ctx context.Context, operation return tx.Commit() } +// Select returns the recordings matching filter, ordered and paged as it asks. +// The caller validates Sort and Dir; an unknown Sort keeps id order. After +// starts the page right behind the recording a cursor names, by its order +// rather than a count, so recordings added or deleted meanwhile neither repeat +// one nor skip one. func (r *RepoOperation) Select(ctx context.Context, filter Filter) ([]Operation, error) { - // Set defaults for date filters - older := filter.Older - if older == "" { - older = "9999-12-31" + where, args := filter.where() + + order, after := "id ASC", "id > ?" + sort, sorted := operationSorts[filter.Sort] + if sorted { + dir, cmp := "ASC", ">" + if filter.Dir == "desc" { + dir, cmp = "DESC", "<" + } + order = sort.column + " " + dir + ", id " + dir + after = "(" + sort.column + ", id) " + cmp + " (" + sort.bound + ", ?)" } - newer := filter.Newer - if newer == "" { - newer = "0000-01-01" + if filter.After != "" { + cursor, err := decodeCursor(filter.After) + if err != nil { + return nil, err + } + where += " AND " + after + if sorted { + args = append(args, cursor.Value) + } + args = append(args, cursor.ID) } - query := ` - SELECT - ` + operationColumns + ` - FROM - operations - WHERE - mission_name LIKE '%' || $1 || '%' - AND date <= $2 - AND date >= $3 - AND tag LIKE '%' || $4 || '%' - ORDER BY id ASC - ` - rows, err := r.db.QueryContext( - ctx, - query, - filter.Name, - older, - newer, - filter.Tag, - ) + query := `SELECT ` + operationColumns + ` FROM operations WHERE ` + where + ` ORDER BY ` + order + if filter.Limit > 0 { + query += ` LIMIT ? OFFSET ?` + args = append(args, filter.Limit, filter.Offset) + } + + rows, err := r.db.QueryContext(ctx, query, args...) if err != nil { return nil, err } @@ -669,6 +853,72 @@ func (r *RepoOperation) Select(ctx context.Context, filter Filter) ([]Operation, return r.scan(ctx, rows) } +// Count returns how many recordings match filter, ignoring its page. +func (r *RepoOperation) Count(ctx context.Context, filter Filter) (int, error) { + where, args := filter.where() + var n int + err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM operations WHERE `+where, args...).Scan(&n) + return n, err +} + +// where builds the WHERE clause shared by Select and Count. +func (f Filter) where() (string, []any) { + older := f.Older + if older == "" { + older = "9999-12-31" + } + newer := f.Newer + if newer == "" { + newer = "0000-01-01" + } + + clauses := []string{ + `mission_name LIKE '%' || ? || '%'`, + `date <= ?`, + `date >= ?`, + `tag LIKE '%' || ? || '%'`, + } + args := []any{f.Name, older, newer, f.Tag} + + if f.Query != "" { + match := `instr(ocap_fold(mission_name), ?) > 0 OR instr(ocap_fold(world_name), ?) > 0` + q := foldText(f.Query) + args = append(args, q, q) + if len(f.queryWorlds) > 0 { + match += ` OR world_name IN (` + placeholders(len(f.queryWorlds)) + `)` + for _, w := range f.queryWorlds { + args = append(args, w) + } + } + clauses = append(clauses, `(`+match+`)`) + } + if len(f.Worlds) > 0 { + clauses = append(clauses, `world_name IN (`+placeholders(len(f.Worlds))+`)`) + for _, w := range f.Worlds { + args = append(args, strings.ToLower(w)) + } + } + if f.TagExact != "" { + clauses = append(clauses, `tag = ?`) + args = append(args, f.TagExact) + } + if f.Player != "" { + clauses = append(clauses, `id IN (SELECT operation_id FROM operation_player_names WHERE name_key = ?)`) + args = append(args, NameKey(f.Player)) + } + if f.PlayerUID != "" { + clauses = append(clauses, `id IN (SELECT operation_id FROM operation_players WHERE player_key = ?)`) + args = append(args, PlayerKey(f.PlayerUID, "")) + } + + return strings.Join(clauses, " AND "), args +} + +// placeholders returns n comma-separated SQL placeholders. +func placeholders(n int) string { + return strings.TrimSuffix(strings.Repeat("?,", n), ",") +} + func (*RepoOperation) scan(ctx context.Context, rows *sql.Rows) ([]Operation, error) { var ( o = Operation{} @@ -798,8 +1048,11 @@ func (r *RepoOperation) ResetConversionStatus(ctx context.Context, fromStatus, t return result.RowsAffected() } -// Delete removes an operation record from the database. +// Delete removes an operation record and its player index rows from the database. func (r *RepoOperation) Delete(ctx context.Context, id int64) error { + if err := deletePlayerIndex(ctx, r.db, `= ?`, id); err != nil { + return err + } result, err := r.db.ExecContext(ctx, `DELETE FROM operations WHERE id = ?`, id) if err != nil { return err @@ -902,6 +1155,7 @@ func unmarshalSideComposition(raw string) SideComposition { } // Update writes the streaming-finalize mutable fields for an existing operation. +// The world name is lowercased, as Store does, so the world filter matches it. // Stats columns (player_count, kill_count, side_composition, player_kill_count) // are owned by UpdateStreamingMeta / UpdateOperationStats and not touched here. func (r *RepoOperation) Update(ctx context.Context, op *Operation) error { @@ -911,7 +1165,7 @@ func (r *RepoOperation) Update(ctx context.Context, op *Operation) error { date = ?, tag = ?, storage_format = ?, conversion_status = ?, schema_version = ?, chunk_count = ?, focus_start = ?, focus_end = ? WHERE id = ?`, - op.WorldName, op.MissionName, op.MissionDuration, op.Filename, + strings.ToLower(op.WorldName), op.MissionName, op.MissionDuration, op.Filename, op.Date, op.Tag, op.StorageFormat, op.ConversionStatus, op.SchemaVersion, op.ChunkCount, op.FocusStart, op.FocusEnd, op.ID) return err diff --git a/internal/server/operation_indexes_test.go b/internal/server/operation_indexes_test.go index 3945c7d2..4edc1300 100644 --- a/internal/server/operation_indexes_test.go +++ b/internal/server/operation_indexes_test.go @@ -17,7 +17,7 @@ func TestMigrationV16OperationsIndexes(t *testing.T) { repo, err := NewRepoOperation(path) require.NoError(t, err) _, err = repo.db.Exec(` - DELETE FROM version WHERE db = 16; + DELETE FROM version WHERE db >= 16; DROP INDEX idx_operations_date; DROP INDEX idx_operations_conversion_status_id; WITH RECURSIVE ids(id) AS ( @@ -44,7 +44,7 @@ func TestMigrationV16OperationsIndexes(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, repo.Close()) }) require.NoError(t, repo.db.QueryRow("SELECT MAX(db) FROM version").Scan(&count)) - require.Equal(t, 16, count) + require.Equal(t, 19, count) _, err = repo.db.Exec("ANALYZE") require.NoError(t, err) diff --git a/internal/server/operation_test.go b/internal/server/operation_test.go index 4ccbc605..128943e3 100644 --- a/internal/server/operation_test.go +++ b/internal/server/operation_test.go @@ -522,7 +522,7 @@ func TestMigrationRerun(t *testing.T) { var version int err = repo2.db.QueryRow("SELECT db FROM version ORDER BY db DESC LIMIT 1").Scan(&version) assert.NoError(t, err) - assert.Equal(t, 16, version) + assert.Equal(t, 19, version) } func TestMigrationV10NormalizeWorldName(t *testing.T) { @@ -630,7 +630,7 @@ func TestMigrationV11DecodeFilenames(t *testing.T) { // Version recorded. var version int require.NoError(t, repo2.db.QueryRow(`SELECT MAX(db) FROM version`).Scan(&version)) - assert.Equal(t, 16, version) + assert.Equal(t, 19, version) } func TestDecodeFilename(t *testing.T) { @@ -967,7 +967,7 @@ func TestMigrationV11_DBCollisionSkipped(t *testing.T) { // Version still bumped. var version int require.NoError(t, repo2.db.QueryRow(`SELECT MAX(db) FROM version`).Scan(&version)) - assert.Equal(t, 16, version) + assert.Equal(t, 19, version) } func TestMigrationV11_FilesystemCollisionSkipped(t *testing.T) { diff --git a/internal/server/players.go b/internal/server/players.go new file mode 100644 index 00000000..55c0e2c9 --- /dev/null +++ b/internal/server/players.go @@ -0,0 +1,388 @@ +package server + +import ( + "context" + "database/sql" + "errors" + "slices" + "strings" +) + +// CurrentPlayerIndexRevision is stored on each operation when its players were +// last indexed. Bump it when the indexed fields change so every completed +// recording is indexed again once. +const CurrentPlayerIndexRevision = 1 + +// OperationPlayer is one player's part in one recording. A player is +// identified by Steam UID when the recording has one and by in-game name +// otherwise (see PlayerKey): recordings from addons that sent no UID have +// none, and converted v1 protobuf without its JSON source keeps none. +type OperationPlayer struct { + UID string `json:"uid,omitempty"` + Name string `json:"name"` + // OtherNames are the other names the player used in the recording, as + // a player with a Steam UID can. + OtherNames []string `json:"otherNames,omitempty"` + Side string `json:"side"` + Role string `json:"role"` + Group string `json:"group"` + Kills int `json:"kills"` + VehicleKills int `json:"vehicleKills"` + TeamKills int `json:"teamKills"` + Deaths int `json:"deaths"` +} + +// PlayerSummary is one player in a search result. UID is empty for a player +// identified by name; Name is the one used in their latest recording. +type PlayerSummary struct { + UID string `json:"uid,omitempty"` + Name string `json:"name"` + Missions int `json:"missions"` + Kills int `json:"kills"` + Deaths int `json:"deaths"` + LastPlayed string `json:"lastPlayed"` +} + +// PlayerMission is one recording in a player's profile. +type PlayerMission struct { + OperationID int64 `json:"operationId"` + MissionName string `json:"missionName"` + WorldName string `json:"worldName"` + Date string `json:"date"` + Tag string `json:"tag"` + Filename string `json:"filename"` + MissionDuration float64 `json:"missionDuration"` + OperationPlayer +} + +// PlayerProfile is a player's record across every indexed recording, newest +// recording first. Name is the one used in the latest recording; a player +// identified by Steam UID may have played under other names, in Aliases. +type PlayerProfile struct { + UID string `json:"uid,omitempty"` + Name string `json:"name"` + Aliases []string `json:"aliases"` + Missions int `json:"missions"` + Kills int `json:"kills"` + VehicleKills int `json:"vehicleKills"` + TeamKills int `json:"teamKills"` + Deaths int `json:"deaths"` + FirstPlayed string `json:"firstPlayed"` + LastPlayed string `json:"lastPlayed"` + Sides map[string]int `json:"sides"` + Recordings []PlayerMission `json:"recordings"` +} + +// OperationsSummary describes every stored recording, for the recording list +// header and filters, which no longer see the whole list once it is paged. +type OperationsSummary struct { + Total int `json:"total"` + Worlds []string `json:"worlds"` + Tags []string `json:"tags"` + MaxPlayers int `json:"maxPlayers"` + TotalKills int `json:"totalKills"` +} + +// playerRecencyOrder orders a player's recordings, joined as o, newest first: +// by the instant of their date, then by id for recordings of the same date, +// as streamed recordings with a calendar date have. +const playerRecencyOrder = `julianday(o.date) DESC, o.id DESC` + +// NameKey is how player names are matched: in any case, ignoring surrounding +// whitespace. +func NameKey(name string) string { + return strings.ToLower(strings.TrimSpace(name)) +} + +// AddName records another name the player used in the recording, once in any +// case. A blank name is no name. +func (p *OperationPlayer) AddName(name string) { + key := NameKey(name) + if key == "" || key == NameKey(p.Name) || slices.ContainsFunc(p.OtherNames, func(other string) bool { return NameKey(other) == key }) { + return + } + p.OtherNames = append(p.OtherNames, strings.TrimSpace(name)) +} + +// deletePlayerIndex deletes the player index rows of the operations whose id +// matches the condition, such as "= ?". +func deletePlayerIndex(ctx context.Context, db execer, condition string, args ...any) error { + for _, table := range []string{"operation_players", "operation_player_names"} { + if _, err := db.ExecContext(ctx, `DELETE FROM `+table+` WHERE operation_id `+condition, args...); err != nil { + return err + } + } + return nil +} + +// PlayerKey is the identity a player is indexed and looked up under: the Steam +// UID when there is one, otherwise the name as NameKey matches it. It is empty +// when there is neither. The prefixes keep a name that happens to look like a +// UID from matching that player. +func PlayerKey(uid, name string) string { + if uid = strings.TrimSpace(uid); uid != "" { + return "uid:" + uid + } + if key := NameKey(name); key != "" { + return "name:" + key + } + return "" +} + +// ReplaceOperationPlayers replaces the player index rows of an operation and +// marks it indexed at CurrentPlayerIndexRevision. It returns ErrNotFound, and +// writes nothing, when the operation is gone: a job that read a recording +// before it was deleted or replaced, which gives the new one another id, must +// not leave its players searchable. +func (r *RepoOperation) ReplaceOperationPlayers(ctx context.Context, id int64, players []OperationPlayer) error { + tx, err := dbBegin(r.db) + if err != nil { + return err + } + defer tx.Rollback() + + // Marking first takes the write lock, so the operation cannot be deleted + // before this commits, and tells whether it is still there. + var live int64 + err = tx.QueryRowContext(ctx, + `UPDATE operations SET player_index_revision = ? WHERE id = ? RETURNING id`, CurrentPlayerIndexRevision, id, + ).Scan(&live) + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return err + } + if err := deletePlayerIndex(ctx, tx, `= ?`, id); err != nil { + return err + } + for _, p := range players { + key := PlayerKey(p.UID, p.Name) + if _, err := tx.ExecContext(ctx, ` + INSERT INTO operation_players + (operation_id, player_key, player_uid, name_key, name, side, role, group_name, + kills, vehicle_kills, team_kills, deaths) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + id, key, strings.TrimSpace(p.UID), NameKey(p.Name), p.Name, p.Side, p.Role, p.Group, + p.Kills, p.VehicleKills, p.TeamKills, p.Deaths); err != nil { + return err + } + for ordinal, name := range append([]string{p.Name}, p.OtherNames...) { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO operation_player_names (operation_id, player_key, ordinal, name_key, name) + VALUES (?, ?, ?, ?, ?)`, + id, key, ordinal, NameKey(name), name); err != nil { + return err + } + } + } + return tx.Commit() +} + +// SelectPlayerIndexBackfill returns completed operations whose players were +// never indexed, or were indexed by an older revision. +func (r *RepoOperation) SelectPlayerIndexBackfill(ctx context.Context) ([]Operation, error) { + rows, err := r.db.QueryContext(ctx, + `SELECT `+operationColumns+` + FROM operations + WHERE conversion_status = 'completed' AND player_index_revision < ? + ORDER BY id ASC`, CurrentPlayerIndexRevision) + if err != nil { + return nil, err + } + defer rows.Close() + + return r.scan(ctx, rows) +} + +// SearchPlayers returns up to limit players who used a name containing query +// in any recording, or whose Steam UID is query, most active first. An empty +// query lists the most active players. +func (r *RepoOperation) SearchPlayers(ctx context.Context, query string, limit int) ([]PlayerSummary, error) { + // The subquery picks the players, by any name they used in any recording, + // so every recording of a match counts, not only those under the name + // searched for, and none counts twice. Name and date are those of the + // player's latest recording in the order GetPlayerProfile lists them, by + // instant and then id, so the two agree when dates tie. + rows, err := r.db.QueryContext(ctx, ` + SELECT player_uid, name, missions, kills, deaths, date + FROM ( + SELECT p.player_key, p.player_uid, p.name, p.name_key, o.date, + ROW_NUMBER() OVER latest AS recency, + COUNT(*) OVER player AS missions, + SUM(p.kills) OVER player AS kills, + SUM(p.deaths) OVER player AS deaths + FROM operation_players p + JOIN operations o ON o.id = p.operation_id + WHERE p.player_key IN ( + SELECT player_key FROM operation_player_names WHERE name_key LIKE '%' || ? || '%' ESCAPE '\' + UNION + SELECT player_key FROM operation_players WHERE player_uid = ?) + WINDOW player AS (PARTITION BY p.player_key), + latest AS (PARTITION BY p.player_key ORDER BY `+playerRecencyOrder+`) + ) + WHERE recency = 1 + ORDER BY missions DESC, name_key ASC, player_key ASC + LIMIT ?`, escapeLike(NameKey(query)), strings.TrimSpace(query), limit) + if err != nil { + return nil, err + } + defer rows.Close() + + players := []PlayerSummary{} + for rows.Next() { + var p PlayerSummary + if err := rows.Scan(&p.UID, &p.Name, &p.Missions, &p.Kills, &p.Deaths, &p.LastPlayed); err != nil { + return nil, err + } + players = append(players, p) + } + return players, rows.Err() +} + +// GetPlayerProfile returns the profile of the player with this Steam UID or, +// without one, of the player recorded without a UID under this name, matched +// in any case. It returns ErrNotFound when no indexed recording has them. +func (r *RepoOperation) GetPlayerProfile(ctx context.Context, uid, name string) (*PlayerProfile, error) { + key := PlayerKey(uid, name) + rows, err := r.db.QueryContext(ctx, ` + SELECT o.id, o.mission_name, o.world_name, o.date, o.tag, o.filename, o.mission_duration, + p.player_uid, p.name, p.side, p.role, p.group_name, p.kills, p.vehicle_kills, p.team_kills, p.deaths + FROM operation_players p + JOIN operations o ON o.id = p.operation_id + WHERE p.player_key = ? + ORDER BY `+playerRecencyOrder, key) + if err != nil { + return nil, err + } + defer rows.Close() + + profile := &PlayerProfile{Aliases: []string{}, Sides: map[string]int{}, Recordings: []PlayerMission{}} + for rows.Next() { + var m PlayerMission + if err := rows.Scan(&m.OperationID, &m.MissionName, &m.WorldName, &m.Date, &m.Tag, &m.Filename, &m.MissionDuration, + &m.UID, &m.Name, &m.Side, &m.Role, &m.Group, &m.Kills, &m.VehicleKills, &m.TeamKills, &m.Deaths); err != nil { + return nil, err + } + profile.add(m) + } + err = rows.Err() + if err == nil && profile.Missions == 0 { + err = ErrNotFound + } + if err == nil { + err = r.addPlayerNames(ctx, key, profile) + } + if err != nil { + return nil, err + } + return profile, nil +} + +// addPlayerNames adds the names the player used besides each recording's +// first: to that recording, and across recordings, newest first, as aliases. +func (r *RepoOperation) addPlayerNames(ctx context.Context, key string, profile *PlayerProfile) error { + rows, err := r.db.QueryContext(ctx, ` + SELECT n.operation_id, n.ordinal, n.name + FROM operation_player_names n + JOIN operations o ON o.id = n.operation_id + WHERE n.player_key = ? + ORDER BY `+playerRecencyOrder+`, n.ordinal`, key) + if err != nil { + return err + } + defer rows.Close() + + recordings := make(map[int64]*PlayerMission, len(profile.Recordings)) + for i := range profile.Recordings { + recordings[profile.Recordings[i].OperationID] = &profile.Recordings[i] + } + for rows.Next() { + var id int64 + var ordinal int + var name string + if err := rows.Scan(&id, &ordinal, &name); err != nil { + return err + } + if m := recordings[id]; m != nil && ordinal > 0 { + m.OtherNames = append(m.OtherNames, name) + } + if !profile.usedName(name) { + profile.Aliases = append(profile.Aliases, name) + } + } + return rows.Err() +} + +// add folds one recording, newer ones first, into the profile. +func (p *PlayerProfile) add(m PlayerMission) { + if p.Missions == 0 { + p.UID = m.UID + p.Name = m.Name + p.LastPlayed = m.Date + } + p.FirstPlayed = m.Date + p.Missions++ + p.Kills += m.Kills + p.VehicleKills += m.VehicleKills + p.TeamKills += m.TeamKills + p.Deaths += m.Deaths + if m.Side != "" { + p.Sides[m.Side]++ + } + p.Recordings = append(p.Recordings, m) +} + +// usedName reports whether the profile already lists this name, as its name or +// an alias, in any case. +func (p *PlayerProfile) usedName(name string) bool { + key := NameKey(name) + if NameKey(p.Name) == key { + return true + } + for _, alias := range p.Aliases { + if NameKey(alias) == key { + return true + } + } + return false +} + +// Summary describes every stored recording. +func (r *RepoOperation) Summary(ctx context.Context) (*OperationsSummary, error) { + s := &OperationsSummary{} + if err := r.db.QueryRowContext(ctx, + `SELECT COUNT(*), COALESCE(MAX(player_count), 0), COALESCE(SUM(kill_count), 0) FROM operations`, + ).Scan(&s.Total, &s.MaxPlayers, &s.TotalKills); err != nil { + return nil, err + } + var err error + if s.Worlds, err = r.distinct(ctx, "world_name"); err != nil { + return nil, err + } + if s.Tags, err = r.distinct(ctx, "tag"); err != nil { + return nil, err + } + return s, nil +} + +// distinct returns the distinct non-empty values of an operations column, sorted. +func (r *RepoOperation) distinct(ctx context.Context, column string) ([]string, error) { + rows, err := r.db.QueryContext(ctx, `SELECT DISTINCT `+column+` FROM operations ORDER BY `+column) + if err != nil { + return nil, err + } + defer rows.Close() + + values := []string{} + for rows.Next() { + var v string + if err := rows.Scan(&v); err != nil { + return nil, err + } + if v != "" { + values = append(values, v) + } + } + return values, rows.Err() +} diff --git a/internal/server/players_test.go b/internal/server/players_test.go new file mode 100644 index 00000000..40391e4a --- /dev/null +++ b/internal/server/players_test.go @@ -0,0 +1,885 @@ +package server + +import ( + "database/sql" + "encoding/base64" + "errors" + "fmt" + "path/filepath" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// newPlayersRepo opens an empty repository in a temporary directory. +func newPlayersRepo(t *testing.T) *RepoOperation { + t.Helper() + repo, err := NewRepoOperation(filepath.Join(t.TempDir(), "players.db")) + require.NoError(t, err) + t.Cleanup(func() { _ = repo.Close() }) + return repo +} + +// storePlayerOp stores a completed synthetic recording and returns its id. +func storePlayerOp(t *testing.T, repo *RepoOperation, filename, mission, world, date string) int64 { + t.Helper() + op := &Operation{ + WorldName: world, MissionName: mission, MissionDuration: 600, Filename: filename, + Date: date, Tag: "coop", StorageFormat: "protobuf", ConversionStatus: ConversionStatusCompleted, + } + require.NoError(t, repo.Store(t.Context(), op)) + return op.ID +} + +// mustExec runs SQL that sets up a test condition. +func mustExec(t *testing.T, db *sql.DB, query string) { + t.Helper() + _, err := db.Exec(query) + require.NoError(t, err) +} + +func TestPlayerKeys(t *testing.T) { + assert.Equal(t, "nosey", NameKey(" NoSey\t")) + assert.Equal(t, "", NameKey(" ")) + + assert.Equal(t, "uid:76561190000000001", PlayerKey(" 76561190000000001 ", "Nosey"), "the Steam UID wins over the name") + assert.Equal(t, "name:nosey", PlayerKey(" ", " NoSey "), "without a UID the name identifies the player") + assert.Equal(t, "", PlayerKey("", " ")) + assert.NotEqual(t, PlayerKey("76561190000000001", ""), PlayerKey("", "76561190000000001"), + "a name that looks like a UID is not that player") +} + +func TestPlayerIndexSearchAndProfile(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + + first := storePlayerOp(t, repo, "first", "Op First", "altis", "2026-01-01") + second := storePlayerOp(t, repo, "second", "Op Second", "stratis", "2026-02-01") + third := storePlayerOp(t, repo, "third", "Op Third", "altis", "2026-03-01") + + require.NoError(t, repo.ReplaceOperationPlayers(ctx, first, []OperationPlayer{ + {Name: "nosey", Side: "WEST", Role: "Rifleman", Group: "Alpha 1-1", Kills: 2, Deaths: 1}, + {Name: "Under_Score", Side: "EAST", Kills: 1}, + })) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, second, []OperationPlayer{ + {Name: "Nosey", Side: "WEST", Kills: 3, VehicleKills: 1, TeamKills: 1, Deaths: 2}, + {Name: "UnderXScore", Side: "EAST"}, + })) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, third, []OperationPlayer{ + {Name: "NOSEY", Side: "", Role: "Zeus"}, + })) + + t.Run("empty query lists the most active players", func(t *testing.T) { + players, err := repo.SearchPlayers(ctx, "", 10) + require.NoError(t, err) + require.Len(t, players, 3) + assert.Equal(t, PlayerSummary{Name: "NOSEY", Missions: 3, Kills: 5, Deaths: 3, LastPlayed: "2026-03-01"}, players[0], + "the name is spelled as in the latest recording") + assert.Equal(t, "Under_Score", players[1].Name, "equal activity falls back to name order") + assert.Equal(t, "UnderXScore", players[2].Name) + }) + + t.Run("query matches any case and LIKE wildcards literally", func(t *testing.T) { + players, err := repo.SearchPlayers(ctx, "r_s", 10) + require.NoError(t, err) + require.Len(t, players, 1) + assert.Equal(t, "Under_Score", players[0].Name) + + players, err = repo.SearchPlayers(ctx, " OSE ", 10) + require.NoError(t, err) + require.Len(t, players, 1) + assert.Equal(t, 3, players[0].Missions) + }) + + t.Run("limit caps the result", func(t *testing.T) { + players, err := repo.SearchPlayers(ctx, "", 1) + require.NoError(t, err) + assert.Len(t, players, 1) + }) + + t.Run("profile aggregates every recording newest first", func(t *testing.T) { + profile, err := repo.GetPlayerProfile(ctx, "", " nOsEy ") + require.NoError(t, err) + assert.Equal(t, "NOSEY", profile.Name) + assert.Empty(t, profile.UID) + assert.Equal(t, []string{}, profile.Aliases, "the same name in another case is no alias") + assert.Equal(t, 3, profile.Missions) + assert.Equal(t, 5, profile.Kills) + assert.Equal(t, 1, profile.VehicleKills) + assert.Equal(t, 1, profile.TeamKills) + assert.Equal(t, 3, profile.Deaths) + assert.Equal(t, "2026-01-01", profile.FirstPlayed) + assert.Equal(t, "2026-03-01", profile.LastPlayed) + assert.Equal(t, map[string]int{"WEST": 2}, profile.Sides, "a recording without a side is not counted") + require.Len(t, profile.Recordings, 3) + assert.Equal(t, third, profile.Recordings[0].OperationID) + assert.Equal(t, "Op First", profile.Recordings[2].MissionName) + assert.Equal(t, "altis", profile.Recordings[2].WorldName) + assert.Equal(t, "first", profile.Recordings[2].Filename) + assert.Equal(t, "coop", profile.Recordings[2].Tag) + assert.InDelta(t, 600, profile.Recordings[2].MissionDuration, 0) + assert.Equal(t, "Rifleman", profile.Recordings[2].Role) + assert.Equal(t, "Alpha 1-1", profile.Recordings[2].Group) + }) + + t.Run("unknown player is not found", func(t *testing.T) { + _, err := repo.GetPlayerProfile(ctx, "", "nobody") + assert.ErrorIs(t, err, ErrNotFound) + }) + + t.Run("replacing drops the old rows", func(t *testing.T) { + require.NoError(t, repo.ReplaceOperationPlayers(ctx, third, nil)) + profile, err := repo.GetPlayerProfile(ctx, "", "nosey") + require.NoError(t, err) + assert.Equal(t, 2, profile.Missions) + }) + + t.Run("recording filter finds a player's recordings", func(t *testing.T) { + ops, err := repo.Select(ctx, Filter{Player: "NOSEY"}) + require.NoError(t, err) + require.Len(t, ops, 2) + assert.Equal(t, first, ops[0].ID) + assert.Equal(t, second, ops[1].ID) + }) + + t.Run("deleting a recording drops its players", func(t *testing.T) { + require.NoError(t, repo.Delete(ctx, first)) + var n int + require.NoError(t, repo.db.QueryRow(`SELECT COUNT(*) FROM operation_players WHERE operation_id = ?`, first).Scan(&n)) + assert.Zero(t, n) + }) + + t.Run("replacing a recording by filename drops its players", func(t *testing.T) { + replacement := &Operation{WorldName: "stratis", MissionName: "Op Second again", Filename: "second", Date: "2026-02-02"} + require.NoError(t, repo.StoreReplacingByFilename(ctx, replacement)) + var n int + require.NoError(t, repo.db.QueryRow(`SELECT COUNT(*) FROM operation_players WHERE operation_id = ?`, second).Scan(&n)) + assert.Zero(t, n) + }) +} + +// A player with a Steam UID is one player under every name they used; a player +// recorded without one is their name, apart from any UID player of that name. +func TestPlayerIndexBySteamUID(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + const nosey, raven = "76561190000000001", "76561190000000002" + + first := storePlayerOp(t, repo, "first", "Op First", "altis", "2026-01-01") + second := storePlayerOp(t, repo, "second", "Op Second", "stratis", "2026-02-01") + third := storePlayerOp(t, repo, "third", "Op Third", "altis", "2026-03-01") + require.NoError(t, repo.ReplaceOperationPlayers(ctx, first, []OperationPlayer{ + {UID: nosey, Name: "Nosey", Side: "WEST", Kills: 1}, + {Name: "Nosey", Side: "EAST", Kills: 5}, + {UID: " " + raven + " ", Name: "Raven", Side: "EAST"}, + })) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, second, []OperationPlayer{ + {UID: nosey, Name: "Ghost", Side: "WEST", Kills: 2, Deaths: 1}, + {UID: raven, Name: "Raven", Side: "EAST"}, + })) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, third, []OperationPlayer{ + {UID: nosey, Name: "N0sey", Side: "WEST"}, + {UID: raven, Name: "RAVEN", Side: "EAST"}, + })) + + t.Run("search by any name used counts every recording", func(t *testing.T) { + players, err := repo.SearchPlayers(ctx, "nosey", 10) + require.NoError(t, err) + require.Len(t, players, 2) + assert.Equal(t, PlayerSummary{UID: nosey, Name: "N0sey", Missions: 3, Kills: 3, Deaths: 1, LastPlayed: "2026-03-01"}, players[0], + "the UID player is listed under their latest name") + assert.Equal(t, PlayerSummary{Name: "Nosey", Missions: 1, Kills: 5, LastPlayed: "2026-01-01"}, players[1], + "the player recorded without a UID stays apart") + + players, err = repo.SearchPlayers(ctx, "GHOST", 10) + require.NoError(t, err) + require.Len(t, players, 1) + assert.Equal(t, nosey, players[0].UID) + assert.Equal(t, 3, players[0].Missions) + }) + + t.Run("search by the exact Steam UID", func(t *testing.T) { + players, err := repo.SearchPlayers(ctx, " "+raven+" ", 10) + require.NoError(t, err) + require.Len(t, players, 1) + assert.Equal(t, PlayerSummary{UID: raven, Name: "RAVEN", Missions: 3, LastPlayed: "2026-03-01"}, players[0]) + + players, err = repo.SearchPlayers(ctx, "7656119", 10) + require.NoError(t, err) + assert.Empty(t, players, "part of a UID matches nothing") + }) + + t.Run("profile by Steam UID lists the other names newest first", func(t *testing.T) { + profile, err := repo.GetPlayerProfile(ctx, nosey, "ignored with a uid") + require.NoError(t, err) + assert.Equal(t, nosey, profile.UID) + assert.Equal(t, "N0sey", profile.Name) + assert.Equal(t, []string{"Ghost", "Nosey"}, profile.Aliases) + assert.Equal(t, 3, profile.Missions) + assert.Equal(t, map[string]int{"WEST": 3}, profile.Sides) + require.Len(t, profile.Recordings, 3) + assert.Equal(t, third, profile.Recordings[0].OperationID) + assert.Equal(t, "Nosey", profile.Recordings[2].Name, "each recording keeps the name used in it") + + profile, err = repo.GetPlayerProfile(ctx, raven, "") + require.NoError(t, err) + assert.Equal(t, "RAVEN", profile.Name) + assert.Equal(t, []string{}, profile.Aliases, "a name in another case is no alias") + }) + + t.Run("profile by name finds only the player without a UID", func(t *testing.T) { + profile, err := repo.GetPlayerProfile(ctx, "", "NOSEY") + require.NoError(t, err) + assert.Empty(t, profile.UID) + assert.Equal(t, 1, profile.Missions) + assert.Equal(t, 5, profile.Kills) + + _, err = repo.GetPlayerProfile(ctx, "", "N0sey") + assert.ErrorIs(t, err, ErrNotFound, "a UID player is not found by name") + }) + + t.Run("recording filters by UID and by name", func(t *testing.T) { + ids := func(f Filter) []int64 { + t.Helper() + ops, err := repo.Select(ctx, f) + require.NoError(t, err) + out := []int64{} + for _, op := range ops { + out = append(out, op.ID) + } + return out + } + assert.Equal(t, []int64{first, second, third}, ids(Filter{PlayerUID: nosey})) + assert.Equal(t, []int64{first}, ids(Filter{Player: "nosey"}), "a name filter matches every player of that name") + assert.Equal(t, []int64{second}, ids(Filter{Player: "ghost", PlayerUID: nosey})) + assert.Empty(t, ids(Filter{PlayerUID: "76561190000000009"})) + }) +} + +// A player with a Steam UID can use several names in one recording. Each is +// searchable and listed, and the recording still counts once. +func TestPlayerIndexKeepsEveryNameOfARecording(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + const uid = "76561190000000001" + first := storePlayerOp(t, repo, "first", "Op First", "altis", "2026-01-01") + second := storePlayerOp(t, repo, "second", "Op Second", "altis", "2026-02-01") + require.NoError(t, repo.ReplaceOperationPlayers(ctx, first, []OperationPlayer{ + {UID: uid, Name: "Nosey", OtherNames: []string{"Raven", "GHOST", "raven"}, Kills: 2}, + })) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, second, []OperationPlayer{{UID: uid, Name: "Ghost", Kills: 1}})) + + players, err := repo.SearchPlayers(ctx, "raven", 10) + require.NoError(t, err) + require.Len(t, players, 1) + assert.Equal(t, PlayerSummary{UID: uid, Name: "Ghost", Missions: 2, Kills: 3, LastPlayed: "2026-02-01"}, players[0], + "a second name finds the player, and no recording counts twice") + + profile, err := repo.GetPlayerProfile(ctx, uid, "") + require.NoError(t, err) + assert.Equal(t, "Ghost", profile.Name) + assert.Equal(t, []string{"Nosey", "Raven"}, profile.Aliases, "each other name once, in any case, newest first") + assert.Empty(t, profile.Recordings[0].OtherNames) + assert.Equal(t, []string{"Raven", "GHOST", "raven"}, profile.Recordings[1].OtherNames) + + ops, err := repo.Select(ctx, Filter{Player: "RAVEN"}) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, first, ops[0].ID) +} + +// Recordings of the same date, as streamed ones with a calendar date are, are +// ordered by id: search and the profile both name the player as in the later. +func TestPlayerSearchAndProfileAgreeOnSameDayRecordings(t *testing.T) { + // Indexed in either order, so the order rows are stored in cannot decide. + for name, olderFirst := range map[string]bool{"older indexed first": true, "newer indexed first": false} { + t.Run(name, func(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + const uid = "76561190000000001" + older := storePlayerOp(t, repo, "older", "Older", "altis", "2026-03-01") + newer := storePlayerOp(t, repo, "newer", "Newer", "altis", "2026-03-01") + index := []func(){ + func() { + require.NoError(t, repo.ReplaceOperationPlayers(ctx, older, []OperationPlayer{{UID: uid, Name: "Old"}})) + }, + func() { + require.NoError(t, repo.ReplaceOperationPlayers(ctx, newer, []OperationPlayer{{UID: uid, Name: "New"}})) + }, + } + if !olderFirst { + index[0], index[1] = index[1], index[0] + } + index[0]() + index[1]() + + found, err := repo.SearchPlayers(ctx, "", 10) + require.NoError(t, err) + require.Len(t, found, 1) + profile, err := repo.GetPlayerProfile(ctx, uid, "") + require.NoError(t, err) + assert.Equal(t, "New", found[0].Name) + assert.Equal(t, profile.Name, found[0].Name) + assert.Equal(t, profile.LastPlayed, found[0].LastPlayed) + assert.Equal(t, []string{"Old"}, profile.Aliases) + }) + } +} + +// A job that read a recording before it was deleted or replaced finishes +// after: its players must not become searchable under a recording that is +// gone, and the replacement keeps only its own. +func TestStalePlayerIndexJobWritesNothing(t *testing.T) { + ctx := t.Context() + stale := []OperationPlayer{{UID: "76561190000000001", Name: "Nosey", OtherNames: []string{"Raven"}}} + + t.Run("after deletion", func(t *testing.T) { + repo := newPlayersRepo(t) + survivor := storePlayerOp(t, repo, "survivor", "Survivor", "altis", "2026-01-01") + require.NoError(t, repo.ReplaceOperationPlayers(ctx, survivor, []OperationPlayer{{UID: "76561190000000001", Name: "Nosey"}})) + deleted := storePlayerOp(t, repo, "deleted", "Deleted", "altis", "2026-01-02") + require.NoError(t, repo.Delete(ctx, deleted)) + + assert.ErrorIs(t, repo.ReplaceOperationPlayers(ctx, deleted, stale), ErrNotFound) + found, err := repo.SearchPlayers(ctx, "raven", 10) + require.NoError(t, err) + assert.Empty(t, found, "a name from the deleted recording finds no one") + var n int + require.NoError(t, repo.db.QueryRow(`SELECT COUNT(*) FROM operation_player_names WHERE operation_id = ?`, deleted).Scan(&n)) + assert.Zero(t, n) + }) + + t.Run("after replacement", func(t *testing.T) { + repo := newPlayersRepo(t) + old := storePlayerOp(t, repo, "replaced", "Replaced", "altis", "2026-01-01") + replacement := &Operation{WorldName: "altis", MissionName: "Replacement", Filename: "replaced", Date: "2026-01-02"} + require.NoError(t, repo.StoreReplacingByFilename(ctx, replacement)) + require.NotEqual(t, old, replacement.ID) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, replacement.ID, []OperationPlayer{{UID: "76561190000000002", Name: "Ghost"}})) + + assert.ErrorIs(t, repo.ReplaceOperationPlayers(ctx, old, stale), ErrNotFound) + found, err := repo.SearchPlayers(ctx, "", 10) + require.NoError(t, err) + require.Len(t, found, 1) + assert.Equal(t, "Ghost", found[0].Name, "only the replacement's players are indexed") + }) +} + +// The recording search matches in any case in every script, as the list did +// when it filtered in the browser, before counting and paging. +func TestRecordingSearchFoldsEveryScript(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + storePlayerOp(t, repo, "evac", "Évacuation de Kavala", "altis", "2026-01-01") + storePlayerOp(t, repo, "op", "ОПЕРАЦИЯ Гроза", "chernarus", "2026-01-02") + storePlayerOp(t, repo, "plain", "Plain", "stratis", "2026-01-03") + for query, want := range map[string]string{ + "évac": "evac", + "ÉVACUATION": "evac", + "операция": "op", + "гроза": "op", + "CHERNARUS": "op", + "100%": "", + "_": "", + } { + filter := Filter{Query: query, Limit: 10} + ops, err := repo.Select(ctx, filter) + require.NoError(t, err) + count, err := repo.Count(ctx, filter) + require.NoError(t, err) + if want == "" { + assert.Empty(t, ops, query) + assert.Zero(t, count, query) + continue + } + require.Len(t, ops, 1, query) + assert.Equal(t, want, ops[0].Filename, query) + assert.Equal(t, 1, count, query) + } +} + +// pageThrough reads every page of filter, Limit at a time, by cursor, calling +// between before each page after the first. +func pageThrough(t *testing.T, repo *RepoOperation, filter Filter, between func(page int)) []string { + t.Helper() + var names []string + for page := 0; ; page++ { + if page > 0 && between != nil { + between(page) + } + ops, err := repo.Select(t.Context(), filter) + require.NoError(t, err) + for _, op := range ops { + names = append(names, op.Filename) + } + if filter.After = filter.NextCursor(ops); filter.After == "" { + return names + } + require.Less(t, page, 50, "paging ends") + } +} + +// Pages continue behind the last recording of the one before, by its place in +// the order, not by a count: a recording added or deleted between two pages +// neither repeats one nor skips one. +func TestRecordingPagesSurviveChangesBetweenThem(t *testing.T) { + ctx := t.Context() + store := func(t *testing.T, repo *RepoOperation, filename, date string) int64 { + t.Helper() + op := &Operation{WorldName: "altis", MissionName: filename, Filename: filename, Date: date} + require.NoError(t, repo.Store(ctx, op)) + return op.ID + } + seed := func(t *testing.T) (*RepoOperation, map[string]int64) { + repo := newPlayersRepo(t) + ids := map[string]int64{} + for i, name := range []string{"r1", "r2", "r3", "r4"} { + ids[name] = store(t, repo, name, fmt.Sprintf("2026-01-0%d", i+1)) + } + return repo, ids + } + newestFirst := Filter{Sort: "date", Dir: "desc", Limit: 2} + + t.Run("an insertion before the cursor repeats nothing", func(t *testing.T) { + repo, _ := seed(t) + got := pageThrough(t, repo, newestFirst, func(page int) { + store(t, repo, fmt.Sprintf("new%d", page), "2026-01-05") + }) + assert.Equal(t, []string{"r4", "r3", "r2", "r1"}, got) + }) + + t.Run("a deletion before the cursor skips nothing", func(t *testing.T) { + repo, ids := seed(t) + got := pageThrough(t, repo, newestFirst, func(page int) { + if page == 1 { + require.NoError(t, repo.Delete(ctx, ids["r4"])) + } + }) + assert.Equal(t, []string{"r4", "r3", "r2", "r1"}, got) + }) + + t.Run("the recording the cursor names may be gone", func(t *testing.T) { + repo, ids := seed(t) + got := pageThrough(t, repo, newestFirst, func(page int) { + if page == 1 { + require.NoError(t, repo.Delete(ctx, ids["r3"])) + } + }) + assert.Equal(t, []string{"r4", "r3", "r2", "r1"}, got) + }) +} + +// Every order pages through to exactly the unpaged list, ties and all: equal +// names in another case, equal durations, equal dates and a date julianday +// cannot read. +func TestRecordingPagesMatchTheUnpagedListInEveryOrder(t *testing.T) { + repo := newPlayersRepo(t) + for i, op := range []*Operation{ + {MissionName: "alpha", MissionDuration: 60, Date: "2026-01-02"}, + {MissionName: "Alpha", MissionDuration: 30, Date: "2026-01-02"}, + {MissionName: "BETA", MissionDuration: 60, Date: "2026-01-01T23:00:00-02:00"}, + {MissionName: "beta", MissionDuration: 90.5, Date: "2026-13-01"}, + {MissionName: "Évac", MissionDuration: 30, Date: "2026-01-03"}, + {MissionName: "gamma", MissionDuration: 0, Date: "2026-99-99"}, + } { + op.WorldName, op.Filename = "altis", fmt.Sprintf("op%d", i+1) + require.NoError(t, repo.Store(t.Context(), op)) + } + for _, sort := range []string{"", "date", "name", "duration"} { + for _, dir := range []string{"asc", "desc"} { + filter := Filter{Sort: sort, Dir: dir} + ops, err := repo.Select(t.Context(), filter) + require.NoError(t, err) + var want []string + for _, op := range ops { + want = append(want, op.Filename) + } + require.Len(t, want, 6) + for _, limit := range []int{1, 2, 4} { + filter.Limit = limit + assert.Equal(t, want, pageThrough(t, repo, filter, nil), "sort %q %s by %d", sort, dir, limit) + } + } + } +} + +func TestPageCursors(t *testing.T) { + ops := []Operation{{ID: 7, Date: "2026-01-01", MissionName: "Op", MissionDuration: 1.5}} + assert.Empty(t, Filter{}.NextCursor(ops), "an unpaged list has no next page") + assert.Empty(t, Filter{Limit: 2}.NextCursor(ops), "nor does a page short of its limit") + + for sort, value := range map[string]any{"": nil, "date": "2026-01-01", "name": "Op", "duration": 1.5} { + cursor, err := decodeCursor(Filter{Sort: sort, Limit: 1}.NextCursor(ops)) + require.NoError(t, err) + assert.Equal(t, pageCursor{Value: value, ID: 7}, cursor, sort) + } + + for _, bad := range []string{"%%%", base64.RawURLEncoding.EncodeToString([]byte("not json"))} { + _, err := decodeCursor(bad) + assert.ErrorIs(t, err, ErrInvalidCursor) + _, err = newPlayersRepo(t).Select(t.Context(), Filter{After: bad}) + assert.ErrorIs(t, err, ErrInvalidCursor) + } +} + +func TestOperationPlayerAddName(t *testing.T) { + p := OperationPlayer{Name: "Nosey"} + for _, name := range []string{"nosey", " Raven ", "RAVEN", " ", "Ghost"} { + p.AddName(name) + } + assert.Equal(t, []string{"Raven", "Ghost"}, p.OtherNames) +} + +// Recordings sort by the instant their date names. An RFC3339 date sorts by +// its time and offset, not as text, and a plain date counts as midnight UTC. +func TestRecordingsSortByInstant(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + for _, op := range []*Operation{ + {WorldName: "altis", MissionName: "Late on the first", Filename: "late", Date: "2026-01-01T23:30:00Z"}, + {WorldName: "altis", MissionName: "Early on the second", Filename: "early", Date: "2026-01-02T00:30:00+02:00"}, + {WorldName: "altis", MissionName: "Second", Filename: "second", Date: "2026-01-02"}, + } { + require.NoError(t, repo.Store(ctx, op)) + } + page := func(f Filter) []string { + t.Helper() + ops, err := repo.Select(ctx, f) + require.NoError(t, err) + var names []string + for _, op := range ops { + names = append(names, op.Filename) + } + return names + } + assert.Equal(t, []string{"second", "late", "early"}, page(Filter{Sort: "date", Dir: "desc"})) + assert.Equal(t, []string{"late"}, page(Filter{Sort: "date", Dir: "desc", Limit: 1, Offset: 1}), + "23:30Z on the first is newer than 00:30+02:00 on the second") + assert.Equal(t, []string{"early", "late", "second"}, page(Filter{Sort: "date", Dir: "asc"})) + + ids := map[string]int64{} + ops, err := repo.Select(ctx, Filter{}) + require.NoError(t, err) + for _, op := range ops { + ids[op.Filename] = op.ID + } + for _, filename := range []string{"late", "early"} { + require.NoError(t, repo.ReplaceOperationPlayers(ctx, ids[filename], []OperationPlayer{{UID: "76561190000000001", Name: filename}})) + } + profile, err := repo.GetPlayerProfile(ctx, "76561190000000001", "") + require.NoError(t, err) + assert.Equal(t, "late", profile.Name, "the profile is named as in the latest recording by time") + assert.Equal(t, "2026-01-02T00:30:00+02:00", profile.FirstPlayed) + found, err := repo.SearchPlayers(ctx, "", 10) + require.NoError(t, err) + assert.Equal(t, "late", found[0].Name) + assert.Equal(t, "2026-01-01T23:30:00Z", found[0].LastPlayed) +} + +// A world name saved in mixed case is lowercased, so the world the summary +// offers selects its recordings. +func TestWorldNamesAreStoredLowercase(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + op := &Operation{WorldName: "altis", MissionName: "Streamed", Filename: "streamed", Date: "2026-01-01"} + require.NoError(t, repo.Store(ctx, op)) + op.WorldName = "Altis" + require.NoError(t, repo.Update(ctx, op)) + + summary, err := repo.Summary(ctx) + require.NoError(t, err) + assert.Equal(t, []string{"altis"}, summary.Worlds) + ops, err := repo.Select(ctx, Filter{Worlds: []string{"Altis"}}) + require.NoError(t, err) + assert.Len(t, ops, 1) +} + +func TestMigrationV18LowercasesWorldNames(t *testing.T) { + path := filepath.Join(t.TempDir(), "operations.db") + repo, err := NewRepoOperation(path) + require.NoError(t, err) + mustExec(t, repo.db, `INSERT INTO operations (world_name, mission_name, mission_duration, filename, date, tag) + VALUES ('Stratis', 'Saved mixed case', 0, 'mixed', '2026-01-01', '')`) + mustExec(t, repo.db, `DELETE FROM version WHERE db >= 18`) + require.NoError(t, repo.Close()) + + repo, err = NewRepoOperation(path) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, repo.Close()) }) + ops, err := repo.Select(t.Context(), Filter{Worlds: []string{"stratis"}}) + require.NoError(t, err) + require.Len(t, ops, 1) + assert.Equal(t, "stratis", ops[0].WorldName) +} + +func TestTagExactMatchesOneTag(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + for _, tag := range []string{"COOP", "COOP-training", "coop"} { + require.NoError(t, repo.Store(ctx, &Operation{WorldName: "altis", MissionName: tag, Filename: tag, Date: "2026-01-01", Tag: tag})) + } + tags := func(f Filter) []string { + t.Helper() + ops, err := repo.Select(ctx, f) + require.NoError(t, err) + var out []string + for _, op := range ops { + out = append(out, op.Tag) + } + return out + } + assert.Equal(t, []string{"COOP"}, tags(Filter{TagExact: "COOP"})) + assert.Equal(t, []string{"COOP", "COOP-training", "coop"}, tags(Filter{Tag: "COOP"}), "tag keeps its contains semantics") +} + +func TestSelectPlayerIndexBackfill(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + + indexed := storePlayerOp(t, repo, "indexed", "Indexed", "altis", "2026-01-01") + unindexed := storePlayerOp(t, repo, "unindexed", "Unindexed", "altis", "2026-01-02") + stale := storePlayerOp(t, repo, "stale", "Stale", "altis", "2026-01-03") + converting := &Operation{WorldName: "altis", MissionName: "Converting", Filename: "converting", Date: "2026-01-04", ConversionStatus: ConversionStatusConverting} + require.NoError(t, repo.Store(ctx, converting)) + + require.NoError(t, repo.ReplaceOperationPlayers(ctx, indexed, nil)) + require.NoError(t, repo.ReplaceOperationPlayers(ctx, stale, nil)) + mustExec(t, repo.db, `UPDATE operations SET player_index_revision = 0 WHERE filename = 'stale'`) + + ops, err := repo.SelectPlayerIndexBackfill(ctx) + require.NoError(t, err) + require.Len(t, ops, 2) + assert.Equal(t, unindexed, ops[0].ID) + assert.Equal(t, stale, ops[1].ID) + + require.NoError(t, repo.Close()) + _, err = repo.SelectPlayerIndexBackfill(ctx) + assert.Error(t, err) +} + +func TestReplaceOperationPlayersErrors(t *testing.T) { + players := []OperationPlayer{{Name: "Nosey"}} + + t.Run("begin", func(t *testing.T) { + repo := newPlayersRepo(t) + orig := dbBegin + t.Cleanup(func() { dbBegin = orig }) + dbBegin = func(*sql.DB) (*sql.Tx, error) { return nil, errors.New("begin failed") } + assert.ErrorContains(t, repo.ReplaceOperationPlayers(t.Context(), 1, players), "begin failed") + }) + + for name, trigger := range map[string]string{ + "delete": `CREATE TRIGGER fail BEFORE DELETE ON operation_players BEGIN SELECT RAISE(ABORT, 'delete failed'); END`, + "insert": `CREATE TRIGGER fail BEFORE INSERT ON operation_players BEGIN SELECT RAISE(ABORT, 'insert failed'); END`, + "names delete": `CREATE TRIGGER fail BEFORE DELETE ON operation_player_names BEGIN SELECT RAISE(ABORT, 'names delete failed'); END`, + "names insert": `CREATE TRIGGER fail BEFORE INSERT ON operation_player_names BEGIN SELECT RAISE(ABORT, 'names insert failed'); END`, + "update": `CREATE TRIGGER fail BEFORE UPDATE ON operations BEGIN SELECT RAISE(ABORT, 'update failed'); END`, + } { + t.Run(name, func(t *testing.T) { + repo := newPlayersRepo(t) + id := storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + // The deletes only fire on existing rows. + mustExec(t, repo.db, `INSERT INTO operation_players (operation_id, player_key, name_key, name) VALUES (1, 'name:old', 'old', 'Old')`) + mustExec(t, repo.db, `INSERT INTO operation_player_names VALUES (1, 'name:old', 0, 'old', 'Old')`) + mustExec(t, repo.db, trigger) + assert.ErrorContains(t, repo.ReplaceOperationPlayers(t.Context(), id, players), name+" failed") + + var n int + require.NoError(t, repo.db.QueryRow(`SELECT COUNT(*) FROM operation_players`).Scan(&n)) + assert.Equal(t, 1, n, "a failed replace leaves the old rows") + }) + } +} + +func TestPlayerQueriesFailures(t *testing.T) { + t.Run("closed database", func(t *testing.T) { + repo := newPlayersRepo(t) + require.NoError(t, repo.Close()) + _, err := repo.SearchPlayers(t.Context(), "", 10) + assert.Error(t, err) + _, err = repo.GetPlayerProfile(t.Context(), "", "nosey") + assert.Error(t, err) + assert.NotErrorIs(t, err, ErrNotFound) + _, err = repo.Summary(t.Context()) + assert.Error(t, err) + _, err = repo.Count(t.Context(), Filter{}) + assert.Error(t, err) + }) + + t.Run("unreadable rows", func(t *testing.T) { + repo := newPlayersRepo(t) + id := storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + mustExec(t, repo.db, `DROP TABLE operation_players`) + mustExec(t, repo.db, `CREATE TABLE operation_players ( + operation_id INTEGER, player_key TEXT, player_uid TEXT, name_key TEXT, name TEXT, side TEXT, role TEXT, + group_name TEXT, kills INTEGER, vehicle_kills INTEGER, team_kills INTEGER, deaths INTEGER)`) + mustExec(t, repo.db, `INSERT INTO operation_players VALUES (`+itoa(id)+`, 'name:ghost', '', 'ghost', NULL, '', '', '', 0, 0, 0, 0)`) + mustExec(t, repo.db, `INSERT INTO operation_player_names VALUES (`+itoa(id)+`, 'name:ghost', 0, 'ghost', 'ghost')`) + + _, err := repo.SearchPlayers(t.Context(), "ghost", 10) + assert.ErrorContains(t, err, "converting NULL to string") + _, err = repo.GetPlayerProfile(t.Context(), "", "ghost") + assert.ErrorContains(t, err, "converting NULL to string") + }) + + t.Run("unreadable names", func(t *testing.T) { + repo := newPlayersRepo(t) + id := storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + require.NoError(t, repo.ReplaceOperationPlayers(t.Context(), id, []OperationPlayer{{Name: "Ghost"}})) + mustExec(t, repo.db, `DROP TABLE operation_player_names`) + _, err := repo.GetPlayerProfile(t.Context(), "", "ghost") + assert.ErrorContains(t, err, "operation_player_names") + + mustExec(t, repo.db, `CREATE TABLE operation_player_names (operation_id INTEGER, player_key TEXT, ordinal INTEGER, name_key TEXT, name TEXT)`) + mustExec(t, repo.db, `INSERT INTO operation_player_names VALUES (`+itoa(id)+`, 'name:ghost', 1, 'ghost', NULL)`) + _, err = repo.GetPlayerProfile(t.Context(), "", "ghost") + assert.ErrorContains(t, err, "converting NULL to string") + }) + + for _, table := range []string{"operation_players", "operation_player_names"} { + t.Run("delete from "+table+" fails before the recording is removed", func(t *testing.T) { + repo := newPlayersRepo(t) + id := storePlayerOp(t, repo, "op", "Op", "altis", "2026-01-01") + require.NoError(t, repo.ReplaceOperationPlayers(t.Context(), id, []OperationPlayer{{Name: "N"}})) + mustExec(t, repo.db, `CREATE TRIGGER fail BEFORE DELETE ON `+table+` BEGIN SELECT RAISE(ABORT, 'players delete failed'); END`) + assert.ErrorContains(t, repo.Delete(t.Context(), id), "players delete failed") + _, err := repo.GetByID(t.Context(), itoa(id)) + assert.NoError(t, err, "the recording stays when its players cannot be removed") + + replacement := &Operation{WorldName: "altis", MissionName: "Op", Filename: "op", Date: "2026-01-02"} + assert.ErrorContains(t, repo.StoreReplacingByFilename(t.Context(), replacement), "players delete failed") + }) + } +} + +func TestOperationsSummary(t *testing.T) { + t.Run("describes every recording", func(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + empty, err := repo.Summary(ctx) + require.NoError(t, err) + assert.Equal(t, &OperationsSummary{Worlds: []string{}, Tags: []string{}}, empty) + + for _, op := range []*Operation{ + {WorldName: "Stratis", MissionName: "A", Filename: "a", Date: "2026-01-01", Tag: "TvT"}, + {WorldName: "altis", MissionName: "B", Filename: "b", Date: "2026-01-02", Tag: ""}, + {WorldName: "altis", MissionName: "C", Filename: "c", Date: "2026-01-03", Tag: "Coop"}, + } { + require.NoError(t, repo.Store(ctx, op)) + } + require.NoError(t, repo.UpdateOperationStats(ctx, 1, 12, 30, 20, nil)) + require.NoError(t, repo.UpdateOperationStats(ctx, 3, 40, 5, 2, nil)) + + summary, err := repo.Summary(ctx) + require.NoError(t, err) + assert.Equal(t, &OperationsSummary{ + Total: 3, Worlds: []string{"altis", "stratis"}, Tags: []string{"Coop", "TvT"}, + MaxPlayers: 40, TotalKills: 35, + }, summary) + }) + + // Each case keeps the columns the earlier queries read, so the failure + // lands on the next one. + for name, table := range map[string]string{ + "worlds query": `CREATE TABLE operations (player_count INTEGER, kill_count INTEGER, tag TEXT)`, + "tags query": `CREATE TABLE operations (player_count INTEGER, kill_count INTEGER, world_name TEXT)`, + "null world": `CREATE TABLE operations (player_count INTEGER, kill_count INTEGER, world_name TEXT, tag TEXT)`, + } { + t.Run(name, func(t *testing.T) { + repo := newPlayersRepo(t) + mustExec(t, repo.db, `DROP TABLE operations`) + mustExec(t, repo.db, table) + if name == "null world" { + mustExec(t, repo.db, `INSERT INTO operations VALUES (1, 1, NULL, '')`) + } + _, err := repo.Summary(t.Context()) + assert.Error(t, err) + }) + } +} + +func TestSelectFiltersSortsAndPages(t *testing.T) { + repo := newPlayersRepo(t) + ctx := t.Context() + for _, op := range []*Operation{ + {WorldName: "altis", MissionName: "bravo 100%", MissionDuration: 300, Filename: "f1", Date: "2026-01-03", Tag: "coop"}, + {WorldName: "stratis", MissionName: "Alpha", MissionDuration: 100, Filename: "f2", Date: "2026-01-01", Tag: "tvt"}, + {WorldName: "chernarus_summer", MissionName: "charlie", MissionDuration: 200, Filename: "f3", Date: "2026-01-02", Tag: "coop"}, + {WorldName: "altis", MissionName: "Delta", MissionDuration: 200, Filename: "f4", Date: "2026-01-02", Tag: "coop"}, + } { + require.NoError(t, repo.Store(ctx, op)) + } + names := func(ops []Operation) []string { + out := make([]string, len(ops)) + for i, op := range ops { + out[i] = op.Filename + } + return out + } + selectNames := func(f Filter) []string { + t.Helper() + ops, err := repo.Select(ctx, f) + require.NoError(t, err) + return names(ops) + } + + assert.Equal(t, []string{"f1", "f2", "f3", "f4"}, selectNames(Filter{}), "no sort keeps id order") + assert.Equal(t, []string{"f2", "f1", "f3", "f4"}, selectNames(Filter{Sort: "name"}), "name sort ignores case") + assert.Equal(t, []string{"f4", "f3", "f1", "f2"}, selectNames(Filter{Sort: "name", Dir: "desc"})) + assert.Equal(t, []string{"f1", "f4", "f3", "f2"}, selectNames(Filter{Sort: "date", Dir: "desc"}), "ties break on id") + assert.Equal(t, []string{"f2", "f3", "f4", "f1"}, selectNames(Filter{Sort: "duration", Dir: "asc"})) + assert.Equal(t, []string{"f4", "f3"}, selectNames(Filter{Sort: "date", Dir: "desc", Limit: 2, Offset: 1})) + assert.Empty(t, selectNames(Filter{Limit: 2, Offset: 10})) + + assert.Equal(t, []string{"f1", "f4"}, selectNames(Filter{Worlds: []string{"ALTIS"}})) + assert.Equal(t, []string{"f1", "f2", "f4"}, selectNames(Filter{Worlds: []string{"altis", "stratis"}})) + assert.Equal(t, []string{"f1"}, selectNames(Filter{Query: "100%"}), "% matches literally") + assert.Empty(t, selectNames(Filter{Query: "o_1"}), "_ matches literally") + assert.Equal(t, []string{"f2"}, selectNames(Filter{Query: "STRAT"}), "q matches the world name") + assert.Equal(t, []string{"f3"}, selectNames(Filter{Query: "Chernarus (Summer)", queryWorlds: []string{"chernarus_summer"}}), + "q matches a world by its display name") + assert.Equal(t, []string{"f3"}, selectNames(Filter{Query: "zzz", queryWorlds: []string{"chernarus_summer"}, Older: "2026-01-02", Newer: "2026-01-02"}), + "display name matches combine with the other filters") + assert.Empty(t, selectNames(Filter{Query: "zzz", queryWorlds: []string{"chernarus_summer"}, Tag: "tvt"})) + + n, err := repo.Count(ctx, Filter{Worlds: []string{"altis"}, Limit: 1, Offset: 1}) + require.NoError(t, err) + assert.Equal(t, 2, n, "count ignores the page") +} + +func TestMigrationsSinceV17(t *testing.T) { + for _, version := range []string{"17", "18", "19"} { + t.Run(version, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "operations.db") + repo, err := NewRepoOperation(path) + require.NoError(t, err) + mustExec(t, repo.db, `DELETE FROM version WHERE db >= `+version) + mustExec(t, repo.db, `CREATE TRIGGER block BEFORE INSERT ON version WHEN NEW.db = `+version+` + BEGIN SELECT RAISE(ABORT, 'blocked migration'); END`) + require.ErrorContains(t, repo.migration(), "blocked migration") + mustExec(t, repo.db, `DROP TRIGGER block`) + require.NoError(t, repo.Close()) + + // Rerunning over the existing columns and tables completes the migrations. + repo, err = NewRepoOperation(path) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, repo.Close()) }) + var latest int + require.NoError(t, repo.db.QueryRow(`SELECT MAX(db) FROM version`).Scan(&latest)) + assert.Equal(t, 19, latest) + assert.True(t, repo.hasColumn("operations", "player_index_revision")) + assert.True(t, repo.hasColumn("operations", "chat_redaction_revision")) + }) + } +} + +func TestPlaceholders(t *testing.T) { + assert.Equal(t, "?", placeholders(1)) + assert.Equal(t, "?,?,?", placeholders(3)) +} + +func itoa(n int64) string { + return strconv.FormatInt(n, 10) +} diff --git a/internal/server/upload_staging.go b/internal/server/upload_staging.go new file mode 100644 index 00000000..ab80ec9a --- /dev/null +++ b/internal/server/upload_staging.go @@ -0,0 +1,38 @@ +package server + +import ( + "crypto/rand" + "os" + "path/filepath" + "strings" +) + +// uploadStagingDir is where an upload waits until it is checked, under the +// data directory so publishing it is a rename. It may hold a #login password +// until then, so nothing in it is ever served, and no recording may take its +// name. +const uploadStagingDir = ".upload-staging" + +// makeUploadStage creates a directory of its own for one upload in the +// staging area, named at random so no other request can find or share it. +func makeUploadStage(dataDir string) (string, error) { + dir := filepath.Join(dataDir, uploadStagingDir, "upload-"+rand.Text()) + return dir, os.MkdirAll(dir, 0o700) +} + +// inUploadStaging reports whether urlPath, under the data directory, lies in +// the upload staging area. The filesystem decides rather than the name: a +// disk that ignores case also finds the area by another case, and Windows by +// a name with dots or spaces after it, or by its 8.3 short name. +func inUploadStaging(dataDir, urlPath string) bool { + first, _, _ := strings.Cut(strings.TrimPrefix(urlPath, "/"), "/") + if first == "" { + return false + } + staging, err := os.Stat(filepath.Join(dataDir, uploadStagingDir)) + if err != nil { + return false // nothing is staged + } + entry, err := os.Stat(filepath.Join(dataDir, first)) + return err == nil && os.SameFile(staging, entry) +} diff --git a/internal/server/upload_staging_test.go b/internal/server/upload_staging_test.go new file mode 100644 index 00000000..6c01a5df --- /dev/null +++ b/internal/server/upload_staging_test.go @@ -0,0 +1,65 @@ +package server + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMakeUploadStage(t *testing.T) { + dataDir := t.TempDir() + first, err := makeUploadStage(dataDir) + require.NoError(t, err) + second, err := makeUploadStage(dataDir) + require.NoError(t, err) + assert.NotEqual(t, first, second, "every upload has a directory of its own") + for _, stage := range []string{first, second} { + assert.DirExists(t, stage) + assert.Equal(t, filepath.Join(dataDir, uploadStagingDir), filepath.Dir(stage)) + } + + blocked := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(blocked, uploadStagingDir), nil, 0o644)) + _, err = makeUploadStage(blocked) + assert.Error(t, err, "a file where the staging area belongs") +} + +func TestInUploadStaging(t *testing.T) { + dataDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dataDir, "rec.json.gz"), nil, 0o644)) + assert.False(t, inUploadStaging(dataDir, "/"+uploadStagingDir+"/x"), "nothing is staged before the first upload") + + stage, err := makeUploadStage(dataDir) + require.NoError(t, err) + for urlPath, want := range map[string]bool{ + "/" + uploadStagingDir + "/" + filepath.Base(stage) + "/recording.json.gz": true, + "/" + uploadStagingDir: true, + uploadStagingDir: true, + "/": false, + "": false, + "/rec.json.gz": false, + "/missing/manifest.pb": false, + } { + assert.Equal(t, want, inUploadStaging(dataDir, urlPath), urlPath) + } + + // A name the disk resolves to the area is the area, on any disk that does. + alias := strings.ToUpper(uploadStagingDir) + _, err = os.Stat(filepath.Join(dataDir, alias)) + assert.Equal(t, err == nil, inUploadStaging(dataDir, "/"+alias+"/x")) +} + +func TestStorageNamesSpareTheStagingArea(t *testing.T) { + for name, invalid := range map[string]bool{ + "": true, " ": true, ".": true, "..": true, "...": true, ". .": true, "a/b": true, "a\\b": true, + uploadStagingDir: true, strings.ToUpper(uploadStagingDir): true, + uploadStagingDir + ".": true, uploadStagingDir + " ": true, + "rec": false, "Op v1.": false, ".hidden": false, uploadStagingDir + "2": false, "upload-staging": false, + } { + assert.Equal(t, invalid, isInvalidStorageName(name), "%q", name) + } +} diff --git a/internal/storage/chat_conversion_test.go b/internal/storage/chat_conversion_test.go new file mode 100644 index 00000000..07635553 --- /dev/null +++ b/internal/storage/chat_conversion_test.go @@ -0,0 +1,73 @@ +package storage + +import ( + "context" + "os" + "path/filepath" + "testing" + + pbv1 "github.com/OCAP2/web/pkg/schemas/protobuf/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestParseChatEvent(t *testing.T) { + for name, tc := range map[string]struct { + event []interface{} + want string + }{ + "every field": { + []interface{}{2.0, "chat", "Moving up", "Nosey", "Side"}, + `{"message":"Moving up","fromName":"Nosey","channel":"Side"}`, + }, + "masked password": { + []interface{}{3.0, "chat", " #LOGIN synthetic-password", "Nosey", "Global"}, + `{"message":"#LOGIN ********","fromName":"Nosey","channel":"Global"}`, + }, + "copy written before the sender was added": { + []interface{}{4.0, "chat", "contact"}, + `{"message":"contact","fromName":"","channel":""}`, + }, + "no message": { + []interface{}{5.0, "chat"}, + `{"message":"","fromName":"","channel":""}`, + }, + } { + t.Run(name, func(t *testing.T) { + event := parseEventArray(tc.event) + require.NotNil(t, event) + assert.Equal(t, "chat", event.Type) + assert.JSONEq(t, tc.want, event.Message) + assert.Zero(t, event.SourceID, "chat is not parsed as a kill") + }) + } +} + +// A converted recording keeps its chat, which playback reads back out of the +// v1 protobuf manifest; the UI's converted-chat test decodes the same message. +func TestConvertKeepsChat(t *testing.T) { + dir := t.TempDir() + jsonPath := filepath.Join(dir, "chat.json") + require.NoError(t, os.WriteFile(jsonPath, []byte(`{ + "worldName": "altis", "missionName": "Synthetic chat", "endFrame": 10, "captureDelay": 1, + "entities": [], "Markers": [], "times": [], + "events": [ + [2, "chat", "Moving up", "Nosey", "Side"], + [3, "chat", "#login synthetic-password", "Nosey", "Global"] + ] + }`), 0o644)) + output := filepath.Join(dir, "chat") + require.NoError(t, NewProtobufEngine(dir).Convert(context.Background(), jsonPath, output)) + + data, err := os.ReadFile(filepath.Join(output, "manifest.pb")) + require.NoError(t, err) + var manifest pbv1.Manifest + require.NoError(t, proto.Unmarshal(data, &manifest)) + require.Len(t, manifest.Events, 2) + assert.Equal(t, "chat", manifest.Events[0].Type) + assert.Equal(t, uint32(2), manifest.Events[0].FrameNum) + assert.JSONEq(t, `{"message":"Moving up","fromName":"Nosey","channel":"Side"}`, manifest.Events[0].Message) + assert.JSONEq(t, `{"message":"#login ********","fromName":"Nosey","channel":"Global"}`, manifest.Events[1].Message) + assert.NotContains(t, string(data), "synthetic-password") +} diff --git a/internal/storage/engine.go b/internal/storage/engine.go index 01cbbd2e..b154b724 100644 --- a/internal/storage/engine.go +++ b/internal/storage/engine.go @@ -34,6 +34,9 @@ type Event struct { ObjectType string `json:"objectType,omitempty"` UnitName string `json:"unitName,omitempty"` Side string `json:"side,omitempty"` + // PlayerUID is the Steam UID of a connected or disconnected player, when + // the recording has one. + PlayerUID string `json:"playerUid,omitempty"` } // EntityDef defines an entity's metadata @@ -49,6 +52,9 @@ type EntityDef struct { IsPlayer bool `json:"isPlayer"` VehicleClass string `json:"vehicleClass,omitempty"` FramesFired []FiredFrame `json:"framesFired,omitempty"` + // PlayerUID is the Steam UID of a player unit. v1 JSON and v2 recordings + // carry it when the addon sent one; converted v1 protobuf has none. + PlayerUID string `json:"playerUid,omitempty"` } // FiredFrame represents a projectile fired at a specific frame diff --git a/internal/storage/json.go b/internal/storage/json.go index 3f4dd69a..5bd3bda7 100644 --- a/internal/storage/json.go +++ b/internal/storage/json.go @@ -40,20 +40,7 @@ func (e *JSONEngine) GetManifest(ctx context.Context, filename string) (*Manifes if entities, ok := data["entities"].([]interface{}); ok { for _, ent := range entities { if em, ok := ent.(map[string]interface{}); ok { - def := EntityDef{ - ID: getUint32(em, "id"), - Type: getString(em, "type"), - Name: getString(em, "name"), - Side: getString(em, "side"), - Group: getString(em, "group"), - Role: getString(em, "role"), - StartFrame: getUint32(em, "startFrameNum"), - IsPlayer: getFloat64(em, "isPlayer") == 1, - } - if em["class"] != nil { - def.VehicleClass = getString(em, "class") - } - manifest.Entities = append(manifest.Entities, def) + manifest.Entities = append(manifest.Entities, entityDefFromJSON(em)) } } } @@ -75,20 +62,87 @@ func (e *JSONEngine) GetManifest(ctx context.Context, filename string) (*Manifes return manifest, nil } -func (e *JSONEngine) loadJSON(filename string) (map[string]interface{}, error) { - // Try gzipped first - path := filepath.Join(e.dataDir, filename+".json.gz") - if _, err := os.Stat(path); err == nil { - return e.loadGzipJSON(path) +// StreamManifest reads the manifest GetManifest does in one streaming pass, +// holding a single entity or event in memory rather than the whole recording. +// The player index reads v1 recordings this way, converted ones included: +// their JSON has the Steam UIDs that the v1 protobuf manifest lacks. +func (e *JSONEngine) StreamManifest(ctx context.Context, filename string) (*Manifest, error) { + // The reader detects gzip from the content. + path, _ := e.jsonPath(filename) + if path == "" { + return nil, fmt.Errorf("recording not found: %s", filename) + } + reader, err := OpenStreamingJSONReader(path) + if err != nil { + return nil, err + } + defer reader.Close() + + manifest := &Manifest{Version: 1, ChunkSize: 300, ChunkCount: 1} + meta, err := reader.Process(StreamingCallbacks{ + OnEntity: func(em map[string]interface{}) error { + manifest.Entities = append(manifest.Entities, entityDefFromJSON(em)) + return nil + }, + OnEvent: func(evtArr []interface{}) error { + if event := parseEventArray(evtArr); event != nil { + manifest.Events = append(manifest.Events, *event) + } + return nil + }, + }) + if err != nil { + return nil, err + } + manifest.WorldName = meta.WorldName + manifest.MissionName = meta.MissionName + manifest.EndFrame = meta.EndFrame + manifest.CaptureDelayMs = meta.CaptureDelayMs + return manifest, nil +} + +// entityDefFromJSON reads one v1 JSON entity. +func entityDefFromJSON(em map[string]interface{}) EntityDef { + def := EntityDef{ + ID: getUint32(em, "id"), + Type: getString(em, "type"), + Name: getString(em, "name"), + Side: getString(em, "side"), + Group: getString(em, "group"), + Role: getString(em, "role"), + StartFrame: getUint32(em, "startFrameNum"), + IsPlayer: getFloat64(em, "isPlayer") == 1, + PlayerUID: getString(em, "playerUid"), } + if em["class"] != nil { + def.VehicleClass = getString(em, "class") + } + return def +} - // Try uncompressed +// jsonPath finds a recording's JSON, gzipped first; it is empty when there is +// none. +func (e *JSONEngine) jsonPath(filename string) (path string, gzipped bool) { + path = filepath.Join(e.dataDir, filename+".json.gz") + if _, err := os.Stat(path); err == nil { + return path, true + } path = filepath.Join(e.dataDir, filename+".json") if _, err := os.Stat(path); err == nil { - return e.loadPlainJSON(path) + return path, false } + return "", false +} - return nil, fmt.Errorf("recording not found: %s", filename) +func (e *JSONEngine) loadJSON(filename string) (map[string]interface{}, error) { + path, gzipped := e.jsonPath(filename) + if path == "" { + return nil, fmt.Errorf("recording not found: %s", filename) + } + if gzipped { + return e.loadGzipJSON(path) + } + return e.loadPlainJSON(path) } func (e *JSONEngine) loadGzipJSON(path string) (map[string]interface{}, error) { diff --git a/internal/storage/parser_test.go b/internal/storage/parser_test.go index 301498c5..be754d72 100644 --- a/internal/storage/parser_test.go +++ b/internal/storage/parser_test.go @@ -295,7 +295,7 @@ func TestParserV1_Parse_Events(t *testing.T) { "events": []interface{}{ []interface{}{8.0, "killed", 0.0, 1.0, "arifle_MX", 150.0}, []interface{}{5.0, "hit", 0.0, 1.0, "pistol"}, - []interface{}{3.0, "chat", 0.0, 0.0, "Hello world"}, + []interface{}{3.0, "customEvent", 0.0, 0.0, "Hello world"}, }, } @@ -319,7 +319,7 @@ func TestParserV1_Parse_Events(t *testing.T) { // Chat event evt = result.Events[2] - assert.Equal(t, "chat", evt.Type) + assert.Equal(t, "customEvent", evt.Type) assert.Equal(t, "Hello world", evt.Message) } @@ -716,7 +716,7 @@ func TestParserV1_parseEvent_EdgeCases(t *testing.T) { t.Run("non-combat event with message at index 4", func(t *testing.T) { evt := p.parseEvent([]interface{}{ 100.0, - "chat", + "customEvent", // an unknown type takes the generic path 5.0, // sourceId 10.0, // targetId "Hello world", // message (not weapon since type is not killed/hit) diff --git a/internal/storage/parser_v1.go b/internal/storage/parser_v1.go index f325bc30..c73a290c 100644 --- a/internal/storage/parser_v1.go +++ b/internal/storage/parser_v1.go @@ -4,6 +4,8 @@ package storage import ( "encoding/json" "strings" + + "github.com/OCAP2/web/internal/redact" ) func init() { @@ -140,6 +142,14 @@ func (p *ParserV1) parseEvent(evtArr []interface{}) *Event { return parseEventArray(evtArr) } +// ChatPayload carries a chat event's fields as JSON in the message of an Event, +// and of a converted v1 protobuf event, where the UI decodes the same keys. +type ChatPayload struct { + Message string `json:"message"` + FromName string `json:"fromName"` + Channel string `json:"channel"` +} + // parseEventArray converts a JSON event array to schema-agnostic Event. func parseEventArray(evtArr []interface{}) *Event { if len(evtArr) < 2 { @@ -158,11 +168,14 @@ func parseEventArray(evtArr []interface{}) *Event { Type: eventType, } - // Connect/disconnect events: [frameNum, "type", "playerName"] + // Connect/disconnect events: [frameNum, "type", "playerName", "playerUid"?] if event.Type == "connected" || event.Type == "disconnected" { if len(evtArr) > 2 { event.Message = toString(evtArr[2]) } + if len(evtArr) > 3 { + event.PlayerUID = toString(evtArr[3]) + } return event } @@ -200,6 +213,25 @@ func parseEventArray(evtArr []interface{}) *Event { return event } + // Chat: [frameNum, "chat", message, fromName?, channel?]. The fields travel + // as JSON in the message, as for the structured events above, with the + // password of a #login command masked on the way. + if event.Type == "chat" { + var payload ChatPayload + if len(evtArr) > 2 { + payload.Message = redact.LoginCommand(toString(evtArr[2])) + } + if len(evtArr) > 3 { + payload.FromName = toString(evtArr[3]) + } + if len(evtArr) > 4 { + payload.Channel = toString(evtArr[4]) + } + encoded, _ := json.Marshal(payload) + event.Message = string(encoded) + return event + } + // End mission: [frameNum, "endMission", [side, message]] or [frameNum, "endMission", "message"] if event.Type == "endMission" { if len(evtArr) > 2 { diff --git a/internal/storage/player_uid_test.go b/internal/storage/player_uid_test.go new file mode 100644 index 00000000..9c345f2a --- /dev/null +++ b/internal/storage/player_uid_test.go @@ -0,0 +1,137 @@ +package storage + +import ( + "compress/gzip" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + + pbv2 "github.com/OCAP2/web/pkg/schemas/protobuf/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// uidRecording is a synthetic v1 recording as the extension writes it: player +// units and connection events carry the Steam UID, AI and vehicles do not. +const uidRecording = `{ + "worldName": "altis", + "missionName": "Synthetic UID Mission", + "endFrame": 40, + "captureDelay": 1, + "entities": [ + {"id": 0, "type": "unit", "name": "Nosey", "side": "WEST", "group": "Alpha", "role": "Medic", "startFrameNum": 0, "isPlayer": 1, "playerUid": "76561190000000001", "positions": [[[1, 2], 0, 1, 0, "Nosey", 1]], "framesFired": []}, + {"id": 1, "type": "unit", "name": "Rifleman", "side": "EAST", "group": "Bravo", "startFrameNum": 0, "isPlayer": 0, "positions": [], "framesFired": []}, + {"id": 2, "type": "vehicle", "name": "Offroad", "class": "car", "startFrameNum": 0, "positions": []} + ], + "events": [ + [0, "connected", "Nosey", "76561190000000001"], + [1, "connected", "Nomad"], + [30, "disconnected", "Nosey", "76561190000000001"], + [20, "killed", 1, [0, "MX"], 100], + [5], + [] + ], + "Markers": [], + "times": [] +}` + +func writeJSONRecording(t *testing.T, dir, name, content string, gzipped bool) { + t.Helper() + if !gzipped { + require.NoError(t, os.WriteFile(filepath.Join(dir, name+".json"), []byte(content), 0o644)) + return + } + f, err := os.Create(filepath.Join(dir, name+".json.gz")) + require.NoError(t, err) + gz := gzip.NewWriter(f) + _, err = gz.Write([]byte(content)) + require.NoError(t, err) + require.NoError(t, gz.Close()) + require.NoError(t, f.Close()) +} + +func assertUIDManifest(t *testing.T, m *Manifest) { + t.Helper() + assert.Equal(t, "altis", m.WorldName) + assert.Equal(t, "Synthetic UID Mission", m.MissionName) + assert.Equal(t, uint32(40), m.EndFrame) + assert.Equal(t, uint32(1000), m.CaptureDelayMs) + require.Len(t, m.Entities, 3) + assert.Equal(t, "76561190000000001", m.Entities[0].PlayerUID) + assert.Equal(t, "Medic", m.Entities[0].Role) + assert.True(t, m.Entities[0].IsPlayer) + assert.Empty(t, m.Entities[1].PlayerUID, "AI has no Steam UID") + assert.Equal(t, "car", m.Entities[2].VehicleClass) + + require.Len(t, m.Events, 4, "events shorter than [frame, type] are skipped") + assert.Equal(t, Event{FrameNum: 0, Type: "connected", Message: "Nosey", PlayerUID: "76561190000000001"}, m.Events[0]) + assert.Equal(t, Event{FrameNum: 1, Type: "connected", Message: "Nomad"}, m.Events[1], "older recordings send no UID") + assert.Equal(t, "76561190000000001", m.Events[2].PlayerUID) + assert.Equal(t, "killed", m.Events[3].Type) + assert.Equal(t, uint32(1), m.Events[3].TargetID) +} + +func TestJSONManifestsCarryPlayerUIDs(t *testing.T) { + for _, gzipped := range []bool{false, true} { + dir := t.TempDir() + writeJSONRecording(t, dir, "uid", uidRecording, gzipped) + engine := NewJSONEngine(dir) + + loaded, err := engine.GetManifest(context.Background(), "uid") + require.NoError(t, err) + assertUIDManifest(t, loaded) + + streamed, err := engine.StreamManifest(context.Background(), "uid") + require.NoError(t, err) + assertUIDManifest(t, streamed) + assert.Equal(t, loaded, streamed, "streaming reads the same manifest") + } +} + +func TestStreamManifestFailures(t *testing.T) { + dir := t.TempDir() + engine := NewJSONEngine(dir) + + _, err := engine.StreamManifest(context.Background(), "missing") + assert.EqualError(t, err, "recording not found: missing") + + writeJSONRecording(t, dir, "broken", `{"entities": [{"id": 0}, `, false) + _, err = engine.StreamManifest(context.Background(), "broken") + assert.ErrorContains(t, err, "stream entities") + + writeJSONRecording(t, dir, "locked", uidRecording, true) + original := openStreamFile + t.Cleanup(func() { openStreamFile = original }) + openStreamFile = func(string) (readSeekCloser, error) { return nil, errors.New("synthetic open failure") } + _, err = engine.StreamManifest(context.Background(), "locked") + assert.EqualError(t, err, "synthetic open failure") +} + +func TestV2ManifestCarriesPlayerUIDs(t *testing.T) { + connected, err := json.Marshal(map[string]any{"playerUid": "76561190000000002"}) + require.NoError(t, err) + + engine := writeV2Manifest(t, t.TempDir(), "rec", &pbv2.Manifest{ + Version: 2, + FrameCount: 10, + Soldiers: []*pbv2.SoldierDef{ + {Id: 1, Name: "Nomad", IsPlayer: true, PlayerUid: "76561190000000002"}, + {Id: 2, Name: "Rifleman"}, + }, + Events: []*pbv2.Event{ + {FrameNum: 1, Event: &pbv2.Event_General{General: &pbv2.GeneralEvent{Name: "connected", Message: "Nomad", ExtraDataJson: connected}}}, + {FrameNum: 2, Event: &pbv2.Event_General{General: &pbv2.GeneralEvent{Name: "disconnected", Message: "Nomad"}}}, + }, + }) + + m := getV2(t, engine, "rec") + require.Len(t, m.Entities, 2) + assert.Equal(t, "76561190000000002", m.Entities[0].PlayerUID) + assert.Empty(t, m.Entities[1].PlayerUID) + require.Len(t, m.Events, 2) + assert.Equal(t, "76561190000000002", m.Events[0].PlayerUID) + assert.Empty(t, m.Events[1].PlayerUID) +} diff --git a/internal/storage/precompress.go b/internal/storage/precompress.go index 147b329b..d4fc03f0 100644 --- a/internal/storage/precompress.go +++ b/internal/storage/precompress.go @@ -105,6 +105,54 @@ func WriteArtifact(path string, data []byte) error { return WriteSidecars(path, data) } +// ReplaceArtifact replaces an artifact that may already be served, and its +// precompressed sidecars. The old sidecars go first: a sidecar can be asked +// for by name, so none may outlive the bytes it was made from, even when a +// later step fails. The raw file is then renamed into place, so a request +// reads the old bytes or the new ones, and the sidecars are written again. +func ReplaceArtifact(path string, data []byte) error { + if err := removeSidecars(path); err != nil { + return err + } + if err := writeFileAtomic(path, data); err != nil { + return err + } + return WriteSidecars(path, data) +} + +// SidecarsMatch reports whether every precompressed sidecar of path that +// exists decodes to data. One that does not decode does not match. +func SidecarsMatch(path string, data []byte) (bool, error) { + for _, encoding := range PrecompressEncodings { + encoded, err := os.ReadFile(path + PrecompressSuffix[encoding]) + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + return false, err + } + decoded, err := decompress(encoding, encoded) + if err != nil || !bytes.Equal(decoded, data) { + return false, nil + } + } + return true, nil +} + +// decompress decodes a sidecar written with one of PrecompressEncodings. +func decompress(encoding string, data []byte) ([]byte, error) { + if encoding == EncodingZstd { + dec, _ := zstd.NewReader(nil) // fails only on invalid options; none are given + defer dec.Close() + return dec.DecodeAll(data, nil) + } + zr, err := gzip.NewReader(bytes.NewReader(data)) + if err != nil { + return nil, err + } + return io.ReadAll(zr) +} + // WriteSidecars writes just the precompressed variants of an artifact whose raw // bytes are already on disk. Conversion reaches it through WriteArtifact; the // backfill command uses it directly, so an existing recording gains sidecars diff --git a/internal/storage/precompress_test.go b/internal/storage/precompress_test.go index 78c14739..d06e765e 100644 --- a/internal/storage/precompress_test.go +++ b/internal/storage/precompress_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "compress/gzip" + "errors" "io" "os" "path/filepath" @@ -250,3 +251,108 @@ func TestWriteSidecars_CompressFailureAborts(t *testing.T) { // The stale sidecars are untouched: the abort happens before any write. assert.DirExists(t, filepath.Join(dir)) } + +// Replacing an artifact rewrites the sidecars too, so a stale compressed copy +// of the old bytes can never answer in place of the new ones. +func TestReplaceArtifact(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "manifest.pb") + require.NoError(t, WriteArtifact(path, compressiblePayload())) + + replacement := bytes.Repeat([]byte("masked manifest bytes "), 4096) + require.NoError(t, ReplaceArtifact(path, replacement)) + raw, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, replacement, raw) + assert.Equal(t, replacement, readGzip(t, path+".gz")) + + assert.Error(t, ReplaceArtifact(filepath.Join(dir, "missing", "manifest.pb"), replacement)) +} + +// A replacement that fails after the raw file changed leaves no sidecar of the +// old bytes behind, since one can be requested by name. +func TestReplaceArtifactNeverLeavesOldSidecars(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "manifest.pb") + require.NoError(t, WriteArtifact(path, compressiblePayload())) + require.FileExists(t, path+".zst") + + orig := precompressZstdEncoder + t.Cleanup(func() { precompressZstdEncoder = orig }) + precompressZstdEncoder = func() (*zstd.Encoder, error) { return nil, errors.New("zstd unavailable") } + + replacement := bytes.Repeat([]byte("masked manifest bytes "), 4096) + require.ErrorContains(t, ReplaceArtifact(path, replacement), "zstd unavailable") + raw, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, replacement, raw) + assert.NoFileExists(t, path+".zst") + assert.NoFileExists(t, path+".gz") + + t.Run("a sidecar that cannot be removed stops the replacement", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "manifest.pb") + require.NoError(t, os.WriteFile(path, []byte("old"), 0o644)) + require.NoError(t, os.MkdirAll(filepath.Join(path+".zst", "busy"), 0o755)) + assert.Error(t, ReplaceArtifact(path, replacement)) + raw, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, "old", string(raw), "the raw file is left as it was") + }) +} + +func TestSidecarsMatch(t *testing.T) { + data := compressiblePayload() + write := func(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "manifest.pb") + require.NoError(t, WriteArtifact(path, data)) + return path + } + + t.Run("sidecars of the same bytes match", func(t *testing.T) { + ok, err := SidecarsMatch(write(t), data) + require.NoError(t, err) + assert.True(t, ok) + }) + t.Run("no sidecars match", func(t *testing.T) { + ok, err := SidecarsMatch(filepath.Join(t.TempDir(), "manifest.pb"), data) + require.NoError(t, err) + assert.True(t, ok) + }) + t.Run("sidecars of other bytes do not", func(t *testing.T) { + path := write(t) + ok, err := SidecarsMatch(path, append([]byte("changed "), data...)) + require.NoError(t, err) + assert.False(t, ok) + }) + for _, suffix := range []string{".zst", ".gz"} { + t.Run("an undecodable "+suffix+" does not match", func(t *testing.T) { + path := write(t) + require.NoError(t, os.WriteFile(path+suffix, []byte("not compressed"), 0o644)) + ok, err := SidecarsMatch(path, data) + require.NoError(t, err) + assert.False(t, ok) + }) + } + t.Run("a truncated gzip sidecar does not match", func(t *testing.T) { + path := write(t) + require.NoError(t, os.Remove(path+".zst")) + encoded, err := os.ReadFile(path + ".gz") + require.NoError(t, err) + require.NoError(t, os.WriteFile(path+".gz", encoded[:len(encoded)/2], 0o644)) + ok, err := SidecarsMatch(path, data) + require.NoError(t, err) + assert.False(t, ok) + }) + t.Run("an unreadable sidecar is an error", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "manifest.pb") + require.NoError(t, os.MkdirAll(path+".zst", 0o755)) + _, err := SidecarsMatch(path, data) + assert.Error(t, err) + }) +} + +func TestManifestVersion(t *testing.T) { + assert.Equal(t, uint64(2), ManifestVersion([]byte{0x08, 0x02})) + assert.Equal(t, uint64(0), ManifestVersion(nil)) +} diff --git a/internal/storage/protobuf.go b/internal/storage/protobuf.go index 203c9bb8..c3888a16 100644 --- a/internal/storage/protobuf.go +++ b/internal/storage/protobuf.go @@ -90,6 +90,12 @@ func (e *ProtobufEngine) GetManifest(ctx context.Context, filename string) (*Man return manifest, nil } +// ManifestVersion returns the schema version a protobuf manifest declares, 1 +// for a converted recording and 2 for a native one, or 0 when it declares none. +func ManifestVersion(data []byte) uint64 { + return protobufVersion(data) +} + func protobufVersion(data []byte) uint64 { for len(data) > 0 { num, typ, n := protowire.ConsumeTag(data) diff --git a/internal/storage/protobuf_v2.go b/internal/storage/protobuf_v2.go index 067a18fb..97a9cbac 100644 --- a/internal/storage/protobuf_v2.go +++ b/internal/storage/protobuf_v2.go @@ -28,7 +28,7 @@ func readV2Manifest(data []byte) (*Manifest, error) { m.AddonVersion = p.Mission.AddonVersion } for _, s := range p.Soldiers { - m.Entities = append(m.Entities, EntityDef{ID: s.Id, Type: "unit", Name: s.Name, Side: v2Side(s.Side), Group: s.GroupName, Role: s.Role, StartFrame: s.StartFrame, EndFrame: s.EndFrame, IsPlayer: s.IsPlayer}) + m.Entities = append(m.Entities, EntityDef{ID: s.Id, Type: "unit", Name: s.Name, Side: v2Side(s.Side), Group: s.GroupName, Role: s.Role, StartFrame: s.StartFrame, EndFrame: s.EndFrame, IsPlayer: s.IsPlayer, PlayerUID: s.PlayerUid}) } for _, v := range p.Vehicles { m.Entities = append(m.Entities, EntityDef{ID: v.Id, Type: "vehicle", Name: v.Name, VehicleClass: v.VehicleClass, StartFrame: v.StartFrame, EndFrame: v.EndFrame}) @@ -70,13 +70,15 @@ func readV2Manifest(data []byte) (*Manifest, error) { evt.ObjectType = g.ObjectType evt.UnitName = g.UnitName var extra struct { - Side string - Position []float32 + Side string + Position []float32 + PlayerUID string `json:"playerUid"` } json.Unmarshal(g.ExtraDataJson, &extra) if evt.Side == "" { evt.Side = extra.Side } + evt.PlayerUID = extra.PlayerUID if len(extra.Position) >= 2 { evt.PosX = extra.Position[0] evt.PosY = extra.Position[1] diff --git a/internal/testkit/cases.go b/internal/testkit/cases.go index 69017acf..edbb54ee 100644 --- a/internal/testkit/cases.go +++ b/internal/testkit/cases.go @@ -1,7 +1,7 @@ package testkit // Bump this when case inputs or expected behavior change. -const fixtureVersion = "ocap-local-v5" +const fixtureVersion = "ocap-local-v7" type testStep struct { target string @@ -48,18 +48,19 @@ var cases = []testCase{ }}, {"conversion-recovery", "Clean interrupted conversions without resetting stream-owned recordings", []testStep{ {"./internal/conversion", []string{"TestWorker_CleanupInterrupted", "TestWorker_CleanupInterrupted_RetryFailed", "TestWorker_CleanupInterrupted_LeavesStreaming", "TestConvertOperation_UpdateStorageFormatError", "TestNativeV2SurvivesLegacyConversionAndStatsBackfill"}}, - {"./internal/server", []string{"TestRetryConversion", "TestRetryConversion_NotFailed", "TestHandlerAdmin_RetryV2AndDeleteLocked"}}, + {"./internal/server", []string{"TestRetryConversion", "TestRetryConversion_NotFailed", "TestHandlerAdmin_RetryV2AndDeleteLocked", "TestStalePlayerIndexJobWritesNothing"}}, }}, {"playback-delivery", "Negotiated recording artifacts and UI compatibility with stored formats", []testStep{ - {"./internal/server", []string{"TestIntegration_ConversionAndStaticServing", "TestIntegration_PrecompressedArtifactServing"}}, - {"./internal/storage", []string{"TestWriteArtifact_RemovesStaleSidecarsWhenPayloadShrinks"}}, - {"./internal/ingestion", []string{"TestExportV2AsV1JSONMatchesSessionConversion", "TestExportV2AsV1JSONErrorsAndCancellation"}}, + {"./internal/server", []string{"TestIntegration_ConversionAndStaticServing", "TestIntegration_PrecompressedArtifactServing", "TestStoredPasswordsNeverLeaveTheServer", "TestStaleSidecarAfterAFailedMaskIsNotServed", "TestReplacingUploadIsMaskedBeforeItIsPublished", "TestStagedUploadIsNeverServed", "TestStoredRecordingIsNotServedByAnotherName", "TestADamagedPartKeepsOnlyItselfFromBeingServed", "TestSidecarWithoutItsManifestIsNotServed", "TestCopiesNoCheckReadsAreNotServed"}}, + {"./internal/storage", []string{"TestWriteArtifact_RemovesStaleSidecarsWhenPayloadShrinks", "TestReplaceArtifactNeverLeavesOldSidecars", "TestConvertKeepsChat"}}, + {"./internal/ingestion", []string{"TestExportV2AsV1JSONMatchesSessionConversion", "TestExportV2AsV1JSONErrorsAndCancellation", "TestRedactStoredChatMasksV2ManifestAndCopy", "TestRedactStoredChatRewritesStaleSidecars", "TestRedactStoredChatStreamsLargeRecordings", "TestMaskJSONChatRefusesWhatIsNotJSON", "TestRedactStoredChatChecksSidecarsWithoutAManifest"}}, {"ui", []string{ "src/data/decoders/__tests__/streamingV2Compatibility.test.ts", "src/data/decoders/__tests__/protobufDecoder.test.ts", "src/data/__tests__/chunkManager.test.ts", "src/pages/recording-playback/__tests__/snapshotReplay.integration.test.ts", "src/pages/recording-playback/__tests__/convertedCombat.integration.test.ts", + "src/pages/recording-playback/__tests__/convertedChat.integration.test.ts", "src/pages/recording-playback/__tests__/transmissionSidecars.integration.test.tsx", "src/playback/__tests__/wholeMissionAnalysis.test.ts", }}, diff --git a/ui/src/data/__tests__/apiClient.test.ts b/ui/src/data/__tests__/apiClient.test.ts index fd50cbdb..cb5a0fe9 100644 --- a/ui/src/data/__tests__/apiClient.test.ts +++ b/ui/src/data/__tests__/apiClient.test.ts @@ -498,6 +498,134 @@ describe("ApiClient", () => { }); }); + // ─── Paged recordings, summary and players ─── + + describe("getRecordingsPage", () => { + const raw = { id: 7, world_name: "altis", mission_name: "Op Paged", mission_duration: 60, filename: "paged", date: "2026-01-01" }; + + function mockPage(data: unknown, headers?: Record) { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ + ok: true, + status: 200, + statusText: "OK", + json: () => Promise.resolve(data), + headers: headers ? new Headers(headers) : undefined, + }), + ); + } + + it("sends every filter and reads the total header", async () => { + mockPage([raw], { "X-Total-Count": "42" }); + const client = new ApiClient("/aar/"); + const page = await client.getRecordingsPage({ + q: "op", tag: "TvT", tagExact: "COOP", worlds: ["altis", "stratis"], player: "Nosey", playerUid: "76561190000000001", + sort: "name", dir: "desc", limit: 50, offset: 100, + }); + + const url = (fetch as ReturnType).mock.calls[0][0] as string; + expect(url).toBe("/aar/api/v1/operations?q=op&tag=TvT&tagExact=COOP&world=altis&world=stratis&player=Nosey&playerUid=76561190000000001&sort=name&dir=desc&limit=50&offset=100"); + expect(page.total).toBe(42); + expect(page.next).toBeNull(); + expect(page.recordings).toEqual([expect.objectContaining({ id: "7", missionName: "Op Paged", worldName: "altis" })]); + }); + + it("continues after a cursor and reads the next one", async () => { + mockPage([raw], { "X-Total-Count": "42", "X-Next-Cursor": "cursor-2" }); + const page = await new ApiClient().getRecordingsPage({ limit: 1, after: "cursor-1" }); + const url = (fetch as ReturnType).mock.calls[0][0] as string; + expect(url).toBe("/api/v1/operations?limit=1&after=cursor-1"); + expect(page.next).toBe("cursor-2"); + }); + + it("sends only the page when no filter is set", async () => { + mockPage([], { "X-Total-Count": "0" }); + await new ApiClient().getRecordingsPage({ limit: 10, offset: 0 }); + const url = (fetch as ReturnType).mock.calls[0][0] as string; + expect(url).toBe("/api/v1/operations?limit=10&offset=0"); + }); + + it("counts the recordings it got when the server sends no total", async () => { + mockPage([raw, raw], {}); + expect((await new ApiClient().getRecordingsPage({ limit: 10, offset: 5 })).total).toBe(7); + mockPage([raw]); + const page = await new ApiClient().getRecordingsPage({ limit: 10 }); + expect(page.total).toBe(1); + expect(page.next).toBeNull(); + }); + + it("redirects to login on 401", async () => { + window.history.replaceState(null, "", "/players"); + mockFetchError(401, "Unauthorized"); + await expect(new ApiClient().getRecordingsPage({ limit: 10, offset: 0 })).rejects.toBeInstanceOf(ApiError); + expect(sessionStorage.getItem("ocap_return_to")).toBe("/players"); + sessionStorage.removeItem("ocap_return_to"); + window.history.replaceState(null, "", "/"); + }); + + it("rethrows other errors without redirecting", async () => { + sessionStorage.removeItem("ocap_return_to"); + mockFetchError(500, "Server Error"); + await expect(new ApiClient().getRecordingsSummary()).rejects.toMatchObject({ status: 500 }); + expect(sessionStorage.getItem("ocap_return_to")).toBeNull(); + }); + }); + + describe("getRecordingsSummary", () => { + it("fetches the summary", async () => { + const summary = { total: 3, worlds: ["altis"], tags: ["TvT"], maxPlayers: 40, totalKills: 12 }; + mockFetchJson(summary); + expect(await new ApiClient("/aar").getRecordingsSummary()).toEqual(summary); + expect(fetch).toHaveBeenCalledWith("/aar/api/v1/operations/summary", expect.anything()); + }); + + it("fills in what the server left out", async () => { + mockFetchJson({}); + expect(await new ApiClient().getRecordingsSummary()).toEqual({ total: 0, worlds: [], tags: [], maxPlayers: 0, totalKills: 0 }); + }); + }); + + describe("searchPlayers", () => { + it("searches by name with a limit", async () => { + const players = [{ name: "Nosey", missions: 3, kills: 5, deaths: 1, lastPlayed: "2026-01-01" }]; + mockFetchJson(players); + expect(await new ApiClient().searchPlayers("no sey", 8)).toEqual(players); + expect(fetch).toHaveBeenCalledWith("/api/v1/players?q=no+sey&limit=8", expect.anything()); + }); + }); + + describe("getPlayerProfile", () => { + const rawProfile = { + name: "Nosey", missions: 1, kills: 1, vehicleKills: 0, teamKills: 0, deaths: 0, + firstPlayed: "2026-01-01", lastPlayed: "2026-01-01", sides: { WEST: 1 }, + recordings: [{ operationId: 9, missionName: "Op", worldName: "altis", date: "2026-01-01", tag: "", filename: "op", missionDuration: 60, name: "Nosey", side: "WEST", role: "", group: "", kills: 1, vehicleKills: 0, teamKills: 0, deaths: 0 }], + }; + + it("fetches a player recorded without a Steam UID by name and turns recording ids into strings", async () => { + mockFetchJson(rawProfile); + const profile = await new ApiClient().getPlayerProfile({ name: "Nosey #1" }); + expect(fetch).toHaveBeenCalledWith("/api/v1/players/profile?name=Nosey+%231", expect.anything()); + expect(profile.recordings[0].operationId).toBe("9"); + expect(profile.sides).toEqual({ WEST: 1 }); + expect(profile.aliases, "a server that sends no aliases means none").toEqual([]); + }); + + it("fetches a player by Steam UID, which wins over the name", async () => { + mockFetchJson({ ...rawProfile, uid: "76561190000000001", aliases: ["Ghost"] }); + const profile = await new ApiClient().getPlayerProfile({ uid: "76561190000000001", name: "Nosey" }); + expect(fetch).toHaveBeenCalledWith("/api/v1/players/profile?uid=76561190000000001", expect.anything()); + expect(profile.uid).toBe("76561190000000001"); + expect(profile.aliases).toEqual(["Ghost"]); + }); + + it("sends an empty name when given neither", async () => { + mockFetchJson(rawProfile); + await new ApiClient().getPlayerProfile({}); + expect(fetch).toHaveBeenCalledWith("/api/v1/players/profile?name=", expect.anything()); + }); + }); + // ─── getSteamLoginUrl ─── describe("getSteamLoginUrl", () => { diff --git a/ui/src/data/__tests__/players.test.ts b/ui/src/data/__tests__/players.test.ts new file mode 100644 index 00000000..6d980f6a --- /dev/null +++ b/ui/src/data/__tests__/players.test.ts @@ -0,0 +1,34 @@ +import { describe, it, expect } from "vitest"; +import { playerKey, playerPath } from "../players"; + +describe("playerKey", () => { + it("keys a player by Steam UID, whatever their name", () => { + expect(playerKey({ uid: "76561190000000001", name: "Nosey" })).toBe("uid:76561190000000001"); + expect(playerKey({ uid: "76561190000000001" })).toBe(playerKey({ uid: "76561190000000001", name: "Ghost" })); + }); + + it("keys a player without a Steam UID by name in any case", () => { + expect(playerKey({ name: " NoSey " })).toBe("name:nosey"); + expect(playerKey({ uid: "", name: "Nosey" })).toBe("name:nosey"); + }); + + it("tells a name that looks like a UID from that player", () => { + expect(playerKey({ name: "76561190000000001" })).not.toBe(playerKey({ uid: "76561190000000001" })); + }); + + it("is empty for neither", () => { + expect(playerKey({})).toBe(""); + expect(playerKey({ name: " " })).toBe(""); + }); +}); + +describe("playerPath", () => { + it("links by Steam UID when there is one", () => { + expect(playerPath({ uid: "76561190000000001", name: "Nosey" })).toBe("/players?uid=76561190000000001"); + }); + + it("links by name otherwise, encoded", () => { + expect(playerPath({ name: "Nosey #1" })).toBe("/players?name=Nosey+%231"); + expect(playerPath({})).toBe("/players?name="); + }); +}); diff --git a/ui/src/data/apiClient.ts b/ui/src/data/apiClient.ts index 85eadd7f..3067167b 100644 --- a/ui/src/data/apiClient.ts +++ b/ui/src/data/apiClient.ts @@ -1,4 +1,14 @@ -import type { Recording, WorldConfig, WorldInfo } from "./types"; +import type { + PlayerMission, + PlayerProfile, + PlayerRef, + PlayerSummary, + Recording, + RecordingPage, + RecordingsSummary, + WorldConfig, + WorldInfo, +} from "./types"; import type { ToolSet, HealthCheck, MapInfo, JobInfo } from "../pages/map-manager/types"; // ─── Response types for endpoints not covered in types.ts ─── @@ -151,6 +161,13 @@ function mapRecording(raw: RawRecording): Recording { }; } +type RawPlayerMission = Omit & { operationId: number }; + +interface RawPlayerProfile extends Omit { + aliases?: string[]; + recordings: RawPlayerMission[]; +} + // ─── Query filter parameters for recordings endpoint ─── export interface RecordingFilters { @@ -160,6 +177,34 @@ export interface RecordingFilters { older?: string; } +export type RecordingSort = "date" | "name" | "duration"; + +/** One page of the recording list, filtered and sorted on the server. */ +export interface RecordingQuery { + /** Mission name, world name or world display name contains. */ + q?: string; + /** Tag contains. */ + tag?: string; + /** Tag equals, in the same case: what a tag chip selects. */ + tagExact?: string; + /** Recorded on one of these worlds. */ + worlds?: string[]; + /** Recordings a player of this in-game name took part in. */ + player?: string; + /** Recordings the player with this Steam UID took part in. */ + playerUid?: string; + sort?: RecordingSort; + dir?: "asc" | "desc"; + limit: number; + /** Matches to skip. */ + offset?: number; + /** + * The `next` of the page before: continues right behind its last + * recording, however the list changed since. + */ + after?: string; +} + // ─── API Client ─── // ─── JWT token store ─── @@ -221,6 +266,75 @@ export class ApiClient { return data.map(mapRecording); } + /** + * Fetch one page of the recording list. + * GET {baseUrl}/api/v1/operations?limit=&after=&... + */ + async getRecordingsPage(query: RecordingQuery): Promise { + const params = new URLSearchParams(); + if (query.q) params.set("q", query.q); + if (query.tag) params.set("tag", query.tag); + if (query.tagExact) params.set("tagExact", query.tagExact); + for (const world of query.worlds ?? []) params.append("world", world); + if (query.player) params.set("player", query.player); + if (query.playerUid) params.set("playerUid", query.playerUid); + if (query.sort) params.set("sort", query.sort); + if (query.dir) params.set("dir", query.dir); + params.set("limit", String(query.limit)); + if (query.offset !== undefined) params.set("offset", String(query.offset)); + if (query.after) params.set("after", query.after); + + const response = await this.fetchViewer(`${this.baseUrl}/api/v1/operations?${params}`); + const recordings = ((await response.json()) as RawRecording[]).map(mapRecording); + // A server without paging answers with every recording, no total and no + // next page. + const total = Number(response.headers?.get("X-Total-Count") ?? NaN); + return { + recordings, + total: Number.isFinite(total) ? total : (query.offset ?? 0) + recordings.length, + next: response.headers?.get("X-Next-Cursor") || null, + }; + } + + /** + * Fetch the totals and filter options of every stored recording. + * GET {baseUrl}/api/v1/operations/summary + */ + async getRecordingsSummary(): Promise { + const raw = await this.fetchJson>(`${this.baseUrl}/api/v1/operations/summary`); + return { + total: raw.total ?? 0, + worlds: raw.worlds ?? [], + tags: raw.tags ?? [], + maxPlayers: raw.maxPlayers ?? 0, + totalKills: raw.totalKills ?? 0, + }; + } + + /** + * Find players by in-game name or exact Steam UID, most active first. + * GET {baseUrl}/api/v1/players?q=&limit= + */ + async searchPlayers(query: string, limit: number): Promise { + const params = new URLSearchParams({ q: query, limit: String(limit) }); + return this.fetchJson(`${this.baseUrl}/api/v1/players?${params}`); + } + + /** + * Fetch a player's record across every indexed recording, by Steam UID when + * the player has one, otherwise by in-game name. + * GET {baseUrl}/api/v1/players/profile?uid= or ?name= + */ + async getPlayerProfile(player: PlayerRef): Promise { + const params = new URLSearchParams(player.uid ? { uid: player.uid } : { name: player.name ?? "" }); + const raw = await this.fetchJson(`${this.baseUrl}/api/v1/players/profile?${params}`); + return { + ...raw, + aliases: raw.aliases ?? [], + recordings: raw.recordings.map((r) => ({ ...r, operationId: String(r.operationId) })), + }; + } + /** * Fetch a single recording by ID or filename. * GET {baseUrl}/api/v1/operations/{id} @@ -670,8 +784,14 @@ export class ApiClient { * graceful login bounce rather than a thrown error. */ private async fetchJson(url: string): Promise { + const response = await this.fetchViewer(url); + return response.json() as Promise; + } + + /** The viewer-flow GET behind fetchJson, for callers that read headers. */ + private async fetchViewer(url: string): Promise { try { - return await this.requestJson(url, { cache: "no-store" }); + return await this.request(url, { cache: "no-store" }); } catch (err) { if (err instanceof ApiError && err.status === 401) { redirectToLogin(); diff --git a/ui/src/data/decoders/__tests__/jsonDecoder.test.ts b/ui/src/data/decoders/__tests__/jsonDecoder.test.ts index 620f9e91..3a5a690f 100644 --- a/ui/src/data/decoders/__tests__/jsonDecoder.test.ts +++ b/ui/src/data/decoders/__tests__/jsonDecoder.test.ts @@ -26,6 +26,27 @@ describe("JsonDecoder.decodeManifest", () => { }]); }); + it("decodes chat with and without its sender and channel", () => { + const manifest = decoder.decodeManifest(toBuffer({ + worldName: "Altis", + missionName: "Chat", + endFrame: 100, + captureDelay: 1, + events: [ + [1, "chat", "contact north", "Nosey", "Side"], + [2, "chat", "legacy copy"], + [3, "chat", "odd sender", 7, null], + [4, "chat", { not: "a message" }], + ], + })); + + expect(manifest.events).toEqual([ + { frameNum: 1, type: "chat", message: "contact north", fromName: "Nosey", channel: "Side" }, + { frameNum: 2, type: "chat", message: "legacy copy", fromName: "", channel: "" }, + { frameNum: 3, type: "chat", message: "odd sender", fromName: "", channel: "" }, + ]); + }); + it("decodes additive server FPS events and rejects malformed samples", () => { const manifest = decoder.decodeManifest(toBuffer({ worldName: "Altis", diff --git a/ui/src/data/decoders/__tests__/protobufDecoder.test.ts b/ui/src/data/decoders/__tests__/protobufDecoder.test.ts index cec1ea3e..4d03dd30 100644 --- a/ui/src/data/decoders/__tests__/protobufDecoder.test.ts +++ b/ui/src/data/decoders/__tests__/protobufDecoder.test.ts @@ -712,6 +712,30 @@ describe("ProtobufDecoder.decodeManifest", () => { } }); + it("decodes converted chat from its JSON fields and skips what a conversion lost", () => { + const buffer = encodePb(PbManifest, { + version: 1, + worldName: "W", + missionName: "M", + endFrame: 100, + chunkSize: 100, + captureDelayMs: 1000, + chunkCount: 1, + events: [ + { frameNum: 1, type: "chat", message: JSON.stringify({ message: "Moving up", fromName: "Nosey", channel: "Side" }) }, + { frameNum: 2, type: "chat", message: JSON.stringify({ message: "contact", fromName: 7, channel: null }) }, + { frameNum: 3, type: "chat", message: "Side" }, + { frameNum: 4, type: "chat", message: "null" }, + { frameNum: 5, type: "chat", message: JSON.stringify({ message: 5 }) }, + ], + }); + + expect(decoder.decodeManifest(buffer).events).toEqual([ + { frameNum: 1, type: "chat", message: "Moving up", fromName: "Nosey", channel: "Side" }, + { frameNum: 2, type: "chat", message: "contact", fromName: "", channel: "" }, + ]); + }); + it("filters out unknown event types", () => { const buffer = encodePb(PbManifest, { version: 1, diff --git a/ui/src/data/decoders/jsonDecoder.ts b/ui/src/data/decoders/jsonDecoder.ts index a53e093c..f9b85333 100644 --- a/ui/src/data/decoders/jsonDecoder.ts +++ b/ui/src/data/decoders/jsonDecoder.ts @@ -305,6 +305,18 @@ function convertEvent(raw: RawJsonEvent): EventDef | null { position: capPos ? [capPos[0], capPos[1]] as [number, number] : undefined, }; } + case "chat": { + // [frameNum, "chat", message, fromName, channel]; copies written before + // the sender was added end at the message. + if (typeof raw[2] !== "string") return null; + return { + frameNum, + type, + message: raw[2], + fromName: typeof raw[3] === "string" ? raw[3] : "", + channel: typeof raw[4] === "string" ? raw[4] : "", + }; + } case "terminalHackStarted": case "terminalHackCanceled": { // [frameNum, type, [unitName, unitColor, terminalColor, terminalID, ...]] diff --git a/ui/src/data/decoders/protobufDecoder.ts b/ui/src/data/decoders/protobufDecoder.ts index 7c60310d..a7daae2f 100644 --- a/ui/src/data/decoders/protobufDecoder.ts +++ b/ui/src/data/decoders/protobufDecoder.ts @@ -285,6 +285,23 @@ export function convertEvent(pb: PbEvent): EventDef | null { case "terminalHackStarted": case "terminalHackCanceled": return { frameNum, type, unitName: pb.message }; + case "chat": { + // Conversion carries the fields as JSON. Recordings converted before it + // did hold only the channel and are skipped. + try { + const payload = JSON.parse(pb.message) as { message?: unknown; fromName?: unknown; channel?: unknown } | null; + if (!payload || typeof payload.message !== "string") return null; + return { + frameNum, + type, + message: payload.message, + fromName: typeof payload.fromName === "string" ? payload.fromName : "", + channel: typeof payload.channel === "string" ? payload.channel : "", + }; + } catch { + return null; + } + } default: return null; } diff --git a/ui/src/data/players.ts b/ui/src/data/players.ts new file mode 100644 index 00000000..6ba4db93 --- /dev/null +++ b/ui/src/data/players.ts @@ -0,0 +1,20 @@ +import type { PlayerRef } from "./types"; + +/** + * One key per player, telling them apart the way the server does: by Steam UID + * when they have one, otherwise by name in any case. Empty for neither. + */ +export function playerKey(player: PlayerRef): string { + if (player.uid) return `uid:${player.uid}`; + const name = player.name?.trim().toLowerCase(); + return name ? `name:${name}` : ""; +} + +/** + * The link to a player's profile: by Steam UID when they have one, otherwise + * by name. + */ +export function playerPath(player: PlayerRef): string { + const params = new URLSearchParams(player.uid ? { uid: player.uid } : { name: player.name ?? "" }); + return `/players?${params}`; +} diff --git a/ui/src/data/types.ts b/ui/src/data/types.ts index 7e255205..2502b06d 100644 --- a/ui/src/data/types.ts +++ b/ui/src/data/types.ts @@ -683,6 +683,84 @@ export interface Recording { focusEnd?: number; } +/** One page of the recording list and the number of matches across all pages. */ +export interface RecordingPage { + recordings: Recording[]; + total: number; + /** Continues behind this page, as RecordingQuery.after; null on the last. */ + next: string | null; +} + +/** Every stored recording at a glance, for the list header and filters. */ +export interface RecordingsSummary { + total: number; + worlds: string[]; + tags: string[]; + maxPlayers: number; + totalKills: number; +} + +/** + * Identifies a player: by Steam UID when their recordings have one, otherwise + * by in-game name. + */ +export interface PlayerRef { + uid?: string; + name?: string; +} + +/** + * A player in a search result. `uid` is the Steam UID, absent for a player + * recorded without one; `name` is the one used in their latest recording. + */ +export interface PlayerSummary { + uid?: string; + name: string; + missions: number; + kills: number; + deaths: number; + lastPlayed: string; +} + +/** A player's part in one recording. */ +export interface PlayerMission { + operationId: string; + missionName: string; + worldName: string; + date: string; + tag: string; + filename: string; + missionDuration: number; + name: string; + side: string; + role: string; + group: string; + kills: number; + vehicleKills: number; + teamKills: number; + deaths: number; +} + +/** A player's record across every indexed recording, newest recording first. */ +export interface PlayerProfile { + /** Steam UID, absent for a player recorded without one. */ + uid?: string; + /** The name used in the latest recording. */ + name: string; + /** Other names the player used, newest first. */ + aliases: string[]; + missions: number; + kills: number; + vehicleKills: number; + teamKills: number; + deaths: number; + firstPlayed: string; + lastPlayed: string; + /** Recordings played per side. */ + sides: Record; + recordings: PlayerMission[]; +} + /** Per-world map configuration (from map.json). */ export interface WorldConfig { worldName: string; diff --git a/ui/src/i18n/locales.ts b/ui/src/i18n/locales.ts index 12b1e1df..42e67948 100644 --- a/ui/src/i18n/locales.ts +++ b/ui/src/i18n/locales.ts @@ -3630,4 +3630,40 @@ export const translations: Record> = { fps_counts_failed: { en: "Unit and vehicle counts could not be loaded.", ru: "Не удалось подсчитать юнитов и технику.", de: "Einheiten und Fahrzeuge konnten nicht gezählt werden.", cs: "Počty jednotek a vozidel se nepodařilo načíst.", it: "Impossibile caricare il conteggio di unità e veicoli.", fr: "Impossible de charger le nombre d'unités et de véhicules.", fi: "Yksiköiden ja ajoneuvojen määrää ei voitu ladata.", uk: "Не вдалося підрахувати юнітів і техніку." }, fps_chart_fps: { en: "Server FPS over the mission", ru: "FPS сервера за миссию", de: "Server-FPS im Missionsverlauf", cs: "FPS serveru během mise", it: "FPS server durante la missione", fr: "FPS serveur au fil de la mission", fi: "Palvelimen FPS tehtävän aikana", uk: "FPS сервера протягом місії" }, fps_chart_population: { en: "Alive units and vehicles over the mission", ru: "Живые юниты и техника за миссию", de: "Lebende Einheiten und Fahrzeuge im Missionsverlauf", cs: "Živé jednotky a vozidla během mise", it: "Unità e veicoli attivi durante la missione", fr: "Unités et véhicules en vie au fil de la mission", fi: "Elossa olevat yksiköt ja ajoneuvot tehtävän aikana", uk: "Живі юніти й техніка протягом місії" }, + + // ─── Chat tab ─── + search_chat: { en: "Search chat...", ru: "Поиск в чате...", de: "Chat durchsuchen...", cs: "Hledat v chatu...", it: "Cerca nella chat...", fr: "Rechercher dans le chat...", fi: "Hae chatista...", uk: "Пошук у чаті..." }, + no_chat_messages: { en: "No chat messages up to this point", ru: "К этому моменту сообщений нет", de: "Bis hierhin keine Chat-Nachrichten", cs: "Do této chvíle žádné zprávy", it: "Nessun messaggio fino a questo punto", fr: "Aucun message jusqu'ici", fi: "Ei viestejä tähän kohtaan mennessä", uk: "До цього моменту повідомлень немає" }, + chat_system: { en: "System", ru: "Система", de: "System", cs: "Systém", it: "Sistema", fr: "Système", fi: "Järjestelmä", uk: "Система" }, + all: { en: "All", ru: "Все", de: "Alle", cs: "Vše", it: "Tutti", fr: "Tous", fi: "Kaikki", uk: "Усі" }, + + // ─── Recording list paging ─── + loading_more: { en: "Loading more...", ru: "Загрузка...", de: "Weitere werden geladen...", cs: "Načítání dalších...", it: "Caricamento...", fr: "Chargement...", fi: "Ladataan lisää...", uk: "Завантаження..." }, + load_more_failed: { en: "Could not load more recordings.", ru: "Не удалось загрузить остальные записи.", de: "Weitere Aufnahmen konnten nicht geladen werden.", cs: "Další záznamy se nepodařilo načíst.", it: "Impossibile caricare altre registrazioni.", fr: "Impossible de charger plus d'enregistrements.", fi: "Lisää tallenteita ei voitu ladata.", uk: "Не вдалося завантажити решту записів." }, + + // ─── Player search and profiles ─── + players_title: { en: "Players", ru: "Игроки", de: "Spieler", cs: "Hráči", it: "Giocatori", fr: "Joueurs", fi: "Pelaajat", uk: "Гравці" }, + players_button: { en: "Player profiles", ru: "Профили игроков", de: "Spielerprofile", cs: "Profily hráčů", it: "Profili giocatori", fr: "Profils des joueurs", fi: "Pelaajaprofiilit", uk: "Профілі гравців" }, + players_search_placeholder: { en: "Search players by name...", ru: "Поиск игрока по имени...", de: "Spieler nach Namen suchen...", cs: "Hledat hráče podle jména...", it: "Cerca giocatori per nome...", fr: "Rechercher un joueur par nom...", fi: "Hae pelaajia nimellä...", uk: "Пошук гравця за іменем..." }, + players_top: { en: "Most active players", ru: "Самые активные игроки", de: "Aktivste Spieler", cs: "Nejaktivnější hráči", it: "Giocatori più attivi", fr: "Joueurs les plus actifs", fi: "Aktiivisimmat pelaajat", uk: "Найактивніші гравці" }, + players_none: { en: "No players found", ru: "Игроки не найдены", de: "Keine Spieler gefunden", cs: "Žádní hráči nenalezeni", it: "Nessun giocatore trovato", fr: "Aucun joueur trouvé", fi: "Pelaajia ei löytynyt", uk: "Гравців не знайдено" }, + players_select_hint: { en: "Pick a player to see their profile", ru: "Выберите игрока, чтобы открыть профиль", de: "Wähle einen Spieler, um sein Profil zu sehen", cs: "Vyberte hráče pro zobrazení profilu", it: "Scegli un giocatore per vederne il profilo", fr: "Choisissez un joueur pour voir son profil", fi: "Valitse pelaaja nähdäksesi profiilin", uk: "Оберіть гравця, щоб відкрити профіль" }, + players_missions_count: { en: "{count} missions", ru: "миссий: {count}", de: "{count} Missionen", cs: "{count} misí", it: "{count} missioni", fr: "{count} missions", fi: "{count} tehtävää", uk: "місій: {count}" }, + player_not_found: { en: "This player is in no indexed recording", ru: "Игрок не найден ни в одной записи", de: "Dieser Spieler ist in keiner indizierten Aufnahme", cs: "Hráč není v žádném indexovaném záznamu", it: "Questo giocatore non è in nessuna registrazione indicizzata", fr: "Ce joueur n'apparaît dans aucun enregistrement indexé", fi: "Pelaajaa ei ole yhdessäkään indeksoidussa tallenteessa", uk: "Гравця немає в жодному індексованому записі" }, + player_steam_id: { en: "Steam ID", ru: "Steam ID", de: "Steam-ID", cs: "Steam ID", it: "Steam ID", fr: "Steam ID", fi: "Steam-tunnus", uk: "Steam ID" }, + player_no_steam_id: { en: "no Steam ID", ru: "без Steam ID", de: "ohne Steam-ID", cs: "bez Steam ID", it: "senza Steam ID", fr: "sans Steam ID", fi: "ei Steam-tunnusta", uk: "без Steam ID" }, + player_matched_by_name: { en: "Recorded without a Steam ID, so matched by in-game name", ru: "Записан без Steam ID, поэтому сопоставлен по игровому имени", de: "Ohne Steam-ID aufgezeichnet, daher nach Spielernamen zugeordnet", cs: "Nahráno bez Steam ID, proto přiřazeno podle herního jména", it: "Registrato senza Steam ID, quindi associato per nome in gioco", fr: "Enregistré sans Steam ID, donc associé par nom en jeu", fi: "Tallennettu ilman Steam-tunnusta, joten yhdistetty pelinimen perusteella", uk: "Записано без Steam ID, тому зіставлено за ігровим ім'ям" }, + player_other_names: { en: "Other names", ru: "Другие имена", de: "Weitere Namen", cs: "Další jména", it: "Altri nomi", fr: "Autres noms", fi: "Muut nimet", uk: "Інші імена" }, + player_load_failed: { en: "Could not load this player", ru: "Не удалось загрузить игрока", de: "Spieler konnte nicht geladen werden", cs: "Hráče se nepodařilo načíst", it: "Impossibile caricare il giocatore", fr: "Impossible de charger ce joueur", fi: "Pelaajaa ei voitu ladata", uk: "Не вдалося завантажити гравця" }, + player_missions: { en: "Missions", ru: "Миссии", de: "Missionen", cs: "Mise", it: "Missioni", fr: "Missions", fi: "Tehtävät", uk: "Місії" }, + player_kd: { en: "K/D", ru: "У/С", de: "K/D", cs: "K/D", it: "K/D", fr: "K/D", fi: "K/D", uk: "В/С" }, + player_vehicle_kills: { en: "Vehicle kills", ru: "Уничтожено техники", de: "Fahrzeugabschüsse", cs: "Zničená vozidla", it: "Veicoli distrutti", fr: "Véhicules détruits", fi: "Tuhotut ajoneuvot", uk: "Знищено техніки" }, + player_team_kills: { en: "Team kills", ru: "Убийства своих", de: "Teamkills", cs: "Zabití spojenců", it: "Uccisioni alleate", fr: "Tirs fratricides", fi: "Omien tapot", uk: "Вбивства своїх" }, + player_first_played: { en: "First played", ru: "Впервые", de: "Zuerst gespielt", cs: "Poprvé", it: "Prima partita", fr: "Première partie", fi: "Ensimmäinen peli", uk: "Уперше" }, + player_last_played: { en: "Last played", ru: "Последний раз", de: "Zuletzt gespielt", cs: "Naposledy", it: "Ultima partita", fr: "Dernière partie", fi: "Viimeisin peli", uk: "Востаннє" }, + player_sides: { en: "Sides played", ru: "Стороны", de: "Gespielte Seiten", cs: "Hrané strany", it: "Fazioni giocate", fr: "Camps joués", fi: "Pelatut puolet", uk: "Сторони" }, + player_recordings: { en: "Recordings", ru: "Записи", de: "Aufnahmen", cs: "Záznamy", it: "Registrazioni", fr: "Enregistrements", fi: "Tallenteet", uk: "Записи" }, + player_role: { en: "Role", ru: "Роль", de: "Rolle", cs: "Role", it: "Ruolo", fr: "Rôle", fi: "Rooli", uk: "Роль" }, + player_side: { en: "Side", ru: "Сторона", de: "Seite", cs: "Strana", it: "Fazione", fr: "Camp", fi: "Puoli", uk: "Сторона" }, + player_open_recording: { en: "Open recording", ru: "Открыть запись", de: "Aufnahme öffnen", cs: "Otevřít záznam", it: "Apri registrazione", fr: "Ouvrir l'enregistrement", fi: "Avaa tallenne", uk: "Відкрити запис" }, }; diff --git a/ui/src/main.tsx b/ui/src/main.tsx index d9317c10..48d2a30a 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -5,6 +5,7 @@ import { RecordingSelector } from "./pages/recording-selector"; import { RecordingPlayback } from "./pages/recording-playback"; import { MapManager } from "./pages/map-manager"; import { AdminPage } from "./pages/admin/AdminPage"; +import { PlayersPage } from "./pages/players"; import { basePath } from "./data/basePath"; // Strip trailing slash for Router base prop (Router expects no trailing slash). @@ -19,6 +20,7 @@ if (root) { + ), root, diff --git a/ui/src/pages/players/PlayersPage.module.css b/ui/src/pages/players/PlayersPage.module.css new file mode 100644 index 00000000..28e854cc --- /dev/null +++ b/ui/src/pages/players/PlayersPage.module.css @@ -0,0 +1,309 @@ +/* ─── Layout ─── */ + +.page { + width: 100%; + height: 100vh; + background: var(--bg-dark); + color: var(--text-primary); + font-family: var(--font-heading); + display: flex; + flex-direction: column; +} + +.header { + display: flex; + align-items: center; + gap: 10px; + padding: 14px 24px 12px; + flex-shrink: 0; + border-bottom: var(--border-subtle); + color: var(--text-muted); +} + +.backBtn { + width: 32px; + height: 32px; + border-radius: var(--radius-md); + background: var(--bg-interactive); + border: var(--border-subtle); + color: var(--text-muted); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: filter 0.15s ease; +} + +.backBtn:hover { + filter: brightness(1.15); +} + +.title { + margin: 0; + font-size: 18px; + font-weight: 700; + color: var(--text-primary); +} + +.body { + flex: 1; + display: flex; + min-height: 0; +} + +/* ─── Player list ─── */ + +.listPane { + width: 300px; + flex-shrink: 0; + border-right: var(--border-subtle); + display: flex; + flex-direction: column; + min-height: 0; +} + +.searchWrap { + position: relative; + display: flex; + align-items: center; + margin: 12px; +} + +.searchIcon { + position: absolute; + left: 10px; + color: var(--text-dimmer); + display: flex; +} + +.searchInput { + width: 100%; + padding: 8px 10px 8px 32px; + border-radius: 6px; + border: var(--border-subtle); + background: var(--bg-interactive); + color: var(--text-primary); + font-size: 13px; + outline: none; +} + +.searchInput:focus { + border-color: color-mix(in srgb, var(--accent-primary) 50%, transparent); +} + +.listTitle, +.sectionTitle { + padding: 4px 14px; + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--text-dimmer); +} + +.list { + list-style: none; + margin: 0; + padding: 4px 8px 16px; + overflow-y: auto; +} + +.listItem { + width: 100%; + display: flex; + flex-direction: column; + gap: 2px; + padding: 8px 10px; + border: 1px solid transparent; + border-radius: 6px; + background: transparent; + color: var(--text-secondary); + text-align: left; + cursor: pointer; +} + +.listItem:hover { + background: var(--bg-interactive); +} + +.listItemActive { + background: color-mix(in srgb, var(--accent-primary) 12%, transparent); + border-color: color-mix(in srgb, var(--accent-primary) 30%, transparent); + color: var(--text-primary); +} + +.listName { + font-size: 13px; + font-weight: 600; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.listMeta { + font-family: var(--font-mono); + font-size: 10px; + color: var(--text-dimmer); +} + +/* Marks a player recorded without a Steam UID, matched by name instead. */ +.listTag { + margin-left: 6px; + font-family: var(--font-body); + color: var(--text-dimmest); +} + +.hint { + padding: 24px; + text-align: center; + font-family: var(--font-mono); + font-size: 12px; + color: var(--text-dimmer); +} + +/* ─── Profile ─── */ + +.profilePane { + flex: 1; + overflow-y: auto; + min-width: 0; +} + +.profile { + max-width: 1000px; + padding: 24px 28px 60px; + display: flex; + flex-direction: column; + gap: 14px; +} + +.profileHeader { + display: flex; + flex-direction: column; + gap: 4px; +} + +.profileName { + margin: 0; + font-size: 24px; + font-weight: 700; +} + +.profileDates { + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-dim); +} + +.profileIdentity { + font-size: 11px; + color: var(--text-dim); +} + +.uid { + font-family: var(--font-mono); + color: var(--text-muted); + user-select: all; +} + +.stats { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); + gap: 8px; +} + +.stat { + display: flex; + flex-direction: column; + gap: 2px; + padding: 12px 14px; + border-radius: 8px; + border: var(--border-subtle); + background: var(--bg-surface); +} + +.statValue { + font-family: var(--font-mono); + font-size: 22px; + font-weight: 700; +} + +.statLabel { + font-size: 11px; + color: var(--text-dim); +} + +.sectionTitle { + padding: 6px 0 0; +} + +.sides { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.side { + padding: 3px 8px; + border: 1px solid; + border-radius: 4px; + font-family: var(--font-mono); + font-size: 11px; + font-weight: 600; +} + +.table { + width: 100%; + border-collapse: collapse; + font-size: 12px; +} + +.table th { + text-align: left; + padding: 6px 8px; + font-family: var(--font-mono); + font-size: 10px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--text-dimmer); + border-bottom: var(--border-subtle); +} + +.table td { + padding: 8px; + border-bottom: 1px solid rgba(255, 255, 255, 0.04); + color: var(--text-secondary); +} + +.row { + cursor: pointer; +} + +.row:hover td { + background: var(--bg-interactive); + color: var(--text-primary); +} + +.num { + text-align: right; + font-family: var(--font-mono); +} + +.mono { + font-family: var(--font-mono); + white-space: nowrap; +} + +@media (max-width: 768px) { + .body { + flex-direction: column; + } + + .listPane { + width: 100%; + max-height: 40vh; + border-right: none; + border-bottom: var(--border-subtle); + } +} diff --git a/ui/src/pages/players/PlayersPage.tsx b/ui/src/pages/players/PlayersPage.tsx new file mode 100644 index 00000000..2a5cf7fc --- /dev/null +++ b/ui/src/pages/players/PlayersPage.tsx @@ -0,0 +1,286 @@ +import { createEffect, createSignal, For, Match, Show, Switch, on, onCleanup, onMount } from "solid-js"; +import type { JSX } from "solid-js"; +import { useNavigate, useSearchParams } from "@solidjs/router"; +import { ApiClient, ApiError } from "../../data/apiClient"; +import { playerKey } from "../../data/players"; +import type { PlayerMission, PlayerProfile, PlayerRef, PlayerSummary, Side } from "../../data/types"; +import { useI18n } from "../../hooks/useLocale"; +import { SIDE_COLORS_UI, SIDE_LABELS } from "../../config/sideColors"; +import { ArrowLeftIcon, SearchIcon, UsersIcon } from "../../components/Icons"; +import styles from "./PlayersPage.module.css"; + +/** Wait for typing to pause before searching on the server. */ +export const PLAYER_SEARCH_DEBOUNCE_MS = 250; +/** Players listed at once. */ +const PLAYER_RESULTS = 50; + +type ProfileState = + | { status: "loading" } + | { status: "ready"; profile: PlayerProfile } + | { status: "missing" } + | { status: "failed" }; + +/** The colour of a side, or a neutral one for anything else. */ +function sideColor(side: string): string { + return SIDE_COLORS_UI[side as Side] ?? "var(--text-dim)"; +} + +/** The faction name of a side, or the side id itself. */ +function sideLabel(side: string): string { + return SIDE_LABELS[side as Side] ?? side; +} + +/** Kills per death, counting no deaths as one. */ +export function killDeathRatio(kills: number, deaths: number): string { + return (kills / Math.max(deaths, 1)).toFixed(2); +} + +/** + * Player search and profiles across every indexed recording. The selected + * player lives in the `uid` query parameter, or `name` for a player recorded + * without a Steam UID, so a profile can be linked. + */ +export function PlayersPage(): JSX.Element { + const { t } = useI18n(); + const navigate = useNavigate(); + const [params, setParams] = useSearchParams(); + const api = new ApiClient(); + + const [search, setSearch] = createSignal(""); + const [query, setQuery] = createSignal(""); + // Results and profiles are kept per query and per player, so a response + // that arrives after the user moved on only fills its own entry. + const [results, setResults] = createSignal>({}); + const [profiles, setProfiles] = createSignal>({}); + const [worldNames, setWorldNames] = createSignal(new Map()); + + const param = (value: string | string[] | undefined): string | undefined => (typeof value === "string" ? value : undefined); + const selected = (): PlayerRef => ({ uid: param(params.uid), name: param(params.name) }); + const selectedKey = () => playerKey(selected()); + const players = () => results()[query()]; + const profile = () => profiles()[selectedKey()]; + const readyProfile = () => { + const state = profile(); + return state?.status === "ready" ? state.profile : undefined; + }; + + onMount(() => { + void api.getWorlds().catch(() => []).then((worlds) => { + setWorldNames(new Map(worlds.map((w) => [w.name, w.displayName]))); + }); + }); + + createEffect(on(query, (q) => { + void api.searchPlayers(q, PLAYER_RESULTS).catch(() => []).then((found) => { + setResults((r) => ({ ...r, [q]: found })); + }); + })); + + createEffect(on(selectedKey, (key) => { + if (!key) return; + setProfiles((p) => ({ ...p, [key]: { status: "loading" } })); + void api.getPlayerProfile(selected()).then( + (loaded): ProfileState => ({ status: "ready", profile: loaded }), + (err): ProfileState => ({ status: err instanceof ApiError && err.status === 404 ? "missing" : "failed" }), + ).then((state) => { + setProfiles((p) => ({ ...p, [key]: state })); + }); + })); + + let searchTimer: ReturnType | undefined; + const updateSearch = (value: string) => { + setSearch(value); + clearTimeout(searchTimer); + searchTimer = setTimeout(() => setQuery(value.trim()), PLAYER_SEARCH_DEBOUNCE_MS); + }; + onCleanup(() => clearTimeout(searchTimer)); + + const openRecording = (mission: PlayerMission) => { + navigate(`/recording/${encodeURIComponent(mission.operationId)}/${encodeURIComponent(mission.filename)}`, { + state: { + missionName: mission.missionName, + worldName: mission.worldName, + missionDuration: mission.missionDuration, + }, + }); + }; + + const worldName = (name: string) => worldNames().get(name) ?? name; + + return ( +
+
+ + +

{t("players_title")}

+
+ +
+
}> + {(found) => ( + 0} fallback={
{t("players_none")}
}> +
    + + {(player) => ( +
  • + +
  • + )} +
    +
+
+ )} + + + +
+ {t("players_select_hint")}
}> + +
{t("loading")}
+
+ +
{t("player_not_found")}
+
+ +
{t("player_load_failed")}
+
+ + {(p) => } + + + + + + ); +} + +function ProfileView(props: { + profile: PlayerProfile; + worldName: (name: string) => string; + onOpen: (mission: PlayerMission) => void; +}): JSX.Element { + const { t } = useI18n(); + const sides = () => Object.entries(props.profile.sides).sort((a, b) => b[1] - a[1]); + const stats = () => [ + { label: t("player_missions"), value: String(props.profile.missions) }, + { label: t("profile_kills"), value: String(props.profile.kills) }, + { label: t("profile_deaths"), value: String(props.profile.deaths) }, + { label: t("player_kd"), value: killDeathRatio(props.profile.kills, props.profile.deaths) }, + { label: t("player_vehicle_kills"), value: String(props.profile.vehicleKills) }, + { label: t("player_team_kills"), value: String(props.profile.teamKills) }, + ]; + + return ( +
+
+

{props.profile.name}

+
+ + {(uid) => ( + <> + {t("player_steam_id")} {uid()} + + )} + +
+ 0}> +
+ {t("player_other_names")}: {props.profile.aliases.join(", ")} +
+
+
+ {t("player_first_played")} {props.profile.firstPlayed} · {t("player_last_played")} {props.profile.lastPlayed} +
+
+ +
+ + {(stat) => ( +
+ {stat.value} + {stat.label} +
+ )} +
+
+ + 0}> +
{t("player_sides")}
+
+ + {([side, count]) => ( + + {sideLabel(side)} · {count} + + )} + +
+
+ +
{t("player_recordings")}
+ + + + + + + + + + + + + + + {(mission) => ( + props.onOpen(mission)} + > + + + + + + + + + )} + + +
{t("date")}{t("recording")}{t("map")}{t("player_side")}{t("player_role")}{t("profile_kills")}{t("profile_deaths")}
{mission.date}{mission.missionName}{props.worldName(mission.worldName)}{mission.side ? sideLabel(mission.side) : ""}{mission.role}{mission.kills}{mission.deaths}
+
+ ); +} diff --git a/ui/src/pages/players/__tests__/PlayersPage.test.tsx b/ui/src/pages/players/__tests__/PlayersPage.test.tsx new file mode 100644 index 00000000..13573353 --- /dev/null +++ b/ui/src/pages/players/__tests__/PlayersPage.test.tsx @@ -0,0 +1,250 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { render, cleanup, fireEvent, screen, within } from "@solidjs/testing-library"; +import { Router, Route, useLocation } from "@solidjs/router"; +import { I18nProvider } from "../../../hooks/useLocale"; +import { PlayersPage } from ".."; +import { PLAYER_SEARCH_DEBOUNCE_MS, killDeathRatio } from "../PlayersPage"; +import type { PlayerProfile, PlayerSummary } from "../../../data/types"; + +const VIPER_UID = "76561190000000005"; + +const players: PlayerSummary[] = [ + { name: "Nosey", missions: 3, kills: 5, deaths: 1, lastPlayed: "2024-05-01" }, + { name: "Nomad", missions: 1, kills: 0, deaths: 2, lastPlayed: "2024-04-01" }, + { uid: VIPER_UID, name: "Viper", missions: 2, kills: 4, deaths: 0, lastPlayed: "2024-06-01" }, +]; + +const profile: PlayerProfile = { + name: "Nosey", + aliases: [], + missions: 3, + kills: 5, + vehicleKills: 1, + teamKills: 1, + deaths: 2, + firstPlayed: "2024-01-01", + lastPlayed: "2024-05-01", + sides: { WEST: 2, LOGIC: 1 }, + recordings: [ + { operationId: "7", missionName: "Op Thunder", worldName: "altis", date: "2024-05-01", tag: "TvT", filename: "op_thunder", missionDuration: 3600, name: "Nosey", side: "WEST", role: "Rifleman", group: "Alpha", kills: 3, vehicleKills: 1, teamKills: 0, deaths: 1 }, + { operationId: "8", missionName: "Op Zeus", worldName: "stratis", date: "2024-01-01", tag: "", filename: "op_zeus", missionDuration: 600, name: "Nosey", side: "", role: "", group: "", kills: 0, vehicleKills: 0, teamKills: 0, deaths: 0 }, + ], +}; + +const viperProfile: PlayerProfile = { + ...profile, + uid: VIPER_UID, + name: "Viper", + aliases: ["Ghost", "V1per"], + recordings: [{ ...profile.recordings[0], operationId: "9", name: "Viper" }], +}; + +function json(data: unknown, status = 200): Response { + return { + ok: status < 300, status, statusText: status < 300 ? "OK" : "Error", + json: () => Promise.resolve(data), + text: () => Promise.resolve(""), + } as unknown as Response; +} + +interface ServerOptions { + /** Answers a URL before the defaults do; undefined falls through. */ + route?: (url: URL) => Promise | undefined; +} + +function mockServer(options: ServerOptions = {}) { + globalThis.fetch = vi.fn().mockImplementation((input: RequestInfo | URL) => { + const url = new URL(String(input), "http://localhost"); + const routed = options.route?.(url); + if (routed) return routed; + switch (url.pathname) { + case "/api/v1/players": { + const q = (url.searchParams.get("q") ?? "").toLowerCase(); + return Promise.resolve(json(players.filter((p) => p.name.toLowerCase().includes(q)))); + } + case "/api/v1/players/profile": + if (url.searchParams.get("uid") === VIPER_UID) return Promise.resolve(json(viperProfile)); + return Promise.resolve(url.searchParams.get("name") === "Nosey" ? json(profile) : json({ detail: "player not found" }, 404)); + case "/api/v1/worlds": + return Promise.resolve(json([{ name: "altis", displayName: "Altis Island" }])); + default: + return Promise.resolve(json({})); + } + }); +} + +function requests(pathname: string): URL[] { + return (globalThis.fetch as ReturnType).mock.calls + .map(([input]) => new URL(String(input), "http://localhost")) + .filter((url) => url.pathname === pathname); +} + +function RouteStub() { + const location = useLocation(); + const state = () => location.state as { missionName?: string } | undefined; + return
{location.pathname} {state()?.missionName}
; +} + +function renderPage(path = "/players") { + window.history.replaceState(null, "", path); + return render(() => ( + {p.children}}> + + + + + )); +} + +describe("PlayersPage", () => { + beforeEach(() => mockServer()); + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + window.history.replaceState(null, "", "/"); + }); + + it("lists the most active players before a search", async () => { + renderPage(); + expect(screen.getByText("Most active players")).toBeDefined(); + expect(screen.getByText("Pick a player to see their profile")).toBeDefined(); + const nosey = await screen.findByTestId("player-Nosey"); + expect(nosey.textContent).toContain("3 missions · 5/1"); + expect(requests("/api/v1/players")[0].searchParams.get("limit")).toBe("50"); + }); + + it("marks the players recorded without a Steam UID", async () => { + renderPage(); + expect((await screen.findByTestId("player-Nosey")).textContent).toContain("no Steam ID"); + expect(screen.getByTestId(`player-${VIPER_UID}`).textContent).not.toContain("no Steam ID"); + }); + + it("links a player with a Steam UID by it and shows their other names", async () => { + renderPage(); + fireEvent.click(await screen.findByTestId(`player-${VIPER_UID}`)); + const card = await screen.findByTestId("player-profile"); + expect(window.location.search).toBe(`?uid=${VIPER_UID}`); + expect(screen.getByTestId(`player-${VIPER_UID}`).className).toContain("listItemActive"); + expect(screen.getByTestId("player-Nosey").className).not.toContain("listItemActive"); + expect(within(card).getByRole("heading", { name: "Viper" })).toBeDefined(); + expect(screen.getByTestId("player-identity").textContent).toBe(`Steam ID ${VIPER_UID}`); + expect(screen.getByTestId("player-aliases").textContent).toBe("Other names: Ghost, V1per"); + expect(requests("/api/v1/players/profile")[0].searchParams.get("uid")).toBe(VIPER_UID); + + // A player without a UID replaces the uid in the link with their name. + fireEvent.click(screen.getByTestId("player-Nosey")); + await vi.waitFor(() => expect(window.location.search).toBe("?name=Nosey")); + expect(await screen.findByText("Recorded without a Steam ID, so matched by in-game name")).toBeDefined(); + expect(screen.queryByTestId("player-aliases")).toBeNull(); + }); + + it("opens a linked Steam UID even when it is not in the list", async () => { + mockServer({ route: (url) => (url.pathname === "/api/v1/players" ? Promise.resolve(json([])) : undefined) }); + renderPage(`/players?uid=${VIPER_UID}&name=ignored`); + expect(await screen.findByTestId("player-profile")).toBeDefined(); + expect(requests("/api/v1/players/profile")[0].searchParams.toString()).toBe(`uid=${VIPER_UID}`); + }); + + it("searches by name once typing pauses", async () => { + renderPage(); + await screen.findByTestId("player-Nomad"); + fireEvent.input(screen.getByTestId("players-search"), { target: { value: " nos " } }); + await vi.waitFor(() => expect(screen.queryByTestId("player-Nomad")).toBeNull(), { timeout: PLAYER_SEARCH_DEBOUNCE_MS + 1000 }); + expect(screen.getByTestId("player-Nosey")).toBeDefined(); + expect(screen.queryByText("Most active players")).toBeNull(); + const searches = requests("/api/v1/players"); + expect(searches[searches.length - 1].searchParams.get("q")).toBe("nos"); + }); + + it("says when no player matches, also when the search fails", async () => { + mockServer({ route: (url) => (url.searchParams.get("q") === "broken" ? Promise.resolve(json({}, 500)) : undefined) }); + renderPage(); + await screen.findByTestId("player-Nosey"); + fireEvent.input(screen.getByTestId("players-search"), { target: { value: "zzz" } }); + expect(await screen.findByText("No players found", undefined, { timeout: 1500 })).toBeDefined(); + fireEvent.input(screen.getByTestId("players-search"), { target: { value: "broken" } }); + await vi.waitFor(() => expect(requests("/api/v1/players").some((u) => u.searchParams.get("q") === "broken")).toBe(true), { timeout: 1500 }); + expect(await screen.findByText("No players found")).toBeDefined(); + }); + + it("shows a player's profile and links it", async () => { + renderPage(); + fireEvent.click(await screen.findByTestId("player-Nosey")); + const card = await screen.findByTestId("player-profile"); + expect(window.location.search).toBe("?name=Nosey"); + expect(screen.getByTestId("player-Nosey").className).toContain("listItemActive"); + + expect(within(card).getByRole("heading", { name: "Nosey" })).toBeDefined(); + expect(card.textContent).toContain("First played 2024-01-01 · Last played 2024-05-01"); + for (const [label, value] of [["Missions", "3"], ["Kills", "5"], ["Deaths", "2"], ["K/D", "2.50"], ["Vehicle kills", "1"], ["Team kills", "1"]]) { + const tile = within(card).getAllByText(label).map((el) => el.parentElement!).find((el) => el.textContent === value + label); + expect(tile, label).toBeDefined(); + } + expect(card.textContent).toContain("BLUFOR · 2"); + expect(card.textContent).toContain("LOGIC · 1"); + + const thunder = screen.getByTestId("player-recording-7"); + expect(thunder.textContent).toContain("Altis Island"); + expect(thunder.textContent).toContain("BLUFOR"); + expect(thunder.textContent).toContain("Rifleman"); + expect(screen.getByTestId("player-recording-8").textContent).toContain("stratis"); + }); + + it("opens a recording from the profile", async () => { + renderPage("/players?name=Nosey"); + fireEvent.click(await screen.findByTestId("player-recording-7")); + expect((await screen.findByTestId("route-stub")).textContent).toBe("/recording/7/op_thunder Op Thunder"); + }); + + it("hides the sides of a player who never had one", async () => { + mockServer({ + route: (url) => (url.pathname === "/api/v1/players/profile" ? Promise.resolve(json({ ...profile, sides: {} })) : undefined), + }); + renderPage("/players?name=Nosey"); + const card = await screen.findByTestId("player-profile"); + expect(card.textContent).not.toContain("Sides played"); + }); + + it("explains a player without indexed recordings", async () => { + renderPage("/players?name=Ghost"); + expect(await screen.findByTestId("player-missing")).toBeDefined(); + }); + + it("explains a profile that failed to load", async () => { + mockServer({ route: (url) => (url.pathname === "/api/v1/players/profile" ? Promise.resolve(json({}, 500)) : undefined) }); + renderPage("/players?name=Nosey"); + expect(await screen.findByTestId("player-failed")).toBeDefined(); + }); + + it("shows the profile as loading until it arrives", async () => { + let answer: (r: Response) => void = () => {}; + mockServer({ + route: (url) => (url.pathname === "/api/v1/players/profile" ? new Promise((resolve) => { answer = resolve; }) : undefined), + }); + renderPage("/players?name=Nosey"); + await vi.waitFor(() => expect(requests("/api/v1/players/profile")).toHaveLength(1)); + expect(screen.getAllByText("Loading...").length).toBeGreaterThan(0); + answer(json(profile)); + expect(await screen.findByTestId("player-profile")).toBeDefined(); + }); + + it("falls back to stored world names when the maps cannot be read", async () => { + mockServer({ route: (url) => (url.pathname === "/api/v1/worlds" ? Promise.reject(new Error("offline")) : undefined) }); + renderPage("/players?name=Nosey"); + expect((await screen.findByTestId("player-recording-7")).textContent).toContain("altis"); + }); + + it("goes back to the recordings", async () => { + renderPage(); + fireEvent.click(screen.getByTestId("players-back")); + expect((await screen.findByTestId("route-stub")).textContent).toContain("/"); + }); +}); + +describe("killDeathRatio", () => { + it("divides kills by deaths, counting no deaths as one", () => { + expect(killDeathRatio(5, 2)).toBe("2.50"); + expect(killDeathRatio(3, 0)).toBe("3.00"); + expect(killDeathRatio(0, 4)).toBe("0.00"); + }); +}); diff --git a/ui/src/pages/players/index.tsx b/ui/src/pages/players/index.tsx new file mode 100644 index 00000000..006e21dc --- /dev/null +++ b/ui/src/pages/players/index.tsx @@ -0,0 +1 @@ +export { PlayersPage } from "./PlayersPage"; diff --git a/ui/src/pages/recording-playback/__tests__/ChatTab.test.tsx b/ui/src/pages/recording-playback/__tests__/ChatTab.test.tsx index 9062b604..8a712de8 100644 --- a/ui/src/pages/recording-playback/__tests__/ChatTab.test.tsx +++ b/ui/src/pages/recording-playback/__tests__/ChatTab.test.tsx @@ -1,22 +1,140 @@ import { describe, it, expect, afterEach } from "vitest"; -import { render, screen, cleanup } from "@solidjs/testing-library"; -import { ChatTab } from "../components/ChatTab"; -import { I18nProvider } from "../../../hooks/useLocale"; +import { render, screen, cleanup, fireEvent } from "@solidjs/testing-library"; +import { ChatTab, channelColor } from "../components/ChatTab"; +import type { EventDef } from "../../../data/types"; +import { createTestEngine, TestProviders, unitDef, makeManifest } from "./testHelpers"; afterEach(() => { cleanup(); }); +function chat(frameNum: number, fromName: string, message: string, channel: string): EventDef { + return { type: "chat", frameNum, fromName, message, channel }; +} + +const messages: EventDef[] = [ + chat(0, "Nosey", "radio check", "Side"), + chat(5, "Nosey", "#login synthetic-password", "Global"), + chat(10, "Nomad", "contact north", "Group"), + chat(20, "", "Engine starting...", "Vehicle"), + chat(30, "Nomad", "moving", ""), + chat(40, "Zeus", "custom", "Custom radio"), +]; + +function renderChat(events: EventDef[]) { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(makeManifest([unitDef()], events, 99)); + render(() => ( + + + + )); + return engine; +} + +function rowTexts(): string[] { + return screen.queryAllByTestId(/^chat-row-/).map((row) => row.textContent ?? ""); +} + describe("ChatTab", () => { - it("renders the chat unavailable message", () => { - render(() => ( - - - - )); - - expect( - screen.getByText("Chat messages not available for this recording"), - ).toBeTruthy(); + it("says when the recording has no chat", () => { + renderChat([]); + expect(screen.getByText("Chat messages not available for this recording")).toBeTruthy(); + expect(screen.queryByTestId("chat-search")).toBeNull(); + }); + + it("lists messages up to the current frame, newest first, with #login passwords masked", () => { + const engine = renderChat(messages); + expect(rowTexts()).toEqual([expect.stringContaining("radio check")]); + + engine.seekTo(99); + const rows = rowTexts(); + expect(rows).toHaveLength(6); + expect(rows[0]).toContain("custom"); + expect(rows[2]).toContain("System: Engine starting..."); + expect(rows[4]).toContain("Nosey: #login ********"); + expect(rows[5]).toContain("radio check"); + expect(rows.join(" ")).not.toContain("synthetic-password"); + }); + + it("shows an empty-state message before the first one at this point", () => { + const engine = renderChat([chat(50, "Nosey", "late", "Side")]); + expect(screen.getByText("No chat messages up to this point")).toBeTruthy(); + engine.seekTo(60); + expect(rowTexts()).toHaveLength(1); + }); + + it("filters by channel and back to all", () => { + const engine = renderChat(messages); + engine.seekTo(99); + const chips = screen.getByTestId("chat-channels"); + expect(chips.textContent).toBe("AllCustom radioGlobalGroupSideVehicle"); + + fireEvent.click(screen.getByTestId("chat-channel-Group")); + expect(rowTexts()).toEqual([expect.stringContaining("contact north")]); + + fireEvent.click(screen.getByTestId("chat-channel-Group")); + expect(rowTexts()).toHaveLength(6); + + fireEvent.click(screen.getByTestId("chat-channel-Side")); + expect(rowTexts()).toHaveLength(1); + fireEvent.click(screen.getByText("All")); + expect(rowTexts()).toHaveLength(6); + }); + + it("hides the channel filter when there is only one channel", () => { + renderChat([chat(0, "Nosey", "one", "Side"), chat(1, "Nosey", "two", "Side")]); + expect(screen.queryByTestId("chat-channels")).toBeNull(); + }); + + it("searches sender and message text", () => { + const engine = renderChat(messages); + engine.seekTo(99); + const search = screen.getByTestId("chat-search"); + + fireEvent.input(search, { target: { value: " NOMAD " } }); + expect(rowTexts()).toHaveLength(2); + + fireEvent.input(search, { target: { value: "north" } }); + expect(rowTexts()).toEqual([expect.stringContaining("contact north")]); + + fireEvent.input(search, { target: { value: "nothing like this" } }); + expect(screen.getByText("No chat messages up to this point")).toBeTruthy(); + }); + + it("moves playback to a message when it is clicked", () => { + const engine = renderChat(messages); + engine.seekTo(99); + const row = screen.getAllByTestId(/^chat-row-/).find((r) => r.textContent?.includes("contact north"))!; + fireEvent.click(row); + expect(engine.currentFrame()).toBe(10); + }); + + it("shows a channel badge only for messages with a channel", () => { + const engine = renderChat([chat(0, "Nomad", "moving", ""), chat(1, "Nosey", "copy", "Side"), chat(2, "Nosey", "out", "Side")]); + engine.seekTo(99); + const rows = screen.getAllByTestId(/^chat-row-/); + expect(rows[0].textContent).toContain("Side"); + expect(rows[2].textContent).not.toContain("Side"); + }); + + it("follows a newly loaded recording", () => { + const engine = renderChat(messages); + expect(screen.getByTestId("chat-search")).toBeTruthy(); + engine.loadRecording(makeManifest([unitDef()], [], 99)); + expect(screen.getByText("Chat messages not available for this recording")).toBeTruthy(); + }); +}); + +describe("channelColor", () => { + it("uses Arma's channel colours in any case", () => { + expect(channelColor("Side")).toBe("#46c8ff"); + expect(channelColor(" GROUP ")).toBe("#b6f25c"); + expect(channelColor("global")).toBe("#d9d9d9"); + }); + + it("gives other channels a neutral colour", () => { + expect(channelColor("Custom radio")).toBe("var(--text-secondary)"); + expect(channelColor("")).toBe("var(--text-secondary)"); }); }); diff --git a/ui/src/pages/recording-playback/__tests__/SidePanel.test.tsx b/ui/src/pages/recording-playback/__tests__/SidePanel.test.tsx index 0cb9c69e..4a879a9b 100644 --- a/ui/src/pages/recording-playback/__tests__/SidePanel.test.tsx +++ b/ui/src/pages/recording-playback/__tests__/SidePanel.test.tsx @@ -27,12 +27,12 @@ describe("SidePanel", () => { )); - for (const label of ["Units", "Events", "ORBAT", "Comms", "Stats", "FPS"]) { + for (const label of ["Units", "Events", "Chat", "ORBAT", "Comms", "Stats", "FPS"]) { expect(screen.getByText(label)).toBeTruthy(); } }); - // Six tabs share a panel fixed at 420px, so a long translation can be + // Seven tabs share one panel, so on a narrow screen a long translation can be // truncated to fit. The tooltip is the only place the full name survives, and // it is what stops a clipped tab from becoming an unidentifiable icon. it("gives every tab a title carrying its full label", () => { @@ -47,7 +47,7 @@ describe("SidePanel", () => { )); - for (const label of ["Units", "Events", "ORBAT", "Comms", "Stats", "FPS"]) { + for (const label of ["Units", "Events", "Chat", "ORBAT", "Comms", "Stats", "FPS"]) { expect(screen.getByTitle(label)).toBeTruthy(); } }); @@ -162,6 +162,24 @@ describe("SidePanel", () => { expect(screen.queryByText("BLUFOR")).toBeNull(); }); + it("shows the chat tab", () => { + const { engine, renderer } = createTestEngine(); + engine.loadRecording(makeManifest([unitDef()], [ + { type: "chat", frameNum: 0, channel: "Side", fromName: "Soldier", message: "radio check" }, + ])); + + const [activeTab, setActiveTab] = createSignal("units"); + render(() => ( + + + + )); + + fireEvent.click(screen.getByText("Chat")); + expect(activeTab()).toBe("chat"); + expect(screen.getByText("radio check")).toBeTruthy(); + }); + it("lists a Zeus module event with its recorded English name", () => { const { engine, renderer } = createTestEngine(); engine.loadRecording( diff --git a/ui/src/pages/recording-playback/__tests__/TimelineScrubber.test.tsx b/ui/src/pages/recording-playback/__tests__/TimelineScrubber.test.tsx index 385d8d91..49c83e18 100644 --- a/ui/src/pages/recording-playback/__tests__/TimelineScrubber.test.tsx +++ b/ui/src/pages/recording-playback/__tests__/TimelineScrubber.test.tsx @@ -827,7 +827,7 @@ describe("TimelineScrubber (handle dragging)", () => { connectEvent(10, "disconnected", "P1"), terminalHackEvent(11, "terminalHackStarted", "P1"), { frameNum: 12, type: "explosion", payload: { name: "Bomb", side: "WEST", radius: 10, x: 0, y: 0 } } as unknown as NonNullable[1]>[number], - { frameNum: 13, type: "chat", payload: { channel: "Global", fromId: 1, fromName: "P1", message: "msg" } } as unknown as NonNullable[1]>[number], + { frameNum: 13, type: "chat", channel: "Global", fromName: "P1", message: "msg" }, { frameNum: 14, type: "killed", victimId: 99, causedById: 1, weapon: "AK", distance: 10 } as unknown as NonNullable[1]>[number], ], 100, diff --git a/ui/src/pages/recording-playback/__tests__/convertedChat.integration.test.ts b/ui/src/pages/recording-playback/__tests__/convertedChat.integration.test.ts new file mode 100644 index 00000000..704f668f --- /dev/null +++ b/ui/src/pages/recording-playback/__tests__/convertedChat.integration.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ApiClient } from "../../../data/apiClient"; +import { + Chunk as PbChunk, + EntityType as PbEntityType, + Manifest as PbManifest, + Side as PbSide, +} from "../../../data/decoders/generated/ocap.pb"; +import type { Recording } from "../../../data/types"; +import { PlaybackEngine } from "../../../playback/engine"; +import { ChatEvent } from "../../../playback/events/chatEvent"; +import { MarkerManager } from "../../../playback/markerManager"; +import { MockRenderer } from "../../../renderers/mockRenderer"; +import { loadRecording } from "../loadRecording"; + +const engines: PlaybackEngine[] = []; +afterEach(() => { + for (const engine of engines) engine.dispose(); + engines.length = 0; +}); + +const buffer = (bytes: Uint8Array): ArrayBuffer => new Uint8Array(bytes).buffer; + +/** + * A converted recording's chat as the server's converter writes it: the fields + * as JSON in the event message (see TestConvertKeepsChat in internal/storage). + * The last event comes from a conversion that kept only the channel. + */ +const convertedChat = [ + { frameNum: 2, type: "chat", message: '{"message":"Moving up","fromName":"Nosey","channel":"Side"}' }, + { frameNum: 3, type: "chat", message: '{"message":"#login ********","fromName":"Nosey","channel":"Global"}' }, + // Converted before the server masked passwords, from a JSON upload. + { frameNum: 4, type: "chat", message: '{"message":"#LOGIN synthetic-password","fromName":"Nomad","channel":"Global"}' }, + { frameNum: 5, type: "chat", message: "Side" }, +]; + +async function loadConverted(): Promise { + const raw = PbManifest.fromPartial({ + version: 1, worldName: "altis", missionName: "Converted chat", endFrame: 9, + chunkSize: 300, chunkCount: 1, captureDelayMs: 1000, + entities: [{ id: 1, type: PbEntityType.ENTITY_TYPE_UNIT, name: "Nosey", side: PbSide.SIDE_WEST, isPlayer: true, startFrame: 0, endFrame: 9 }], + events: convertedChat, + }); + const api = { + getWorldConfig: vi.fn(async () => ({ worldName: "altis", worldSize: 30720, minZoom: 0, maxZoom: 6 })), + getManifest: vi.fn(async () => buffer(PbManifest.encode(raw).finish())), + getChunk: vi.fn(async () => buffer(PbChunk.encode(PbChunk.fromPartial({ + startFrame: 0, frameCount: 10, + frames: Array.from({ length: 10 }, (_, frameNum) => ({ frameNum, entities: [{ entityId: 1, posX: frameNum, posY: 0, alive: 1 }] })), + })).finish())), + } as unknown as ApiClient; + const rec: Recording = { + id: "43", filename: "converted-chat", worldName: "altis", missionName: "Converted chat", + storageFormat: "protobuf", date: "2026-12-01", missionDuration: 10, + }; + const renderer = new MockRenderer(); + const engine = new PlaybackEngine(renderer); + engines.push(engine); + await loadRecording(api, engine, new MarkerManager(renderer), rec); + return engine; +} + +describe("converted recording chat", () => { + it("plays back the chat a conversion carried, with passwords masked", async () => { + const engine = await loadConverted(); + const chat = engine.eventManager.getAll().filter((event): event is ChatEvent => event instanceof ChatEvent); + expect(chat.map((event) => [event.frameNum, event.fromName, event.channel, event.message])).toEqual([ + [2, "Nosey", "Side", "Moving up"], + [3, "Nosey", "Global", "#login ********"], + [4, "Nomad", "Global", "#LOGIN ********"], + ]); + expect(JSON.stringify(chat)).not.toContain("synthetic-password"); + }); +}); diff --git a/ui/src/pages/recording-playback/__tests__/deepLink.test.ts b/ui/src/pages/recording-playback/__tests__/deepLink.test.ts index 7211e1fa..f51882ad 100644 --- a/ui/src/pages/recording-playback/__tests__/deepLink.test.ts +++ b/ui/src/pages/recording-playback/__tests__/deepLink.test.ts @@ -51,7 +51,7 @@ describe("readDeepLink", () => { }); it("keeps every tab the side panel actually has", () => { - for (const tab of ["units", "events", "orbat", "comms", "stats", "fps"]) { + for (const tab of ["units", "events", "chat", "orbat", "comms", "stats", "fps"]) { expect(readDeepLink(`?tab=${tab}`).tab).toBe(tab); } }); diff --git a/ui/src/pages/recording-playback/components/ChatTab.tsx b/ui/src/pages/recording-playback/components/ChatTab.tsx index 0fe038cc..34010e77 100644 --- a/ui/src/pages/recording-playback/components/ChatTab.tsx +++ b/ui/src/pages/recording-playback/components/ChatTab.tsx @@ -1,14 +1,155 @@ +import { createMemo, createSignal, For, Show } from "solid-js"; import type { JSX } from "solid-js"; +import { useEngine } from "../../../hooks/useEngine"; import { useI18n } from "../../../hooks/useLocale"; +import { ChatEvent } from "../../../playback/events/chatEvent"; +import { formatElapsedTime } from "../../../playback/time"; +import { ClockIcon, MessageSquareIcon } from "../../../components/Icons"; import styles from "./SidePanel.module.css"; +/** Arma's default chat channel colours, keyed by lower-cased channel name. */ +const CHANNEL_COLORS: Record = { + global: "#d9d9d9", + side: "#46c8ff", + command: "#ffeb5c", + group: "#b6f25c", + vehicle: "#ffc533", + direct: "#ffffff", + system: "#8f8f8f", +}; + +const OTHER_CHANNEL_COLOR = "var(--text-secondary)"; + +/** The colour Arma shows a chat channel in; custom channels get a neutral one. */ +export function channelColor(channel: string): string { + return CHANNEL_COLORS[channel.trim().toLowerCase()] ?? OTHER_CHANNEL_COLOR; +} + +/** + * Chat messages up to the current frame, newest first, filterable by channel + * and text. Clicking a message moves playback to it. #login commands never + * become chat events, so they are not listed. + */ export function ChatTab(): JSX.Element { + const engine = useEngine(); const { t } = useI18n(); + const [filterText, setFilterText] = createSignal(""); + const [channel, setChannel] = createSignal(null); + + // Every message in the recording: it decides between the empty state and + // the list, and which channels can be filtered. + const allMessages = createMemo(() => { + engine.recordingVersion(); + return engine.eventManager.getAll().filter((e): e is ChatEvent => e instanceof ChatEvent); + }); + + const channels = createMemo(() => + [...new Set(allMessages().map((m) => m.channel).filter(Boolean))].sort((a, b) => a.localeCompare(b)), + ); + + const visible = createMemo(() => { + const text = filterText().trim().toLowerCase(); + const selected = channel(); + return engine + .activeEvents() + .filter((e): e is ChatEvent => e instanceof ChatEvent) + .filter((m) => selected === null || m.channel === selected) + .filter((m) => !text || `${m.fromName} ${m.message}`.toLowerCase().includes(text)) + .reverse(); + }); + + const chipStyle = (value: string | null): JSX.CSSProperties => { + const active = channel() === value; + const color = value === null ? "var(--text-primary)" : channelColor(value); + return { + background: active ? "rgba(255, 255, 255, 0.08)" : "transparent", + color: active ? color : "var(--text-dimmer)", + }; + }; + return ( -
-
- {t("chat_unavailable")} + 0} + fallback={ +
+
{t("chat_unavailable")}
+
+ } + > +
+ setFilterText(e.currentTarget.value)} + /> +
+ + 1}> +
+ + + {(name) => ( + + )} + +
+
+ +
+ 0} fallback={
{t("no_chat_messages")}
}> + + {(message) => { + const color = channelColor(message.channel); + return ( + + ); + }} + +
-
+ ); } diff --git a/ui/src/pages/recording-playback/components/SidePanel.tsx b/ui/src/pages/recording-playback/components/SidePanel.tsx index ea76fba6..74e44873 100644 --- a/ui/src/pages/recording-playback/components/SidePanel.tsx +++ b/ui/src/pages/recording-playback/components/SidePanel.tsx @@ -1,9 +1,10 @@ import { Switch, Match, For, createEffect, onCleanup } from "solid-js"; import type { Accessor, JSX } from "solid-js"; -import { UsersIcon, ActivityIcon, BarChartIcon, RadioIcon, SitemapIcon, GaugeIcon } from "../../../components/Icons"; +import { UsersIcon, ActivityIcon, BarChartIcon, RadioIcon, SitemapIcon, GaugeIcon, MessageSquareIcon } from "../../../components/Icons"; import { useI18n } from "../../../hooks/useLocale"; import { UnitsTab } from "./UnitsTab"; import { EventsTab } from "./EventsTab"; +import { ChatTab } from "./ChatTab"; import { StatsTab } from "./StatsTab"; import { FpsTab } from "./FpsTab"; import { CommsTab } from "./CommsTab"; @@ -33,6 +34,7 @@ export function SidePanel(props: SidePanelProps): JSX.Element { const tabs = [ { id: "units" as const, labelKey: "units", Icon: UsersIcon }, { id: "events" as const, labelKey: "events", Icon: ActivityIcon }, + { id: "chat" as const, labelKey: "chat_messages", Icon: MessageSquareIcon }, { id: "orbat" as const, labelKey: "orbat", Icon: SitemapIcon }, { id: "comms" as const, labelKey: "comms", Icon: RadioIcon }, { id: "stats" as const, labelKey: "stats", Icon: BarChartIcon }, @@ -76,6 +78,9 @@ export function SidePanel(props: SidePanelProps): JSX.Element { + + + diff --git a/ui/src/pages/recording-playback/deepLink.ts b/ui/src/pages/recording-playback/deepLink.ts index 123dd128..c0a5a9b7 100644 --- a/ui/src/pages/recording-playback/deepLink.ts +++ b/ui/src/pages/recording-playback/deepLink.ts @@ -14,7 +14,7 @@ import type { Side } from "../../data/types"; /** Panel tabs a link may select. Mirrors the tab ids in . */ -export const DEEP_LINK_TABS = ["units", "events", "orbat", "comms", "stats", "fps"] as const; +export const DEEP_LINK_TABS = ["units", "events", "chat", "orbat", "comms", "stats", "fps"] as const; export type DeepLinkTab = (typeof DEEP_LINK_TABS)[number]; diff --git a/ui/src/pages/recording-playback/shortcuts.ts b/ui/src/pages/recording-playback/shortcuts.ts index 65a021be..a946ad31 100644 --- a/ui/src/pages/recording-playback/shortcuts.ts +++ b/ui/src/pages/recording-playback/shortcuts.ts @@ -7,7 +7,7 @@ import { HitKilledEvent } from "../../playback/events/hitKilledEvent"; export const [leftPanelVisible, setLeftPanelVisible] = createSignal(true); -/** Active tab in the side panel: "units" | "events" | "stats" | "chat" */ +/** Active tab in the side panel: one of the SidePanel tab ids, such as "units" or "chat". */ export const [activePanelTab, setActivePanelTab] = createSignal("units"); /** Currently selected side in the units tab — drives briefing marker filtering. */ diff --git a/ui/src/pages/recording-selector/RecordingSelector.module.css b/ui/src/pages/recording-selector/RecordingSelector.module.css index 8c2de650..8cec3eca 100644 --- a/ui/src/pages/recording-selector/RecordingSelector.module.css +++ b/ui/src/pages/recording-selector/RecordingSelector.module.css @@ -271,6 +271,103 @@ align-items: center; } +/* ── Player suggestions under the search box ── */ + +.playerSuggestions { + position: absolute; + top: calc(100% + 6px); + left: 0; + right: 0; + z-index: var(--z-dropdown); + background: color-mix(in srgb, var(--bg-dark) 97%, transparent); + backdrop-filter: blur(16px); + border: var(--border-subtle); + border-radius: 6px; + box-shadow: var(--shadow-dropdown); + animation: fadeIn 0.15s ease-out; + padding: 4px; + display: flex; + flex-direction: column; +} + +.playerSuggestionsTitle { + padding: 6px 8px 4px; + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--text-dimmer); +} + +.playerSuggestion { + display: flex; + align-items: center; + gap: 8px; + padding: 7px 8px; + border: none; + border-radius: 4px; + background: transparent; + color: var(--text-secondary); + cursor: pointer; + text-align: left; + font-size: 12px; +} + +.playerSuggestion:hover { + background: var(--bg-interactive); + color: var(--text-primary); +} + +.playerSuggestionName { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.playerSuggestionMeta { + font-family: var(--font-mono); + font-size: 10px; + color: var(--text-dimmer); +} + +.loadingMore { + padding: 12px; + text-align: center; + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-dim); +} + +.loadMoreFailed { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--accent-danger); +} + +.retryButton { + display: flex; + align-items: center; + gap: 4px; + padding: 4px 10px; + border-radius: 6px; + border: none; + background: color-mix(in srgb, var(--accent-danger) 10%, transparent); + color: var(--accent-danger); + font-size: var(--font-size-sm); + font-family: var(--font-mono); + cursor: pointer; +} + +.retryButton:hover { + filter: brightness(1.1); +} + .searchIcon { position: absolute; left: 12px; diff --git a/ui/src/pages/recording-selector/RecordingSelector.tsx b/ui/src/pages/recording-selector/RecordingSelector.tsx index 20406811..746da461 100644 --- a/ui/src/pages/recording-selector/RecordingSelector.tsx +++ b/ui/src/pages/recording-selector/RecordingSelector.tsx @@ -1,16 +1,16 @@ -import { createSignal, createMemo, createEffect, Show, For, onMount, onCleanup, batch } from "solid-js"; +import { createSignal, createMemo, createEffect, Show, For, onMount, onCleanup, batch, on } from "solid-js"; import type { JSX } from "solid-js"; import { useNavigate } from "@solidjs/router"; import { createVirtualizer } from "@tanstack/solid-virtual"; -import type { Recording } from "../../data/types"; -import { ApiClient, type BuildInfo } from "../../data/apiClient"; +import type { PlayerSummary, Recording, RecordingsSummary } from "../../data/types"; +import { ApiClient, type BuildInfo, type RecordingQuery, type RecordingSort } from "../../data/apiClient"; import { useI18n } from "../../hooks/useLocale"; import { useCustomize } from "../../hooks/useCustomize"; import { useAuth } from "../../hooks/useAuth"; import { useClickOutside } from "../../hooks/useClickOutside"; import { LOCALES } from "../../i18n/i18n"; import { LOCALE_LABELS } from "./constants"; -import { GlobeIcon, UsersIcon, CrosshairIcon, ChevronDownIcon, UploadIcon, SearchIcon, TagIcon, MapIcon, XIcon, GitHubIcon, ExternalLinkIcon, HeartIcon, AlertTriangleIcon, BookOpenIcon, ShieldCheckIcon } from "../../components/Icons"; +import { GlobeIcon, UsersIcon, CrosshairIcon, ChevronDownIcon, UploadIcon, SearchIcon, TagIcon, MapIcon, XIcon, GitHubIcon, ExternalLinkIcon, HeartIcon, AlertTriangleIcon, BookOpenIcon, ShieldCheckIcon, RefreshCwIcon } from "../../components/Icons"; import { AuthBadge } from "../../components/AuthBadge"; import { getMapColor, isRecordingReady, stripRecordingExtension } from "./helpers"; import { StatPill, TagBadge, SortHeader } from "./components"; @@ -18,8 +18,24 @@ import { RecordingRow } from "./RecordingRow"; import { DetailSidebar } from "./DetailSidebar"; import { EditModal, DeleteConfirm, UploadDialog } from "./dialogs"; import { basePath } from "../../data/basePath"; +import { playerPath } from "../../data/players"; import styles from "./RecordingSelector.module.css"; +// ─── Paging ─── + +/** Recordings fetched per page. */ +export const PAGE_SIZE = 100; +/** Fetch the next page once the list is scrolled this close to its end. */ +const LOAD_AHEAD = 20; +/** Wait for typing to pause before searching on the server. */ +export const SEARCH_DEBOUNCE_MS = 250; +/** Players suggested under the search box. */ +const PLAYER_SUGGESTIONS = 5; +/** Shortest search that also looks for players. */ +const MIN_PLAYER_QUERY = 2; + +const EMPTY_SUMMARY: RecordingsSummary = { total: 0, worlds: [], tags: [], maxPlayers: 0, totalKills: 0 }; + // ─── Main Component ─── export function RecordingSelector(): JSX.Element { @@ -55,33 +71,134 @@ export function RecordingSelector(): JSX.Element { let searchRef: HTMLInputElement | undefined; let scrollRef: HTMLDivElement | undefined; - // Refetch recordings + worlds whenever the auth state changes (login, - // logout, initial getMe resolving). Tracking authenticated() ties the - // effect to the signal; the empty initial run still fires on mount. + // The list is paged on the server: `recordings` holds the pages loaded so + // far, `total` the matches across all pages and `summary` every recording. + const [summary, setSummary] = createSignal(EMPTY_SUMMARY); + const [total, setTotal] = createSignal(0); + // Where the next page starts: right behind the last recording loaded, so a + // recording added or deleted meanwhile neither repeats nor skips one. + const [nextPage, setNextPage] = createSignal(null); + const [loadingMore, setLoadingMore] = createSignal(false); + // A failed next page stops loading more, rather than retrying on every + // render, until the reader retries it or the list is reloaded. + const [pageFailed, setPageFailed] = createSignal(false); + // The search as sent to the server, once typing pauses. + const [query, setQuery] = createSignal(""); + const [playerMatches, setPlayerMatches] = createSignal([]); + const [suggestionsOpen, setSuggestionsOpen] = createSignal(false); + // Responses to an older filter are dropped. + let pageGeneration = 0; + + const refreshSummary = async () => { + setSummary(await api.getRecordingsSummary().catch(() => EMPTY_SUMMARY)); + }; + + // Refetch the header data whenever the auth state changes (login, logout, + // initial getMe resolving). Tracking authenticated() ties the effect to the + // signal; the empty initial run still fires on mount. createEffect(() => { void authenticated(); - setLoading(true); + void refreshSummary(); void Promise.all([ - api.getRecordings(), api.getVersion().catch(() => null), api.getWorlds().catch(() => []), - ]) - .then(([recs, info, worlds]) => { - setRecordings(recs.reverse()); - if (info) setBuildInfo(info); - const lookup = new Map(); - for (const w of worlds) { - lookup.set(w.name, w.displayName); - } - setWorldNames(lookup); - }) - .catch(() => { - setRecordings([]); - setWorldNames(new Map()); - }) - .finally(() => setLoading(false)); + ]).then(([info, worlds]) => { + if (info) setBuildInfo(info); + const lookup = new Map(); + for (const w of worlds) { + lookup.set(w.name, w.displayName); + } + setWorldNames(lookup); + }); + }); + + const pageQuery = (after: string | null): RecordingQuery => ({ + q: query() || undefined, + tagExact: tagFilter() ?? undefined, + worlds: [...mapFilter()], + sort: sortBy() as RecordingSort, + dir: sortDir() as "asc" | "desc", + limit: PAGE_SIZE, + after: after ?? undefined, }); + const loadFirstPage = async () => { + const generation = ++pageGeneration; + batch(() => { + setLoading(true); + setPageFailed(false); + }); + const page = await api.getRecordingsPage(pageQuery(null)).catch(() => ({ recordings: [], total: 0, next: null })); + if (generation !== pageGeneration) return; + batch(() => { + setRecordings(page.recordings); + setTotal(page.total); + setNextPage(page.next); + setLoading(false); + }); + }; + + // Loads the page after the last one loaded, from the same cursor when it + // retries a page that failed. + const loadMore = async () => { + const generation = pageGeneration; + batch(() => { + setLoadingMore(true); + setPageFailed(false); + }); + try { + const page = await api.getRecordingsPage(pageQuery(nextPage())); + if (generation === pageGeneration) { + batch(() => { + // A recording whose date was edited can move behind the cursor and + // come again; it is listed once. + setRecordings((loaded) => { + const seen = new Set(loaded.map((rec) => rec.id)); + return [...loaded, ...page.recordings.filter((rec) => !seen.has(rec.id))]; + }); + setTotal(page.total); + setNextPage(page.next); + }); + } + } catch { + if (generation === pageGeneration) setPageFailed(true); + } finally { + setLoadingMore(false); + } + }; + + // Reload from the first page whenever the filters, the order or the auth + // state change. + createEffect(on([authenticated, query, tagFilter, mapFilter, sortBy, sortDir], () => { + void loadFirstPage(); + })); + + // Suggest players matching the search. + createEffect(on(query, (q) => { + if (q.length < MIN_PLAYER_QUERY) { + setPlayerMatches([]); + return; + } + void api.searchPlayers(q, PLAYER_SUGGESTIONS) + .catch(() => []) + .then((players) => { + if (query() === q) setPlayerMatches(players); + }); + })); + + let searchTimer: ReturnType | undefined; + const updateSearch = (value: string) => { + setSearch(value); + setSuggestionsOpen(true); + clearTimeout(searchTimer); + searchTimer = setTimeout(() => setQuery(value.trim()), SEARCH_DEBOUNCE_MS); + }; + onCleanup(() => clearTimeout(searchTimer)); + + const openPlayer = (player: PlayerSummary) => { + navigate(playerPath(player)); + }; + createEffect(() => { void authenticated(); api.getMapToolTools().then(() => setMapToolEnabled(true)).catch(() => setMapToolEnabled(false)); @@ -98,6 +215,7 @@ export function RecordingSelector(): JSX.Element { setLangOpen(false); setEditingRec(null); setDeletingRec(null); + setSuggestionsOpen(false); searchRef!.blur(); } if (e.key === "Enter" && selectedId()) { @@ -106,7 +224,7 @@ export function RecordingSelector(): JSX.Element { } if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); - const list = filtered(); + const list = recordings(); if (list.length === 0) return; const currentIdx = list.findIndex((o) => o.id === selectedId()); let nextIdx: number; @@ -133,19 +251,20 @@ export function RecordingSelector(): JSX.Element { } }; - // Derived data + // Derived data, from the summary of every recording rather than the pages + // loaded so far. const uniqueMaps = createMemo(() => { const names = worldNames(); - return [...new Set(recordings().map((o) => o.worldName))].sort((a, b) => + return [...summary().worlds].sort((a, b) => (names.get(a) ?? a).localeCompare(names.get(b) ?? b) ); }); - const uniqueTags = createMemo(() => ([...new Set(recordings().map((o) => o.tag).filter(Boolean))] as string[]).sort((a, b) => a.localeCompare(b))); + const uniqueTags = createMemo(() => [...summary().tags].sort((a, b) => a.localeCompare(b))); - const hasPlayerData = createMemo(() => recordings().some(r => (r.playerCount ?? 0) > 0)); - const hasKillData = createMemo(() => recordings().some(r => (r.killCount ?? 0) > 0)); - const maxPlayers = createMemo(() => Math.max(0, ...recordings().map(r => r.playerCount ?? 0))); - const totalKills = createMemo(() => recordings().reduce((s, r) => s + (r.killCount ?? 0), 0)); + const maxPlayers = () => summary().maxPlayers; + const totalKills = () => summary().totalKills; + const hasPlayerData = () => maxPlayers() > 0; + const hasKillData = () => totalKills() > 0; const gridColumns = createMemo(() => { let cols = "1fr 130px 100px"; @@ -155,41 +274,24 @@ export function RecordingSelector(): JSX.Element { return cols; }); - const filtered = createMemo(() => { - let result = [...recordings()]; - const s = search().toLowerCase(); - if (s) { - result = result.filter((r) => - r.missionName.toLowerCase().includes(s) || - r.worldName.toLowerCase().includes(s) || - worldDisplayName(r.worldName).toLowerCase().includes(s) - ); - } - const tf = tagFilter(); - if (tf) result = result.filter((r) => r.tag === tf); - const mf = mapFilter(); - if (mf.size > 0) result = result.filter((r) => mf.has(r.worldName)); - - const sb = sortBy(); - const sd = sortDir(); - result.sort((a, b) => { - let cmp: number; - if (sb === "date") cmp = new Date(a.date).getTime() - new Date(b.date).getTime(); - else if (sb === "name") cmp = a.missionName.localeCompare(b.missionName); - else cmp = a.missionDuration - b.missionDuration; - return sd === "desc" ? -cmp : cmp; - }); - return result; - }); - const virtualizer = createVirtualizer({ - get count() { return filtered().length; }, + get count() { return recordings().length; }, getScrollElement: () => scrollRef ?? null, estimateSize: () => 61, overscan: 10, initialRect: { width: 0, height: 800 }, }); + // Fetch the next page as the end of the loaded rows comes into view. + createEffect(() => { + const items = virtualizer.getVirtualItems(); + const last = items[items.length - 1]; + const loaded = recordings().length; + if (last && last.index >= loaded - LOAD_AHEAD && nextPage() !== null && !loading() && !loadingMore() && !pageFailed()) { + void loadMore(); + } + }); + const selectedRec = createMemo(() => { const id = selectedId(); return id ? recordings().find((o) => o.id === id) ?? null : null; @@ -198,9 +300,13 @@ export function RecordingSelector(): JSX.Element { const hasFilters = () => search() || tagFilter() || mapFilter().size > 0; const clearFilters = () => { - setSearch(""); - setTagFilter(null); - setMapFilter(new Set()); + clearTimeout(searchTimer); + batch(() => { + setSearch(""); + setQuery(""); + setTagFilter(null); + setMapFilter(new Set()); + }); }; // Map filter dropdown helpers @@ -238,8 +344,7 @@ export function RecordingSelector(): JSX.Element { // Admin handlers const refreshRecordings = async () => { - const recs = await api.getRecordings(); - setRecordings(recs.reverse()); + await Promise.all([loadFirstPage(), refreshSummary()]); }; const handleEditSave = async (id: string, data: { missionName?: string; tag?: string; date?: string }) => { @@ -312,7 +417,7 @@ export function RecordingSelector(): JSX.Element {
- {customize().headerSubtitle || <>Operation Capture and Playback · {recordings().length} {t("recordings")}} + {customize().headerSubtitle || <>Operation Capture and Playback · {summary().total} {t("recordings")}}
@@ -368,6 +473,14 @@ export function RecordingSelector(): JSX.Element {
+ + )} + +
+ {/* Tag filters */} @@ -513,7 +650,7 @@ export function RecordingSelector(): JSX.Element { {t("loading")} - +
{t("no_recordings_found")} @@ -523,7 +660,7 @@ export function RecordingSelector(): JSX.Element {
{(vItem) => { - const rec = () => filtered()[vItem.index]; + const rec = () => recordings()[vItem.index]; return ( {(o) => ( @@ -545,6 +682,18 @@ export function RecordingSelector(): JSX.Element { }}
+ +
{t("loading_more")}
+
+ + +
{/* Footer */} @@ -577,7 +726,7 @@ export function RecordingSelector(): JSX.Element { - {filtered().length} {t("of")} {recordings().length} {t("recordings")} + {total()} {t("of")} {summary().total} {t("recordings")}
diff --git a/ui/src/pages/recording-selector/__tests__/RecordingSelector.test.tsx b/ui/src/pages/recording-selector/__tests__/RecordingSelector.test.tsx index 0069f2e5..66c9f490 100644 --- a/ui/src/pages/recording-selector/__tests__/RecordingSelector.test.tsx +++ b/ui/src/pages/recording-selector/__tests__/RecordingSelector.test.tsx @@ -6,7 +6,8 @@ import { CustomizeProvider } from "../../../hooks/useCustomize"; import { AuthProvider } from "../../../hooks/useAuth"; import { setAuthToken } from "../../../data/apiClient"; import { RecordingSelector } from ".."; -import type { Recording } from "../../../data/types"; +import { SEARCH_DEBOUNCE_MS } from "../RecordingSelector"; +import type { PlayerSummary, Recording } from "../../../data/types"; // ─── Helpers ─── @@ -54,27 +55,115 @@ const mockRecordings: Recording[] = [ }, ]; -function mockFetchWith(ops: Recording[]) { - globalThis.fetch = vi.fn().mockResolvedValue({ - ok: true, - json: () => - Promise.resolve( - ops.map((op) => ({ - id: Number(op.id), - world_name: op.worldName, - mission_name: op.missionName, - mission_duration: op.missionDuration, - filename: `${op.id}.json`, - date: op.date, - tag: op.tag, - storageFormat: op.storageFormat, - conversionStatus: op.conversionStatus, - player_count: op.playerCount, - kill_count: op.killCount, - player_kill_count: op.playerKillCount, - })), - ), - } as Response); +function rawRecording(op: Recording) { + return { + id: Number(op.id), + world_name: op.worldName, + mission_name: op.missionName, + mission_duration: op.missionDuration, + filename: `${op.id}.json`, + date: op.date, + tag: op.tag, + storageFormat: op.storageFormat, + conversionStatus: op.conversionStatus, + player_count: op.playerCount, + kill_count: op.killCount, + player_kill_count: op.playerKillCount, + }; +} + +function jsonResponse(data: unknown, headers: Record = {}): Response { + return { + ok: true, status: 200, statusText: "OK", + json: () => Promise.resolve(data), + headers: new Headers(headers), + } as unknown as Response; +} + +/** The recording list as the server pages it: filtered, sorted, then sliced. */ +function serveRecordings(ops: Recording[], url: URL): Response { + const params = url.searchParams; + const q = (params.get("q") ?? "").toLowerCase(); + const tag = params.get("tag") ?? ""; + const tagExact = params.get("tagExact") ?? ""; + const worlds = params.getAll("world"); + let result = ops.filter((op) => + (!q || op.missionName.toLowerCase().includes(q) || op.worldName.toLowerCase().includes(q)) && + (!tag || (op.tag ?? "").includes(tag)) && + (!tagExact || op.tag === tagExact) && + (worlds.length === 0 || worlds.includes(op.worldName)), + ); + // Sorted by the value asked for, then by id, and continued behind a cursor + // of both, as the server does. + const sort = params.get("sort"); + const sign = params.get("dir") === "desc" ? -1 : 1; + const position = (op: Recording): [string | number, number] => [ + sort === "name" ? op.missionName : sort === "duration" ? op.missionDuration : sort === "date" ? op.date : 0, + Number(op.id), + ]; + const order = ([av, aid]: [string | number, number], [bv, bid]: [string | number, number]) => { + const primary = typeof av === "string" ? av.localeCompare(String(bv)) : av - Number(bv); + return sort ? sign * (primary || aid - bid) : aid - bid; + }; + result = [...result].sort((a, b) => order(position(a), position(b))); + const total = result.length; + const after = params.get("after"); + if (after) { + const cursor = JSON.parse(after) as [string | number, number]; + result = result.filter((op) => order(position(op), cursor) > 0); + } + const offset = Number(params.get("offset") ?? 0); + const limit = Number(params.get("limit") ?? result.length); + const page = result.slice(offset, offset + limit); + const headers: Record = { "X-Total-Count": String(total) }; + if (page.length === limit) headers["X-Next-Cursor"] = JSON.stringify(position(page[page.length - 1])); + return jsonResponse(page.map(rawRecording), headers); +} + +function summaryOf(ops: Recording[]) { + return { + total: ops.length, + worlds: [...new Set(ops.map((op) => op.worldName))], + tags: [...new Set(ops.map((op) => op.tag).filter(Boolean))], + maxPlayers: Math.max(0, ...ops.map((op) => op.playerCount ?? 0)), + totalKills: ops.reduce((sum, op) => sum + (op.killCount ?? 0), 0), + }; +} + +interface FakeServerOptions { + players?: PlayerSummary[]; + /** Answers a URL before the defaults do; undefined falls through. */ + route?: (url: URL, init?: RequestInit) => Promise | undefined; +} + +/** A fetch that answers like the server: paged recordings, their summary and player search. */ +function fakeServer(ops: Recording[], options: FakeServerOptions = {}) { + return vi.fn().mockImplementation((input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input), "http://localhost"); + const routed = options.route?.(url, init); + if (routed) return routed; + if ((init?.method ?? "GET") !== "GET") return Promise.resolve(jsonResponse({})); + switch (url.pathname) { + case "/api/v1/operations": + return Promise.resolve(serveRecordings(ops, url)); + case "/api/v1/operations/summary": + return Promise.resolve(jsonResponse(summaryOf(ops))); + case "/api/v1/players": { + const q = (url.searchParams.get("q") ?? "").toLowerCase(); + return Promise.resolve(jsonResponse((options.players ?? []).filter((p) => p.name.toLowerCase().includes(q)))); + } + case "/api/v1/customize": + return Promise.resolve(jsonResponse({})); + case "/api/v1/auth/me": + return Promise.resolve(jsonResponse({ authenticated: false })); + default: + return Promise.resolve(jsonResponse([])); + } + }); +} + +function mockFetchWith(ops: Recording[], options?: FakeServerOptions) { + globalThis.fetch = fakeServer(ops, options); } /** Lightweight stub that renders location state without needing Leaflet/engine */ @@ -88,11 +177,18 @@ function RecordingStub() { ); } +/** Stands in for the players page, showing the query it was opened with. */ +function PlayersStub() { + const location = useLocation(); + return
{location.search}
; +} + function renderPage() { return render(() => ( {p.children}}> + )); } @@ -227,6 +323,22 @@ describe("RecordingSelector", () => { expect(queryByTestId("recording-2")).not.toBeNull(); }); + it("selects exactly the clicked tag, not every tag containing it", async () => { + mockFetchWith([ + ...mockRecordings, + { id: "9", worldName: "Altis", missionName: "Op Training", missionDuration: 60, date: "2024-04-01", tag: "COOP-training" }, + ]); + const { findByTestId, queryByTestId } = renderPage(); + await findByTestId("recording-9"); + + fireEvent.click(screen.getByTestId("tag-filter-COOP")); + await vi.waitFor(() => expect(queryByTestId("recording-9")).toBeNull()); + expect(queryByTestId("recording-2")).not.toBeNull(); + const last = listRequests()[listRequests().length - 1]; + expect(last.searchParams.get("tagExact")).toBe("COOP"); + expect(last.searchParams.has("tag")).toBe(false); + }); + it("toggles tag filter off when clicked again", async () => { const { findByTestId, queryByTestId } = renderPage(); await findByTestId("recording-1"); @@ -656,7 +768,7 @@ describe("RecordingSelector", () => { await findByTestId("recording-1"); // 2 unique maps: Altis and Stratis - expect(screen.getByText("2")).toBeDefined(); + expect(await screen.findByText("2")).toBeDefined(); expect(screen.getAllByText("Maps").length).toBeGreaterThan(0); }); @@ -751,7 +863,7 @@ describe("RecordingSelector (player/kill columns)", () => { // Column headers for players and kills should be visible // t("players") = "Players", t("total_kills") = "Kills" - expect(screen.getAllByText("Players").length).toBeGreaterThanOrEqual(1); + expect((await screen.findAllByText("Players")).length).toBeGreaterThanOrEqual(1); expect(screen.getAllByText("Kills").length).toBeGreaterThanOrEqual(1); }); @@ -761,8 +873,8 @@ describe("RecordingSelector (player/kill columns)", () => { // maxPlayers = 32, label t("max_players") = "Max Players" // "32" appears in both the stat pill and the row, so check for at least one + expect(await screen.findByText("Max Players")).toBeDefined(); expect(screen.getAllByText("32").length).toBeGreaterThanOrEqual(1); - expect(screen.getByText("Max Players")).toBeDefined(); }); it("shows totalKills stat pill", async () => { @@ -770,7 +882,7 @@ describe("RecordingSelector (player/kill columns)", () => { await findByTestId("recording-10"); // totalKills = 150 + 50 = 200, label t("total_kills") = "Kills" - expect(screen.getByText("200")).toBeDefined(); + expect(await screen.findByText("200")).toBeDefined(); }); }); @@ -862,6 +974,7 @@ function mockAdminFetch(ops: Recording[]) { conversionStatus: op.conversionStatus, })); + const server = fakeServer(ops); return vi.fn().mockImplementation((url: string, init?: RequestInit) => { const u = typeof url === "string" ? url : ""; @@ -915,11 +1028,8 @@ function mockAdminFetch(ops: Recording[]) { } as Response); } - // Default: operations list - return Promise.resolve({ - ok: true, status: 200, statusText: "OK", - json: () => Promise.resolve(rawOps), - } as Response); + // Default: the recording list, its summary and the rest as the server answers them + return server(url, init); }); } @@ -1043,7 +1153,7 @@ describe("RecordingSelector (Admin)", () => { await findByTestId("launch-button"); // Click Edit in sidebar - fireEvent.click(screen.getByRole("button", { name: /Edit/ })); + fireEvent.click(await screen.findByRole("button", { name: /Edit/ })); // Edit modal should appear await vi.waitFor(() => { @@ -1069,7 +1179,7 @@ describe("RecordingSelector (Admin)", () => { await findByTestId("launch-button"); // Click Delete in sidebar - fireEvent.click(screen.getByRole("button", { name: /Delete/ })); + fireEvent.click(await screen.findByRole("button", { name: /Delete/ })); // Confirm dialog should appear (title + danger button both say "Delete Recording") await vi.waitFor(() => { @@ -1096,7 +1206,7 @@ describe("RecordingSelector (Admin)", () => { await findByTestId("launch-button"); // Retry button should be visible for failed operation - const retryBtn = screen.getByRole("button", { name: /Retry/ }); + const retryBtn = await screen.findByRole("button", { name: /Retry/ }); fireEvent.click(retryBtn); // Verify retry API was called @@ -1457,41 +1567,22 @@ describe("RecordingSelector (Admin)", () => { it("handles getVersion/getWorlds failures, custom logos, empty list ArrowDown, sort asc->desc, map filter search/pills/outside-click, modal cancel, and map-manager nav", async () => { setAuthToken("valid-token"); - globalThis.fetch = vi.fn().mockImplementation((url: string) => { - const u = typeof url === "string" ? url : ""; - if (u.includes("/api/v1/auth/me")) { - return Promise.resolve({ - ok: true, status: 200, statusText: "OK", - json: () => Promise.resolve({ authenticated: true, role: "admin", steamId: "1", steamName: "Admin" }), - } as Response); - } - if (u.includes("/api/version") || u.includes("/api/v1/worlds")) { - return Promise.reject(new Error("fail")); - } - if (u.includes("/api/v1/customize")) { - return Promise.resolve({ - ok: true, status: 200, statusText: "OK", - json: () => Promise.resolve({ enabled: true, websiteLogo: "https://example.com/logo.png", websiteURL: "https://example.com" }), - } as Response); - } - if (u.includes("/api/v1/maptool/tools")) { - return Promise.resolve({ - ok: true, status: 200, statusText: "OK", - json: () => Promise.resolve([{ name: "pmtiles", found: true, required: true }]), - } as Response); - } - return Promise.resolve({ - ok: true, status: 200, statusText: "OK", - json: () => Promise.resolve(mockRecordings.map((op) => ({ - id: Number(op.id), - world_name: op.worldName, - mission_name: op.missionName, - mission_duration: op.missionDuration, - filename: `${op.id}.json`, - date: op.date, - tag: op.tag, - }))), - } as Response); + mockFetchWith(mockRecordings, { + route: (url) => { + if (url.pathname === "/api/v1/auth/me") { + return Promise.resolve(jsonResponse({ authenticated: true, role: "admin", steamId: "1", steamName: "Admin" })); + } + if (url.pathname === "/api/version" || url.pathname === "/api/v1/worlds") { + return Promise.reject(new Error("fail")); + } + if (url.pathname === "/api/v1/customize") { + return Promise.resolve(jsonResponse({ enabled: true, websiteLogo: "https://example.com/logo.png", websiteURL: "https://example.com" })); + } + if (url.pathname === "/api/v1/maptool/tools") { + return Promise.resolve(jsonResponse([{ name: "pmtiles", found: true, required: true }])); + } + return undefined; + }, }); const { findByTestId } = renderPage(); @@ -1514,7 +1605,7 @@ describe("RecordingSelector (Admin)", () => { fireEvent.click(document.querySelector("div[class*='langOverlay']") as HTMLElement); // MapFilterDropdown: open, search matching world, clear search, search non-matching, select map, click pill to remove, outside click closes - const trigger = screen.getByTestId("map-filter-dropdown-trigger"); + const trigger = await screen.findByTestId("map-filter-dropdown-trigger"); fireEvent.click(trigger); const dropdown = await screen.findByTestId("map-filter-dropdown"); const mapSearchInput = dropdown.querySelector("input") as HTMLInputElement; @@ -1534,13 +1625,14 @@ describe("RecordingSelector (Admin)", () => { // ArrowDown when filtered list is empty const searchInput = screen.getByTestId("search-input") as HTMLInputElement; fireEvent.input(searchInput, { target: { value: "no-match-xyz" } }); + await screen.findByText(/No recordings found/); fireEvent.keyDown(window, { key: "ArrowDown" }); fireEvent.input(searchInput, { target: { value: "" } }); // Edit modal Cancel & Delete confirm Cancel fireEvent.click(await findByTestId("recording-1")); await findByTestId("launch-button"); - fireEvent.click(screen.getByRole("button", { name: /Edit/ })); + fireEvent.click(await screen.findByRole("button", { name: /Edit/ })); fireEvent.click(await screen.findByRole("button", { name: "Cancel" })); expect(screen.queryByText("Edit Recording")).toBeNull(); @@ -1577,40 +1669,22 @@ describe("RecordingSelector (Admin)", () => { it("matches map dropdown filter by raw worldName fallback and handles stale selectedId after reload", async () => { let returnEmptyOps = false; setAuthToken("valid-token"); - globalThis.fetch = vi.fn().mockImplementation((url: string) => { - const u = typeof url === "string" ? url : ""; - if (u.includes("/api/v1/auth/me")) { - return Promise.resolve({ - ok: true, status: 200, - json: () => Promise.resolve({ authenticated: !returnEmptyOps, role: "admin", steamId: "1", steamName: "Admin" }), - } as Response); - } - if (u.includes("/api/v1/auth/logout")) { - returnEmptyOps = true; - return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({}) } as Response); - } - if (u.includes("/api/v1/worlds")) { - return Promise.resolve({ - ok: true, status: 200, - json: () => Promise.resolve([{ name: "Altis", displayName: "Isle Display" }]), - } as Response); - } - return Promise.resolve({ - ok: true, status: 200, - json: () => Promise.resolve( - returnEmptyOps - ? [] - : mockRecordings.map((op) => ({ - id: Number(op.id), - world_name: op.worldName, - mission_name: op.missionName, - mission_duration: op.missionDuration, - filename: `${op.id}.json`, - date: op.date, - tag: op.tag, - })), - ), - } as Response); + const withRecordings = fakeServer(mockRecordings); + const withoutRecordings = fakeServer([]); + mockFetchWith([], { + route: (url, init) => { + if (url.pathname === "/api/v1/auth/me") { + return Promise.resolve(jsonResponse({ authenticated: !returnEmptyOps, role: "admin", steamId: "1", steamName: "Admin" })); + } + if (url.pathname === "/api/v1/auth/logout") { + returnEmptyOps = true; + return Promise.resolve(jsonResponse({})); + } + if (url.pathname === "/api/v1/worlds") { + return Promise.resolve(jsonResponse([{ name: "Altis", displayName: "Isle Display" }])); + } + return (returnEmptyOps ? withoutRecordings : withRecordings)(url.href, init) as Promise; + }, }); const { findByTestId } = renderPage(); @@ -1619,7 +1693,7 @@ describe("RecordingSelector (Admin)", () => { await findByTestId("detail-sidebar"); // Open map filter and search by raw "altis" (displayName is "Isle Display") - fireEvent.click(screen.getByTestId("map-filter-dropdown-trigger")); + fireEvent.click(await screen.findByTestId("map-filter-dropdown-trigger")); const dropdown = await screen.findByTestId("map-filter-dropdown"); const input = dropdown.querySelector("input") as HTMLInputElement; fireEvent.input(input, { target: { value: "altis" } }); @@ -1682,3 +1756,342 @@ describe("RecordingSelector (Admin)", () => { }); }); + +// ─── Server paging ─── + +/** A response the client reads as a failed request. */ +function failedResponse(): Response { + return { ok: false, status: 500, statusText: "Server Error", text: () => Promise.resolve("") } as unknown as Response; +} + +/** The recording list requests made so far. */ +function listRequests(): URL[] { + return (globalThis.fetch as ReturnType).mock.calls + .map(([input]) => new URL(String(input), "http://localhost")) + .filter((url) => url.pathname === "/api/v1/operations"); +} + +function recordingRows(): HTMLElement[] { + return screen.queryAllByTestId(/^recording-\d+$/); +} + +describe("RecordingSelector (server paging)", () => { + const seven: Recording[] = Array.from({ length: 7 }, (_, i) => ({ + id: String(i + 1), + worldName: "Altis", + missionName: `Op ${i + 1}`, + missionDuration: 60 * (i + 1), + date: `2024-01-0${i + 1}`, + tag: "TvT", + })); + + /** Pages of at most three rows, so a short list still spans pages. */ + function smallPage(url: URL): Response { + url.searchParams.set("limit", "3"); + return serveRecordings(seven, url); + } + + beforeEach(() => window.history.replaceState(null, "", "/")); + afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + + it("asks the server for one sorted page at a time", async () => { + mockFetchWith(seven); + renderPage(); + await screen.findByTestId("recording-1"); + const first = listRequests()[0]; + expect(first.searchParams.get("limit")).toBe("100"); + expect(first.searchParams.has("after")).toBe(false); + expect(first.searchParams.has("offset")).toBe(false); + expect(first.searchParams.get("sort")).toBe("date"); + expect(first.searchParams.get("dir")).toBe("desc"); + }); + + it("loads further pages until every match is loaded", async () => { + mockFetchWith(seven, { + route: (url) => (url.pathname === "/api/v1/operations" ? Promise.resolve(smallPage(url)) : undefined), + }); + renderPage(); + await vi.waitFor(() => expect(recordingRows()).toHaveLength(7)); + expect(screen.getByText(/7 of 7 recordings/)).toBeDefined(); + const cursors = listRequests().map((url) => url.searchParams.get("after")); + expect(cursors).toEqual([null, expect.any(String), expect.any(String)]); + expect(listRequests().every((url) => !url.searchParams.has("offset"))).toBe(true); + }); + + it("continues behind the last loaded recording while the list changes", async () => { + const live = [...seven]; + let requests = 0; + mockFetchWith(seven, { + route: (url) => { + if (url.pathname !== "/api/v1/operations") return undefined; + requests++; + // A newer recording arrives after the first page, and a loaded one is + // deleted after the second: an offset would repeat and then skip one. + if (requests === 2) live.push({ ...seven[0], id: "8", missionName: "Op 8", date: "2024-02-01" }); + if (requests === 3) live.splice(live.findIndex((rec) => rec.id === "6"), 1); + url.searchParams.set("limit", "3"); + return Promise.resolve(serveRecordings(live, url)); + }, + }); + renderPage(); + await vi.waitFor(() => expect(listRequests()).toHaveLength(3)); + await new Promise((resolve) => setTimeout(resolve, 50)); + const ids = recordingRows().map((row) => row.getAttribute("data-testid")); + expect(ids).toEqual(["recording-7", "recording-6", "recording-5", "recording-4", "recording-3", "recording-2", "recording-1"]); + expect(listRequests()).toHaveLength(3); + }); + + it("lists a recording once when a page repeats it", async () => { + mockFetchWith(seven, { + route: (url) => { + if (url.pathname !== "/api/v1/operations") return undefined; + const repeated = url.searchParams.has("after") ? [seven[4], seven[0]] : [seven[6], seven[5], seven[4]]; + return Promise.resolve(jsonResponse(repeated.map(rawRecording), { + "X-Total-Count": "4", + ...(url.searchParams.has("after") ? {} : { "X-Next-Cursor": "next" }), + })); + }, + }); + renderPage(); + await vi.waitFor(() => expect(recordingRows()).toHaveLength(4)); + expect(recordingRows().map((row) => row.getAttribute("data-testid"))).toEqual( + ["recording-7", "recording-6", "recording-5", "recording-1"]); + }); + + it("stops loading more after a failed page, and says so, until the list reloads", async () => { + mockFetchWith(seven, { + route: (url) => { + if (url.pathname !== "/api/v1/operations") return undefined; + return Promise.resolve(url.searchParams.has("after") ? failedResponse() : smallPage(url)); + }, + }); + renderPage(); + await vi.waitFor(() => expect(listRequests()).toHaveLength(2)); + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(recordingRows()).toHaveLength(3); + expect(listRequests()).toHaveLength(2); + expect(screen.getByRole("alert").textContent).toContain("Could not load more recordings."); + + fireEvent.click(screen.getByRole("button", { name: "Name" })); + await vi.waitFor(() => expect(listRequests()).toHaveLength(4)); + }); + + it("retries a failed page from where the list stopped", async () => { + let failed = false; + let answerRetry: (() => void) | undefined; + mockFetchWith(seven, { + route: (url) => { + if (url.pathname !== "/api/v1/operations") return undefined; + if (!url.searchParams.has("after")) return Promise.resolve(smallPage(url)); + if (!failed) { + failed = true; + return Promise.resolve(failedResponse()); + } + if (!answerRetry) { + return new Promise((resolve) => { answerRetry = () => resolve(smallPage(url)); }); + } + return Promise.resolve(smallPage(url)); + }, + }); + renderPage(); + const retry = await screen.findByRole("button", { name: "Retry" }); + expect(recordingRows()).toHaveLength(3); + const failedCursor = listRequests()[1].searchParams.get("after"); + expect(failedCursor).not.toBeNull(); + + fireEvent.click(retry); + await vi.waitFor(() => expect(listRequests()).toHaveLength(3)); + expect(listRequests()[2].searchParams.get("after")).toBe(failedCursor); + expect(screen.queryByTestId("load-more-failed")).toBeNull(); + expect(screen.getByTestId("loading-more")).toBeDefined(); + + answerRetry!(); + await vi.waitFor(() => expect(recordingRows()).toHaveLength(7)); + expect(screen.getByText(/7 of 7 recordings/)).toBeDefined(); + expect(screen.queryByTestId("load-more-failed")).toBeNull(); + }); + + it("offers the retry again when it fails too", async () => { + mockFetchWith(seven, { + route: (url) => { + if (url.pathname !== "/api/v1/operations") return undefined; + return Promise.resolve(url.searchParams.has("after") ? failedResponse() : smallPage(url)); + }, + }); + renderPage(); + fireEvent.click(await screen.findByRole("button", { name: "Retry" })); + await vi.waitFor(() => expect(listRequests()).toHaveLength(3)); + expect(await screen.findByRole("button", { name: "Retry" })).toBeDefined(); + expect(recordingRows()).toHaveLength(3); + expect(listRequests()[2].searchParams.get("after")).toBe(listRequests()[1].searchParams.get("after")); + }); + + it("drops pages answered after the filters changed", async () => { + const pending: Array<{ url: URL; answer: (failed?: boolean) => void }> = []; + mockFetchWith(seven, { + route: (url) => { + if (url.pathname !== "/api/v1/operations") return undefined; + return new Promise((resolve) => { + pending.push({ url, answer: (failed) => resolve(failed ? failedResponse() : smallPage(url)) }); + }); + }, + }); + renderPage(); + const search = screen.getByTestId("search-input") as HTMLInputElement; + + // A first page that answers after the search changed is dropped. + await vi.waitFor(() => expect(pending).toHaveLength(1)); + fireEvent.input(search, { target: { value: "Op 1" } }); + await vi.waitFor(() => expect(pending).toHaveLength(2)); + pending[1].answer(); + await vi.waitFor(() => expect(recordingRows()).toHaveLength(1)); + pending[0].answer(); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(recordingRows()).toHaveLength(1); + + // So is a next page, whether it arrives or fails. + fireEvent.input(search, { target: { value: "" } }); + await vi.waitFor(() => expect(pending).toHaveLength(3)); + pending[2].answer(); + await vi.waitFor(() => expect(pending).toHaveLength(4)); + expect(screen.getByTestId("loading-more")).toBeDefined(); + fireEvent.input(search, { target: { value: "Op" } }); + await vi.waitFor(() => expect(pending).toHaveLength(5)); + pending[3].answer(); + pending[4].answer(); + await vi.waitFor(() => expect(pending).toHaveLength(6)); + fireEvent.click(screen.getByRole("button", { name: "Name" })); + await vi.waitFor(() => expect(pending).toHaveLength(7)); + pending[5].answer(true); + pending[6].answer(); + await vi.waitFor(() => expect(pending).toHaveLength(8), { timeout: 2000 }); + expect(pending[7].url.searchParams.get("after")).not.toBeNull(); + expect(screen.queryByTestId("loading-more")).not.toBeNull(); + }); +}); + +// ─── Player search ─── + +describe("RecordingSelector (player search)", () => { + const players: PlayerSummary[] = [ + { name: "Nosey", missions: 3, kills: 5, deaths: 1, lastPlayed: "2024-05-01" }, + { name: "Nomad", missions: 1, kills: 0, deaths: 2, lastPlayed: "2024-04-01" }, + ]; + + function playerRequests(): URL[] { + return (globalThis.fetch as ReturnType).mock.calls + .map(([input]) => new URL(String(input), "http://localhost")) + .filter((url) => url.pathname === "/api/v1/players"); + } + + beforeEach(() => window.history.replaceState(null, "", "/")); + afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + + it("suggests players matching the search and opens their profile", async () => { + mockFetchWith(mockRecordings, { players }); + renderPage(); + await screen.findByTestId("recording-1"); + fireEvent.input(screen.getByTestId("search-input"), { target: { value: "nos" } }); + + const suggestions = await screen.findByTestId("player-suggestions"); + expect(within(suggestions).getByText("Nosey")).toBeDefined(); + expect(within(suggestions).getByText("3 missions")).toBeDefined(); + expect(within(suggestions).queryByText("Nomad")).toBeNull(); + expect(playerRequests()[0].searchParams.get("limit")).toBe("5"); + + const nosey = screen.getByTestId("player-suggestion-Nosey"); + expect(fireEvent.mouseDown(nosey)).toBe(false); + fireEvent.click(nosey); + expect((await screen.findByTestId("players-stub")).textContent).toBe("?name=Nosey"); + }); + + it("opens a suggested player with a Steam UID by it", async () => { + mockFetchWith(mockRecordings, { + players: [{ uid: "76561190000000005", name: "Viper", missions: 2, kills: 4, deaths: 0, lastPlayed: "2024-06-01" }], + }); + renderPage(); + await screen.findByTestId("recording-1"); + fireEvent.input(screen.getByTestId("search-input"), { target: { value: "vip" } }); + fireEvent.click(await screen.findByTestId("player-suggestion-76561190000000005")); + expect((await screen.findByTestId("players-stub")).textContent).toBe("?uid=76561190000000005"); + }); + + it("hides the suggestions on blur and Escape and shows them again on focus", async () => { + mockFetchWith(mockRecordings, { players }); + renderPage(); + await screen.findByTestId("recording-1"); + const input = screen.getByTestId("search-input"); + fireEvent.input(input, { target: { value: "no" } }); + await screen.findByTestId("player-suggestions"); + + fireEvent.blur(input); + expect(screen.queryByTestId("player-suggestions")).toBeNull(); + fireEvent.focus(input); + expect(screen.getByTestId("player-suggestions")).toBeDefined(); + fireEvent.keyDown(window, { key: "Escape" }); + expect(screen.queryByTestId("player-suggestions")).toBeNull(); + }); + + it("does not look up players for a one-letter search", async () => { + mockFetchWith(mockRecordings, { players }); + renderPage(); + await screen.findByTestId("recording-1"); + fireEvent.input(screen.getByTestId("search-input"), { target: { value: "n" } }); + await vi.waitFor(() => expect(listRequests().some((url) => url.searchParams.get("q") === "n")).toBe(true)); + expect(playerRequests()).toHaveLength(0); + }); + + it("shows no suggestions when the player search fails", async () => { + mockFetchWith(mockRecordings, { + route: (url) => (url.pathname === "/api/v1/players" ? Promise.resolve(failedResponse()) : undefined), + }); + renderPage(); + await screen.findByTestId("recording-1"); + fireEvent.input(screen.getByTestId("search-input"), { target: { value: "nos" } }); + await vi.waitFor(() => expect(playerRequests()).toHaveLength(1)); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(screen.queryByTestId("player-suggestions")).toBeNull(); + }); + + it("drops player results for an older search", async () => { + const answers: Array<(found: PlayerSummary[]) => void> = []; + mockFetchWith(mockRecordings, { + route: (url) => { + if (url.pathname !== "/api/v1/players") return undefined; + return new Promise((resolve) => answers.push((found) => resolve(jsonResponse(found)))); + }, + }); + renderPage(); + await screen.findByTestId("recording-1"); + const input = screen.getByTestId("search-input"); + fireEvent.input(input, { target: { value: "no" } }); + await vi.waitFor(() => expect(answers).toHaveLength(1)); + fireEvent.input(input, { target: { value: "nos" } }); + await vi.waitFor(() => expect(answers).toHaveLength(2)); + + answers[1]([players[0]]); + await screen.findByTestId("player-suggestion-Nosey"); + answers[0](players); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(screen.queryByTestId("player-suggestion-Nomad")).toBeNull(); + }); + + it("clearing the filters drops a search still being typed", async () => { + mockFetchWith(mockRecordings, { players }); + renderPage(); + await screen.findByTestId("recording-1"); + fireEvent.input(screen.getByTestId("search-input"), { target: { value: "Bravo" } }); + fireEvent.click(screen.getByTestId("clear-filters")); + await new Promise((resolve) => setTimeout(resolve, SEARCH_DEBOUNCE_MS + 50)); + expect(listRequests().some((url) => url.searchParams.has("q"))).toBe(false); + expect(recordingRows()).toHaveLength(5); + }); + + it("opens the players page from the header", async () => { + mockFetchWith(mockRecordings); + renderPage(); + await screen.findByTestId("recording-1"); + fireEvent.click(screen.getByTestId("players-button")); + expect((await screen.findByTestId("players-stub")).textContent).toBe(""); + }); +}); diff --git a/ui/src/playback/__tests__/engine.test.ts b/ui/src/playback/__tests__/engine.test.ts index 32085c9d..f28f9ced 100644 --- a/ui/src/playback/__tests__/engine.test.ts +++ b/ui/src/playback/__tests__/engine.test.ts @@ -521,6 +521,21 @@ describe("PlaybackEngine", () => { expect(engine.eventManager.getAll()).toHaveLength(2); }); + it("masks the admin password in #login chat commands", () => { + engine.loadRecording(makeManifest({ + events: [ + { frameNum: 1, type: "chat", channel: "Global", fromName: "Nosey", message: " #LOGIN synthetic-password" }, + { frameNum: 2, type: "chat", channel: "Side", fromName: "Nosey", message: "moving up" }, + ], + }), makeMockChunkManager()); + + const chat = engine.eventManager.getAll(); + expect(chat).toHaveLength(2); + expect(chat[0]).toMatchObject({ type: "chat", channel: "Global", fromName: "Nosey", message: "#LOGIN ********" }); + expect(chat[1]).toMatchObject({ type: "chat", message: "moving up" }); + expect(JSON.stringify(chat)).not.toContain("synthetic-password"); + }); + it("uses stamped TFAR settings and skips tfarSettings as a timeline event", () => { const manifest = makeManifest({ radioPropagation: { diff --git a/ui/src/playback/engine.ts b/ui/src/playback/engine.ts index 6330f5be..7475c9bc 100644 --- a/ui/src/playback/engine.ts +++ b/ui/src/playback/engine.ts @@ -21,7 +21,7 @@ import { HitKilledEvent } from "./events/hitKilledEvent"; import { ConnectEvent } from "./events/connectEvent"; import { EndMissionEvent } from "./events/endMissionEvent"; import { GeneralMissionEvent } from "./events/generalEvent"; -import { ChatEvent } from "./events/chatEvent"; +import { ChatEvent, redactLoginCommand } from "./events/chatEvent"; import { CapturedEvent } from "./events/capturedEvent"; import { TerminalHackEvent } from "./events/terminalHackEvent"; import { PlayerSnapshotEvent } from "./events/playerSnapshotEvent"; @@ -70,7 +70,7 @@ function createGameEvent(def: EventDef): GameEvent | null { case "generalEvent": return new GeneralMissionEvent(def.frameNum, id, def.message); case "chat": - return new ChatEvent(def.frameNum, id, def.channel, def.fromName, def.message); + return new ChatEvent(def.frameNum, id, def.channel, def.fromName, redactLoginCommand(def.message)); case "captured": case "capturedFlag": case "contested": diff --git a/ui/src/playback/events/__tests__/chatEvent.test.ts b/ui/src/playback/events/__tests__/chatEvent.test.ts new file mode 100644 index 00000000..ff4fa885 --- /dev/null +++ b/ui/src/playback/events/__tests__/chatEvent.test.ts @@ -0,0 +1,56 @@ +import { describe, it, expect } from "vitest"; +import { ChatEvent, LOGIN_MASK, redactLoginCommand } from "../chatEvent"; + +// Whitespace beyond ASCII, built from code points so the source stays plain. +const NBSP = String.fromCharCode(0xa0); +const NEL = String.fromCharCode(0x85); +const BOM = String.fromCharCode(0xfeff); +const IDEOGRAPHIC_SPACE = String.fromCharCode(0x3000); +const ZERO_WIDTH_SPACE = String.fromCharCode(0x200b); + +describe("redactLoginCommand", () => { + it.each([ + ["#login synthetic-password", "#login ********"], + [" #LOGIN synthetic-password ", "#LOGIN ********"], + ["#Login\tsynthetic password with spaces", "#Login ********"], + ["#loginsynthetic", "#login ********"], + ["#login ********", "#login ********"], + ])("masks the password in %j", (message, masked) => { + expect(redactLoginCommand(message)).toBe(masked); + }); + + it.each([ + ["#login", "#login"], + [" #login ", "#login"], + ])("keeps a bare %j, which has no password", (message, kept) => { + expect(redactLoginCommand(message)).toBe(kept); + }); + + it.each(["#logout", "#log", "say #login later", "", " moving up "])("leaves %j unchanged", (message) => { + expect(redactLoginCommand(message)).toBe(message); + }); + + it("skips the Unicode whitespace the server and the addon skip", () => { + expect(redactLoginCommand(`${NBSP}#login synthetic-password`)).toBe("#login ********"); + expect(redactLoginCommand(`${BOM}${IDEOGRAPHIC_SPACE}${NEL}#LOGIN synthetic-password${NEL}`)).toBe("#LOGIN ********"); + expect(redactLoginCommand(`#login${NBSP}synthetic-password`)).toBe("#login ********"); + expect(redactLoginCommand(`#login${NBSP}${NEL}`)).toBe("#login"); + expect(redactLoginCommand(`${NBSP}say #login later`)).toBe(`${NBSP}say #login later`); + }); + + it("does not count a zero-width space as whitespace, as the server does not", () => { + expect(redactLoginCommand(`${ZERO_WIDTH_SPACE}#login text`)).toBe(`${ZERO_WIDTH_SPACE}#login text`); + }); + + it("uses a fixed mask, whatever the password's length", () => { + expect(redactLoginCommand("#login a")).toBe(redactLoginCommand("#login a-much-longer-password")); + expect(LOGIN_MASK).toBe("********"); + }); +}); + +describe("ChatEvent", () => { + it("keeps the message fields", () => { + const event = new ChatEvent(4, 9, "Side", "Nosey", "moving up"); + expect(event).toMatchObject({ frameNum: 4, id: 9, type: "chat", channel: "Side", fromName: "Nosey", message: "moving up" }); + }); +}); diff --git a/ui/src/playback/events/chatEvent.ts b/ui/src/playback/events/chatEvent.ts index 7806d24f..988600ee 100644 --- a/ui/src/playback/events/chatEvent.ts +++ b/ui/src/playback/events/chatEvent.ts @@ -1,5 +1,32 @@ import { GameEvent } from "./gameEvent"; +const LOGIN_COMMAND = "#login"; + +/** + * Whitespace around a #login command: JavaScript's, which adds U+FEFF to + * Unicode White_Space, and U+0085, which the server and the addon count too. + */ +const LEADING_SPACE = /^[\s\u0085]+/; +const TRAILING_SPACE = /[\s\u0085]+$/; +const ONLY_SPACE = /^[\s\u0085]*$/; + +/** Stands in for everything typed after #login, fixed so it does not reveal the password's length. */ +export const LOGIN_MASK = "********"; + +/** + * Masks the server admin password in an Arma #login chat command. The command, + * matched in any case and ignoring surrounding whitespace, is kept, and + * everything typed after it becomes {@link LOGIN_MASK}; any other message is + * returned unchanged. The addon and the server mask new recordings the same + * way; this covers recordings saved before they did. + */ +export function redactLoginCommand(message: string): string { + const trimmed = message.replace(LEADING_SPACE, "").replace(TRAILING_SPACE, ""); + const command = trimmed.slice(0, LOGIN_COMMAND.length); + if (command.toLowerCase() !== LOGIN_COMMAND) return message; + return ONLY_SPACE.test(trimmed.slice(LOGIN_COMMAND.length)) ? command : `${command} ${LOGIN_MASK}`; +} + /** * A chat message, typed by a player or sent by a script in a player's name * (an engine start-up mod writing "Engine starting..." to the vehicle channel). diff --git a/ui/src/styles/variables.css b/ui/src/styles/variables.css index c2a6e588..e864554e 100644 --- a/ui/src/styles/variables.css +++ b/ui/src/styles/variables.css @@ -83,7 +83,9 @@ /* ── Playback layout ── */ --pb-top-height: 48px; --pb-bottom-height: 94px; - --pb-panel-default-width: 32.5rem; + /* Fits the seven side panel tabs on one row in the longest locale (cs, fi: + 49 label characters at --font-size-md). Narrower viewports wrap them. */ + --pb-panel-default-width: 36rem; --pb-panel-available-width: calc(100vw - 3rem); --pb-panel-width: min(var(--pb-panel-default-width), var(--pb-panel-available-width)); }