72 Commits

Author SHA1 Message Date
11619a4dc6 feat(rust): NPC sides, the faction table, an event's escort, ally and tether (runicnpc stage 5)
RunicNPC stage 5 on the site (docs runicnpc/PLAN.md, D253-D272):

- profiles gain the guard role, faction, relations (its own exceptions),
  alertRadius, turrets, hurtByPlayers, hurtsPlayers and kitUse, checked in
  RunicNPC's order and words, and defaulting to "players only" (D255);
- the faction table: one site-wide table, one row per pair and both ways
  (D254, D268), stored in rust_npc_factions, edited on the NPC profiles page
  (PUT /admin/rust/npcs/factions), pushed to every server with its
  profiles and hashed with them, and a standalone server's own pairs
  adopted at its first push with the site's winning (D244, D251);
- the Place NPCs step takes escort (a Steam id or a {placeholder}), an ally
  (a clan from the new rust.options.clans source, or the team of a player)
  and tether (the zone this event made), for a RunicNPC profile only
  (D269, D270, D272);
- a placement may be held inside a zone (tether, D272);
- the bridge's RunicNPC API floor is 4.

Tests: 488 server, 66 client. routes.manifest.json regenerated against the
pinned core (one route added).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-10-01 07:58:13 -05:00
b83fa8174c Merge pull request 'feat(rust): RunicNPC profiles, placements, event NPCs and per-profile kills (runicnpc stage 4)' (#29) from feat/runicnpc-stage4 into edge
Reviewed-on: #29
2026-09-30 19:52:12 +00:00
a5b9bf434f fix(rust): name the servers in a refused restore
All checks were successful
PR Checks / client-build (pull_request) Successful in 27s
PR Checks / server-tests (pull_request) Successful in 34s
PR Checks / frozen-manifest (pull_request) Successful in -1m12s
The walk read "is on rust-oxide"; it now reads the server's name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-30 08:45:25 -05:00
7eae4a1e62 feat(rust): NPC profiles and placements pages, the profile leaderboard (runicnpc stage 4)
Admin: Rust NPC profiles (the form RunicNPC reads, per server, shared or
fleet, each server's push state and refusals, replaced profiles with
Restore) and Rust NPC placements (the live map: click to place, pins for
every placement; edit, rename, respawn, remove). The live map takes a pick
handler and pins, unchanged for the public page.

Public: the leaderboard ranks by a profile's kills (D250), and opening a
row shows that player's kills by profile (D252); the killfeed names a
RunicNPC NPC by its own name. Player: your own kills by profile. Titles: a
rule on a profile's kills picks the profile. npcs.test.js covers the
profile checks, adoption, the push, the picker and verb, the triggers, kill
crediting, titles and placements (481 server tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-30 04:42:05 -05:00
fa16f0ad2e feat(rust): NPC profile and placement routes, the event picker, triggers and titles (runicnpc stage 4)
Admin: /admin/rust/npcs for profiles (create, change, delete, restore a
replaced one, push now) and each server's placements (list, add from a map
point, change, remove, rename, respawn). Public: the profiles a leaderboard
ranks by, one profile's ranking counted as the profile says (D247, D250), and
one player's kills by profile (D252). Player: your own kills by profile.

The Place NPCs step offers the site's profiles first, then Rust's own
(D243). rust.npc.died and rust.npc.health are triggers a phase can wait on.
A title rule can rank a profile's kills. Swagger fragment, engagement and
route manifests regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-30 04:34:43 -05:00
564a234890 feat(rust): RunicNPC profiles, their push and adoption, per-profile kills (runicnpc stage 4, WIP)
Schema for site NPC profiles (per server, shared or fleet), the per-server
push record, and kills by profile. The push adopts a server's own profiles
before its first push (D244), keeping one whose name a site profile already
has as replaced (D251). The tally's npcProfileKills are stored per profile
and credited to the site profile pushed under that name (D247).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-30 04:21:46 -05:00
b0143801a2 Merge pull request 'feat(rust): the live map draws monuments by label, minor labels hidden (PLAN_REDESIGNS §4, D196, D213)' (#28) from feat/map-marker-labels into edge
Reviewed-on: #28
2026-09-30 00:17:25 +00:00
4035c523cb fix(rust): the fleet's label list prefers a capitalised spelling
All checks were successful
PR Checks / client-build (pull_request) Successful in 22s
PR Checks / frozen-manifest (pull_request) Successful in 41s
PR Checks / server-tests (pull_request) Successful in 7m45s
Found on the walk: the game spells one label "jungle swamp" on both rigs'
maps, and the fleet list printed it that way beside the minor list's
"Jungle Swamp".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 18:19:31 -05:00
b4f71c05cc feat(rust): eight more minor map labels start hidden (D213)
Read from the Carbon rig regenerated at world 6000, seed 981448696, whose map
carries every built-in label: the three that were unverified (Oxum's Gas
Station, Mining Outpost, Ranch) are spelled as written. Adds Canyon B/C,
Lake A, Oasis A/C, Mountain, Train Tunnel Link and Abandoned Cabins, and a
test over that map's 51 real labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 18:12:08 -05:00
0da8f44b55 feat(rust): the live map draws monuments by label, minor labels hidden (PLAN_REDESIGNS §4, D196)
A switch per monument label, a fleet default and a per-server override, on
Admin -> Rust visibility's live map card. Substations, caves, train tunnels,
wells and the other minor labels start hidden; every other label is drawn,
so a monument a game update adds appears. GET /map leaves hidden labels out
of the answer, so the website and the app both lose them.

No schema change: rows are map.marker.<label key> in rust_settings and
rust_map_overrides. No wire change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 12:10:47 -05:00
eb184aaac8 Merge pull request 'feat(rust): chat titles rank twenty-three conditions, and admins name the categories (PLAN_REDESIGNS §5, D172-D175, D209)' (#26) from feat/title-conditions into edge
Reviewed-on: #26
2026-09-29 17:00:52 +00:00
837b84580e Merge edge into feat/title-conditions: §3's zone presets
All checks were successful
PR Checks / server-tests (pull_request) Successful in 24s
PR Checks / frozen-manifest (pull_request) Successful in 36s
PR Checks / client-build (pull_request) Successful in 7m39s
Two conflicts, both additive: schema.sql and purge.sql keep both phases'
tables. Swagger fragment (61 paths) and routes.manifest (67 routes)
regenerated against the pinned core; 455 server and 58 client tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 11:36:00 -05:00
ea2a40320a Merge pull request 'feat(rust): zone presets, and the zone step's options, messages and dome (PLAN_REDESIGNS §3, D210-D212)' (#27) from feat/zones-domes into edge
Reviewed-on: #27
2026-09-29 16:28:08 +00:00
d89ebbdd23 feat(rust): the zone step labels its domes for what they show (D212)
All checks were successful
PR Checks / client-build (pull_request) Successful in 17s
PR Checks / frozen-manifest (pull_request) Successful in 43s
PR Checks / server-tests (pull_request) Successful in 7m44s
Standard is listed first as the full shaded dome and is the default; each
colour says it shows only where it meets the ground or a building.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 09:42:22 -05:00
8361b19c24 feat(rust): zone presets, and the zone step's options, messages and dome (PLAN_REDESIGNS §3, D210)
Admin → Rust zone presets: named sets of ZoneManager flags and settings for
one server, several, or every server (D195), ticked in groups read from each
server's own ZoneManager list in its last hello (D211). A flag not on a
covered server is refused on save with the server named; two presets of one
name may not share a server.

rust.zone.open gains options (one line, NoBuild, radiation=10), enterMessage,
leaveMessage, delivery, dome and domeStack. The options field's dropdown is
rust.options.zone_presets, whose row VALUE is the preset's line, so picking
one copies it into the step (D210) and no published event changes when a
preset does. The line and the dome are checked against the server's hello
on save and in a dry run; bad-option and dome-unavailable are permanent.

Schema: rust_zone_presets, rust_zone_preset_servers. Swagger fragment and
routes.manifest regenerated against the pinned core f0e7d2a.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 05:25:44 -05:00
cf63b902bf fix(rust): the title weapon and plant lists, read off the rig's own item list
All checks were successful
PR Checks / client-build (pull_request) Successful in 26s
PR Checks / server-tests (pull_request) Successful in 30s
PR Checks / frozen-manifest (pull_request) Successful in 43s
A read-only probe walked ItemManager.itemList on rust-oxide (2026-09-29). Revolvers are pistol_revolver, python and hc_revolver; bows add the legacy bow, the mini crossbow and the bowless crossbow and leave out the speargun; melee is every BaseMelee except the pies; blades add the obsidian, sunken and skinning knives and the chainsword; plants add wheat and the two wild berries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-29 02:07:29 -05:00
aea94b5d7a feat(rust): chat titles rank twenty-three conditions, and admins name the categories (PLAN_REDESIGNS §5, D172-D175, D209)
- Schema: fourteen title columns on rust_player_wipe_stats (the two
  best_* distances move by GREATEST, the rest are sums), rust_weapon_kills
  (kills by weapon prefab name) and rust_title_categories (the admin's
  title per category). purge.sql drops the two tables.
- Ingest: player.tally's new fields, in one statement per frame, none
  for an older plugin's frame.
- Titles: 23 categories plus playtime, each naming where it is read
  from (a sum, a MAX, npc_kills - animal_kills in signed arithmetic, or
  a named list). The bow/melee/blade/revolver/wood/ore/plants lists are
  one file, applied when a title is read. "NPC kills" ranks human NPCs
  only (D209).
- A rule's text may be empty, meaning the category's title: the rule's
  own, then the admin's, then the default. Typed-only-markup is still
  refused. A rename forgets every server's cached answer.
- Admin API: GET /admin/rust/title-categories and
  PUT /admin/rust/title-categories/:stat (empty text resets); the server
  list returns them too. Swagger fragment and routes.manifest.json
  regenerated (63 routes, against the pinned core).
- Screen: every category in the rule form, the category's title as a
  placeholder, and a Category titles section with Save and Reset.

The weapon lists are unverified until the rig probe runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-28 23:32:59 -05:00
afb16112b0 Merge pull request 'feat(rust): the permission manager — the site owns the whole store (D160-D163, D188-D198)' (#25) from feat/perm-manager into edge
Reviewed-on: #25
2026-09-28 16:39:11 +00:00
e0d13e73db feat(rust): the permission manager — the site owns the whole store (D160-D163, D188-D198)
All checks were successful
PR Checks / client-build (pull_request) Successful in 21s
PR Checks / frozen-manifest (pull_request) Successful in 43s
PR Checks / server-tests (pull_request) Successful in 7m58s
PLAN_REDESIGNS section 1.

- Every sync reads the store (perm.inventory), reconciles it against the
  site's record and its ledger, and pushes. A change made in the game is
  settled by the server's policy (D161): auto-adopt (default), adopt, or
  revoke. The first read of a server imports everything (D198).
- Groups belong to one server unless an admin shares them (D189), in new
  id-keyed tables; the old ones are copied once at boot and left unread.
  Holders may be a Steam account nobody linked (D188).
- An in-game change affects that server only (D190): a grant that reaches
  further gains an exception, a shared group is split.
- Never judged: a permission the server does not register right now (an
  unloaded plugin is not a revocation), and a pair an event lease holds.
- A new admin API (server view, grant/revoke with everywhere-or-here,
  groups by id, share/split, members, drift answers) and a screen on
  PermissionsManager's flow with a state on every toggle (D162, D163, U-1).
- The announcement voice names a group by id; old name settings still read.

Walked on both rigs against the walk core: import on an existing install,
auto-adopt of a grant and a revoke, a fleet grant's exception, Kits
unloaded without loss, a shared group split, adopt and revoke policies.
Server 420/420, client 58/58, swagger, imports and route manifest current.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-28 06:58:59 -05:00
77c90db338 Merge pull request 'chore(ci): pin core back to main now website#209 has merged' (#24) from chore/repin-core-1.11 into edge
Reviewed-on: #24
2026-09-27 08:59:06 +00:00
0fb6767692 chore(ci): pin core back to main now website#209 has merged
All checks were successful
PR Checks / client-build (pull_request) Successful in 17s
PR Checks / server-tests (pull_request) Successful in 21s
PR Checks / frozen-manifest (pull_request) Successful in 40s
The frozen-manifest job was pinned to website#209's branch head while
MODULE_API 1.11.0 was unmerged. It merged as f0e7d2a on main.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-27 03:28:08 -05:00
65b9ccd161 Merge pull request 'fix(rust): skip servers known down for a link code, hold syncs while offline (F6, F7)' (#23) from fix/protocol-13-step2-walk into edge
Reviewed-on: #23
2026-09-27 08:26:43 +00:00
263be1df45 fix(rust): skip servers known down for a link code, hold syncs while offline (F6, F7)
All checks were successful
PR Checks / client-build (pull_request) Successful in 23s
PR Checks / frozen-manifest (pull_request) Successful in 47s
PR Checks / server-tests (pull_request) Successful in 7m57s
Two findings of the step-2 player walk (2026-09-27, both rigs).

F6, option (b) of the org lead (D186): a code no recent issuer holds -
every made-up one - was still asked of every other enabled server, and
while any of them was down the redeem waited out its whole timeout
(12 s on both rigs). The second pass now skips the servers the board
poll last saw without a connected game; they count as offline without
the wait. Issuers are still asked whatever their state, so a good code
on a down server stays "unsure". Live on the walk core: 338 ms with five
servers down, 360 ms with a rig stopped as well.

F7 (D187): on Carbon a due audit sync went out the moment the sidecar
reconnected, 80 s before "Server startup complete". The worldReady hold
reads the stored hello, which is the OLD boot's until the poll reads the
new one. reasonToSync now also holds while the stored state says the
game is not connected (online 0), which the poll writes the moment the
server goes away. titleSync already held on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-27 03:14:10 -05:00
31b99fab61 Merge pull request 'fix(rust): protocol 13 step 2 — expiry, plugin loads, the loading hold, NPC names, the link fleet (F2 F5 F6 F7 F8 F13 F14)' (#22) from fix/protocol-13-step2 into edge
Reviewed-on: #22
2026-09-27 06:10:01 +00:00
478c52e7a1 ci(rust): pin frozen-manifest to website#209 while coreApi is ^1.11.0
All checks were successful
PR Checks / client-build (pull_request) Successful in 22s
PR Checks / server-tests (pull_request) Successful in 23s
PR Checks / frozen-manifest (pull_request) Successful in 39s
The job cloned a MODULE_API 1.10.0 main and the loader refused the module
("needs core API ^1.11.0, this core is 1.10.0"), so it added no routes and
failed by construction. Pinned to #209's head (cc1f49a), where the job's own
steps pass: core alone 280 routes up to date, with this module 49 routes all
documented. Re-pin to #209's main merge sha once it lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-26 22:08:39 -05:00
b10f11b057 fix(rust): protocol 13 step 2 — expiry, plugin loads, the loading hold, NPC names, the link fleet (F2 F5 F6 F7 F8 F13 F14)
Some checks failed
PR Checks / client-build (pull_request) Successful in 18s
PR Checks / frozen-manifest (pull_request) Failing after 56s
PR Checks / server-tests (pull_request) Successful in 7m45s
The module's half of PLAN_FIXES §6 step 2 (decisions D181-D185, docs#288).

- F13/F14 (D170, D183): `world.expired`, recognisable from protocol 13 by its
  `what`, is handed to core as the resource the zone step ledgered
  (`world`, `<serverId>:<id>`) through ctx.events.expired, which records it
  `expired`. coreApi moves to ^1.11.0 (website#209).
- F8 (D184): `plugin.loaded` / `plugin.unloaded` mark the permission sync dirty
  when the plugin added or removed permissions, so an unresolved grant lands on
  the next tick instead of the fifteen-minute audit.
- Catalogue: plugin.loaded/unloaded, world.expired and lease.expired are staff
  kinds. The last two were never classified (default deny kept them off public
  pages); the test now covers every event kind through protocol 13.
- F7: permission and title pushes hold while the stored hello says
  `worldReady: false` (a human's "sync now" does not); a failed or refused
  permission sync now logs at warn.
- F2 (D185): the killfeed names an NPC attacker — a family (Scientist, Bandit
  guard, Bradley APC…) or the prefab without its variant digits (wolf2 → Wolf).
- F5/F6: a link code is asked of the servers that minted one in the last six
  minutes first, then of the rest, each group in parallel; "unsure" only when
  one of the minting servers is unreachable.
- D182: the admin server list carries the ZoneManager helper's state from the
  hello, and the servers page says what a missing or failed helper costs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-26 21:35:46 -05:00
80c05a3c1e Merge pull request 'fix(rust): protocol 13 — a configuration save that settles after its reload (F9, D179)' (#20) from fix/protocol-13-config-reload into edge
Reviewed-on: #20
2026-09-26 22:41:16 +00:00
fee0b294a9 fix(rust): freeze the write-poll route in routes.manifest.json
All checks were successful
PR Checks / client-build (pull_request) Successful in 16s
PR Checks / server-tests (pull_request) Successful in 19s
PR Checks / frozen-manifest (pull_request) Successful in -1m3s
The new GET /admin/rust/config/:serverId/writes/:writeId was documented in
swagger-fragment.json but not in the committed manifest, so the frozen-
manifest job and frozenManifest.test.js both failed. Regenerated against
core at the pinned ref (efa9db7), exactly as the job does: one route added,
nothing of core's moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-26 17:34:09 -05:00
654a24585d fix(rust): protocol 13 — a configuration save that settles after its reload (F9, D179)
Some checks failed
PR Checks / server-tests (pull_request) Failing after 16s
PR Checks / client-build (pull_request) Successful in 17s
PR Checks / frozen-manifest (pull_request) Failing after 37s
The plugin now answers a save once the files are written, with pending and
a writeId, and reports the reload later as a config.outcome event. The save
is recorded as reloading with a settle_by of two plugin ceilings plus slack
on the database's clock; ingest settles the row by (server, writeId), only
while it is still reloading, so a replay moves nothing and a late outcome
still lands. A row past settle_by reads as lost.

GET /admin/rust/config/:serverId/writes/:writeId serves the poll; the page
polls it every two seconds, holds the Save button while it waits, and says
whether a rolled-back plugin came back on its old file. config.outcome is
a staff kind: it carries the server's log tail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-26 17:16:45 -05:00
36eae7ffa8 Merge pull request 'feat(rust): chat titles, BetterChat group styles, the voice and popups (phase 17)' (#19) from feat/phase-17-integrations into edge
Reviewed-on: #19
2026-09-25 23:31:44 +00:00
0efd5644f6 fix(rust): a bad title mode reaches the form as a sentence
All checks were successful
PR Checks / client-build (pull_request) Successful in 22s
PR Checks / server-tests (pull_request) Successful in 27s
PR Checks / frozen-manifest (pull_request) Successful in 50s
The router's own isIn check answered a mode it did not know with
express-validator's "Invalid value" before titles.validateSettings could
say which words are allowed. Found on the walk; the router now checks shape
only, as every other phase-17 route does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-25 18:23:29 -05:00
1b70cef5be feat(rust): chat titles, BetterChat group styles, the voice and popups (phase 17)
PLAN.md §33, D134-D143. Protocol 12.

- Chat titles (D135-D137): per-server rules (stat, top N, text, colour)
  that rank the current wipe, and a mode (first | all | up to N). Worked
  out once in model/titles and read three ways: pushed whole to the game by
  a new titleSync loop (on change, restart or wipe), and on every
  leaderboard row as `titles`. Admin: PUT /servers/:id/titles.
- Group styles (D138, D139): a site group may carry all twelve BetterChat
  fields (rust_perm_group_chat). They ride perm.sync with `expect` from the
  pushed ledger, which gains a value column; a field changed in game is a
  `chat-field` drift row with the game's value, adopted into the style or
  put back. A withdrawn style is one `chat-group` retirement, never for
  `default`, cleared from the ledger only once BetterChat removed it.
- The voice (D140): one fleet setting naming a styled group; news and
  rust.announce chat lines carry its format and the plugin says them with
  no sender. Admin: GET/PUT /voice.
- Popups (D141, D142): rust.announce gains `delivery` (still version 1,
  from rust.options.delivery); each server gains news_delivery beside the
  news switch; `popup-unavailable` is not retried.
- GET /servers/:id/integrations reads, live, which optional mods a server
  has loaded. README lists BetterChat and PopupNotifications as optional.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-25 17:48:22 -05:00
fb5a581a94 Merge pull request 'feat(rust): slash commands, the next wipe, and the Admin → Rust servers page (phase 16)' (#18) from feat/phase-16-commands into edge
Reviewed-on: #18
2026-09-25 19:18:32 +00:00
cddba957d3 feat(rust): Admin → Rust servers page and the next wipe on the web (phase 16)
All checks were successful
PR Checks / client-build (pull_request) Successful in 26s
PR Checks / frozen-manifest (pull_request) Successful in 49s
PR Checks / server-tests (pull_request) Successful in 7m49s
The module had no page for its own server rows: they were written only
through PUT /admin/rust/servers/:id, and the README described an
"Admin → Rust" server form that did not exist. D133 (org lead) builds it:
add, edit, test and delete a server, with the D130 wipe schedule in the
same form. The token stays write-only and an edit sends the stored
protocol back rather than re-stamping the row.

The next wipe shows on the server list and in the server page's header,
in the reader's own clock, marked "rescheduled" for a one-off date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-25 13:29:59 -05:00
0670341198 feat(rust): slash commands and the next wipe, server half (phase 16)
Five read-only commands registered with api.registerSlashCommands:
/status, /wipe, /top, /online and /clan (D126). Every refusal is private,
and any answer narrower than public (online names, a clan roster) goes
to the caller alone (D127). No command asks a sidecar.

The next wipe (D128, D130): six nullable columns on rust_servers, a pure
nextWipe(row, now) with the zone arithmetic through Intl, computed on
every read. The public server shape gains nextWipe; the admin shape
gains the stored schedule; PUT /admin/rust/servers/:id takes the six
fields and writes them only when wipeRule is present.

server/commands joins ci/bundle.json, which checkBundle caught.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-25 13:29:59 -05:00
cf4d183181 Merge pull request 'feat(rust): the live map (phase 14, protocol 11)' (#17) from feat/phase-14-map into edge
Reviewed-on: #17
2026-09-25 12:00:47 +00:00
0cb9bdd1f0 feat(rust): the live map (phase 14, protocol 11)
All checks were successful
PR Checks / server-tests (pull_request) Successful in 28s
PR Checks / client-build (pull_request) Successful in 27s
PR Checks / frozen-manifest (pull_request) Successful in -1m9s
PLAN.md §30 as approved, plus D119/D120 from the build.

Server:
- rust_map_images (one row per server: picture as MEDIUMBLOB, geometry,
  monuments, DERIVATION_VERSION) and rust_map_overrides; purge.sql pair.
- mapImages.js: D110. The board poll notices a new boot/wipe/seed/size and
  asks map.info; a new key or hash from the free Rust+ cache (or a render
  kept on disk) is fetched in slices, checked against its SHA-256 and stored
  in one statement. One fetch per server, a backoff on failure, `stale`
  abandons a fetch that straddles a map change. Render now (D109) is
  admin-only and watched to completion.
- mapLive.js: D111. One map.live per server per 5 s whoever asks; positions
  are held in memory only.
- model/map: four layers (world, events public; players, bases staff), a
  fleet default plus per-server override (D114), the players layer capped by
  presence (D113), own dot and online first-party clan mates for a linked
  viewer (D115, D117, D118). A layer the viewer may not see is absent from
  the answer, never sent and hidden.
- Routes: public /servers/:id/map, /map/image (immutable under its hash),
  /map/live; admin /servers/:id/map/fetch and /render; the Map card on the
  visibility PUT. Swagger fragment and frozen manifest regenerated.

Client:
- A Map tab: Leaflet over the picture in CRS.Simple, the game's own grid
  (labels only when a cell is wide enough to hold one), a legend that lists
  hidden layers with who can see them, polled every 10 s while visible.
- D120: Leaflet is a lazy split chunk beside entry.js, not in it. release.yml
  copies every dist/*.js; checkExternals and build.test.js hold both ends.
- The Map card on Admin -> Rust visibility, with Fetch again and Render now.

Capability `map` declared for the Android app (phase 15).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-25 01:06:10 -05:00
ac0bcd850a Merge pull request 'feat(rust): the rewards — tally, kit reward, chat and the news leg (phase 13b, protocol 10)' (#16) from feat/phase-13b-rewards into edge
Reviewed-on: #16
2026-09-24 13:02:15 +00:00
42029734ad fix(rust): lowercase the reward option-source ids, and test the grammar
All checks were successful
PR Checks / client-build (pull_request) Successful in 20s
PR Checks / frozen-manifest (pull_request) Successful in 50s
PR Checks / server-tests (pull_request) Successful in 7m45s
The first boot against real core refused the whole module at register:
`rust.options.runZones` fails core's EVENT_ID grammar, which is lowercase
dotted segments only. The fake api validates none of it, so 310 green
tests said nothing. The four fixed-choice sources and the chat-server
source are renamed, and entry.test now holds every action, budget,
lease and option-source id against a copy of the grammar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-24 07:47:01 -05:00
cc185db26b feat(rust): the rewards — tally, kit reward, chat and the news leg (phase 13b, protocol 10)
Four event verbs and the announce leg, per PLAN.md §29:

- rust.participation.open / .collect: the plugin counts who takes part
  (seconds, kills or both, in a zone this run opened or the whole server)
  and collect files them as the run's participants, keyed by Steam id.
- rust.kit.entitle: the five recipient modes (D101), rows in the new
  rust_perm_run_grants (D84) unioned into the permission push, one extra
  use of the kit per reward as site-held credits on perm.sync (D103),
  and the rust.kit.entitled notice deferred from phase 10 (D64).
- rust.announce: one server or every server (D105).
- rust.chat announce leg, speaking only on servers whose new news switch
  is on (D104) - a card on Admin -> Rust visibility (D106).

Budgets rust.grants and rust.announcements; the kit source and four
fixed-choice sources (core has no enum param type). rust_perm_run_grants
carries core's idempotency key so a revert of a lost answer can find its
rows. Protocol 10.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-24 07:00:44 -05:00
9753dda4af Merge pull request 'feat(rust): the world verbs, their budgets and the reconcile watch (phase 13a, protocol 9)' (#15) from feat/phase-13a-world into edge
Reviewed-on: #15
2026-09-24 10:11:01 +00:00
ba636c8939 fix(rust): hold the reconcile until the world is loaded, and never read a refusal as a revert
All checks were successful
PR Checks / client-build (pull_request) Successful in 20s
PR Checks / server-tests (pull_request) Successful in 25s
PR Checks / frozen-manifest (pull_request) Successful in -1m10s
Two defects the phase 13a walk found by restarting the rig mid-run:

- The watch asked core to reconcile the moment a new boot id appeared, which
  is before the game has loaded its save — every crate looked gone and was
  orphaned. It now waits for the plugin's hello to say `worldReady`; an older
  plugin that never says is taken as ready.
- revert() read any 200 as success. On this bridge a refusal is a 200
  carrying world.error (`not-ready` while loading), so every row would have
  been marked reverted with the game still holding every crate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-24 02:16:03 -05:00
fab31f23e8 refactor(rust): one placing verb per kind — rust.crate.place and rust.npc.place (D97)
Core learns which caps an action accepts by pricing its declared examples
once, and drops a dimension priced at zero. A single rust.prefab.place whose
cost moved between rust.prefabs and rust.npcs by its prefab param could only
ever show the crates cap, so D89's separate dial for fights was unreachable.

Two verbs, each pricing exactly one dimension, with the prefab source split
to match (rust.options.crates / rust.options.npcs). The switchboard can now
allow crates and leave NPCs off. The plugin's world.place is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-24 02:09:49 -05:00
a3bcec9cde feat(rust): the world verbs, their budgets and the reconcile watch (phase 13a, protocol 9)
- registerEventActions: rust.zone.open and rust.prefab.place, both
  reversible 'ledger' with revert() and reconcile(), budgetMs 15000 above the
  client's 12 s. A location is a monument (kind + instance, carrying its
  server) or raw coordinates, exactly one (D87, D93); bounds mirrored from the
  plugin so a bad step is refused on the form (D95); zone minutes required and
  held by the game (D96).
- registerEventBudgets: rust.prefabs, rust.npcs and rust.zone.minutes, each
  beside the verb that spends it (D79, D89).
- Option sources rust.options.monuments (live, searchable) and
  rust.options.prefabs (mirrored, answers with every server off), registered in
  the one batch core accepts alongside the lease sources.
- Refs are <serverId>:<id>, since revert and reconcile get no params. The undo
  sends no idempotency key; a lost answer is reverted by key on every server.
  reconcile asks the plugin, and a server that cannot be asked keeps its rows.
- The refresh's bootId/wipeId watch calls ctx.events.reconcile() on a restart
  or a wipe, never on a first sighting or a reconnect (§11.1).
- The permission mirror keeps the plugin's new notLanded grants out of what it
  records as pushed, and the admin page says so (D85).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-24 01:26:57 -05:00
36a5cb975a Merge pull request 'feat(rust): the leases and their option sources (phase 12, protocol 8)' (#14) from feat/phase-12-leases into edge
Reviewed-on: #14
2026-09-24 04:03:23 +00:00
d973db7a43 feat(rust): the leases and their option sources (phase 12, protocol 8)
All checks were successful
PR Checks / client-build (pull_request) Successful in 19s
PR Checks / server-tests (pull_request) Successful in 22s
PR Checks / frozen-manifest (pull_request) Successful in 40s
Four leases on core.lease: rust.decay.scale, rust.population, rust.spawn.scalar and rust.group.permission. Every lease is targeted and the target names the server (D73). Also the three target option sources plus rust.options.servers, with no budgets (D79). Held for up to seven days (D77).

A key that is already held reads as its baseline. Drift is an answer, not a failure. inForce reads the plugin's holds and never compares values. Lease calls get a 4.5s timeout so that two of them fit in core.lease's 10s budget, and a timed-out apply is followed by a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-23 21:14:06 -05:00
2f561b1103 Merge pull request 'feat(rust): notifications and engagement (phase 10, protocol 7)' (#13) from feat/phase-10-engagement into edge
Reviewed-on: #13
2026-09-23 18:43:58 +00:00
648d3fd2e1 fix(rust): every notice says which server, clan or player it is about
All checks were successful
PR Checks / client-build (pull_request) Successful in 18s
PR Checks / frozen-manifest (pull_request) Successful in 43s
PR Checks / server-tests (pull_request) Successful in 7m48s
The live walk rendered a generic in-app notice as "A server came online.
A server's game started..." Core's structural projection falls back to
the trigger's label and description when the payload has no title, and
on a multi-server site that never says which server. Core's rule is that
the payload wins, so every trigger now declares `title` and `intro`, and
the emitter writes the sentence ("Oxide rig is online"). An operator's
own template can still ignore it and use the parts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-23 13:37:05 -05:00
285db0baa7 feat(rust): notifications and engagement (phase 10, protocol 7)
Registers the engagement set R7 put in v1: thirteen triggers, four push
streams, three audiences, four bodies (two triggers, email and in-app)
and thirteen disabled rules in seven groups (PLAN.md §25, D59-D68).

The raid alert goes to everyone authorised on the tool cupboard, one
emit per linked person with ownerUserId, so the owner ceiling holds per
emit. It covers doors and walls (protocol 7), never names the raider,
alerts nobody when there is no cupboard, and carries ownerOnline so
"offline only" is the seeded rule's condition rather than code.

The fan-out runs off ingest before a frame is applied, since applying a
disband deletes the roster the notice is sent to. A replayed event is
told only while it is news: 15 minutes for broadcasts, 24 hours for
personal and staff events. Dedupe keys come from the event, not the
sidecar's row id. Server online/offline and a new kills leader are
in-memory transitions, never on first sight, and a tie is not a lead.
A login with no approval within a minute becomes a staff notice via a
query, so a restart loses nothing.

Also fixes a phase-4 gap (D68): the refresh now asks /health, so a game
that hung, or whose bridge was unloaded, while the sidecar stayed up no
longer reads as online. It stops naming players as online, and a stale
board no longer moves "last seen".

engagement-triggers.json is the committed freeze of all of it, checked
in CI with line endings normalised. The check was verified by breaking
it both ways.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-23 06:06:19 -05:00
dc3c9689b4 Merge pull request 'feat(rust): Teams from first-party clans (phase 9, protocol 6)' (#12) from feat/phase-9-clans into edge
Reviewed-on: #12
2026-09-23 10:33:13 +00:00
c94271104f feat(rust): Teams from first-party clans (phase 9, protocol 6)
All checks were successful
PR Checks / server-tests (pull_request) Successful in 24s
PR Checks / frozen-manifest (pull_request) Successful in 46s
PR Checks / client-build (pull_request) Successful in 8m3s
A first-party Rust clan is a Team (R5). This module becomes the site's
Team provider and answers core from the plugin's `clans` board. Design
of record: docs/modules/rust/PLAN.md §24, D47-D58.

- The store: rust_clans, rust_clan_members and rust_clan_boards. A clan's
  identity is <serverId>:<clanId>:<createdMs> (D52), because the game
  restarts clan ids whenever its clan database version changes.
- The provider (D53): getTeams is complete only when every server's
  board is fresh, supported and untruncated. It is partial when some
  are, and refuses when none are. Freshness is judged by the website's
  clock, from when the board's `t` last advanced.
- Only a complete board may mark a clan gone. A board at the game's
  100-clan ceiling (D55), or one with an unreadable row, proves nothing
  about what it leaves out.
- Leadership is diffed board to board and published (D54). The five clan
  events are published as team.* kinds, and written to the Team feed as
  members-only lines (D49).
- Core only writes feed items for a Team it already holds. So the last 10
  minutes of clan events are re-offered on each board refresh, deduped by
  a sha1 key: core clamps a dedupeKey to 40 characters, and a readable key
  would be truncated into collisions.
- projectRoster and the clan page share one audience rule (D48): the
  clan's linked members and staff by default, re-read from the users row.
  The setting lives on Admin > Rust visibility, which also warns about
  uMod Clans (D47) and the ceiling.
- Public: GET servers/:id/clans (the list is public, D58) and
  GET clans/:externalId. The client adds a Clans tab and
  /rust/clans/:externalId, with three module slots for core's notify,
  activity and forum contributions (D56).
- Linking and unlinking an account ask core to reconcile Teams (D57).
- The clan kinds are staff-class in the public feed allowlist.
- PROTOCOL_VERSION is now 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-23 05:14:18 -05:00
da1a393702 Merge pull request 'fix(rust): nothing names who is online by default' (#11) from fix/presence-visibility into edge
Reviewed-on: #11
2026-09-23 05:36:23 +00:00
be44839896 fix(rust): nothing names who is online by default
All checks were successful
PR Checks / client-build (pull_request) Successful in 27s
PR Checks / frozen-manifest (pull_request) Successful in 51s
PR Checks / server-tests (pull_request) Successful in 8m6s
The org lead's rule, settled 2026-09-22: who is online is always the
narrowest audience - staff - unless an operator deliberately widens it,
and a count is fine where a list of names is not.

The public site broke that in three places since phase 4. The Online
tab named every player, the feed carried joins, respawns, deaths, chat
and tallies, and the leaderboard's lastSeen - refreshed every minute by
a gather tally - said who was on as plainly as either. All three now
sit behind one setting:

* PRESENCE_KINDS, a subset of the public allowlist, gated per request.
  Below the audience the feed keeps the server's own story (wipe, start,
  shutdown) and says presenceHidden rather than looking quiet.
* the Online route answers { players: [], hidden, count, audience } -
  same shape, so an older client renders empty rather than breaking.
* rungs staff / signed_in / public, fleet-wide default in a new
  rust_settings table with an optional per-server override on
  rust_servers; an unknown stored word narrows to staff.
* the viewer's standing is RE-READ from the users row (ctx.users.getById),
  not taken from the token, so a demotion or a ban applies on the next
  request. Walked: a moderator demoted mid-session lost the roll call on
  the same cookie.
* per-viewer answers are Cache-Control: private, no-store.
* GET/PUT /admin/rust/visibility (requireRole admin) and an admin page,
  Rust visibility; every save is one activity-log row.

The browser walk also found every empty state in this module rendering
as a blank box. Core's EmptyState renders children only; this module
passed title/message (the shape the Integration Kit template teaches)
and React dropped both without a word. Fixed module-side with a small
Empty wrapper - nothing core or module-uo renders changes - and a client
test that refuses a titled EmptyState or a PageHeader subtitle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E14m6SuuY6i1vASFeGDBeY
2026-09-23 00:30:08 -05:00
480a99f661 Merge pull request 'feat(rust): what the site has given a player, as the player reads it' (#10) from feat/phase-8-player-permissions into edge
Reviewed-on: #10
2026-09-23 01:52:23 +00:00
c4dda5f85c fix(rust): put the word on the pill, not only the dot
All checks were successful
PR Checks / client-build (pull_request) Successful in 24s
PR Checks / server-tests (pull_request) Successful in 25s
PR Checks / frozen-manifest (pull_request) Successful in 47s
A filled circle beside a hollow one is the whole difference between "you
have this in game" and "you do not yet", which is more than a shape should
have to carry — and a reader who cannot tell the two apart gets no answer
at all. The pill now reads "<server> · has it" or "<server> · waiting",
which is also what the app's leg says, so the two surfaces describe the
same state in the same words.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-22 20:32:34 -05:00
383e89442e feat(rust): what the site has given a player, as the player reads it
Phase 8's website half. Phase 7 made the site the author of in-game
privilege and gave an operator every view of it; this is the other side,
and it is the first time a player can see what they hold without asking
one.

`GET /player/rust/permissions` is self-scoped in SQL and read-only by
construction — a grant a player could change would not be a grant. Three
things make it a different shape from the admin read rather than a
filtered one:

  * the scope arithmetic is answered on the server. A client handed `*`
    would have to know what the fleet is to say anything, and then
    `inScope` exists twice. Each entry carries the servers it reaches,
    already resolved and already marked.
  * `live` is the pushed ledger, never the authored row. A grant is not a
    privilege in a game until a sync confirmed it, and phase 7 is careful
    never to record a push that silently did nothing — so "waiting" is
    honest, and the alternative is the site claiming to have given
    something it has not.
  * nothing says WHY it is waiting. An offline server, a permission no
    loaded plugin registered and a store that has never seen the account
    all look the same from here; telling them apart is an operator's
    diagnosis and an inventory of what is installed.

An entitlement that reaches nobody still lists, and the page says so —
authored against the website account, it exists before a Steam id does,
and hiding it until one turns up is the defect the admin user page
shipped in phase 7 (PLAN.md §20.5).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-22 20:09:51 -05:00
47756d392a Merge pull request 'feat(rust): mod configuration from the site, and an editor that will not rewrite a float' (#9) from feat/phase-7b-config into edge
Reviewed-on: #9
2026-09-22 15:02:18 +00:00
e54ae3afb9 feat(rust): mod configuration from the site, and an editor that will not rewrite a float
All checks were successful
PR Checks / server-tests (pull_request) Successful in 18s
PR Checks / frozen-manifest (pull_request) Successful in 51s
PR Checks / client-build (pull_request) Successful in 7m56s
R18's two tiers: a form generated from a config file's own values, and raw JSON
for what a form cannot express. Admin → Rust mod config, one live round trip per
action, nothing cached between a browser and a game host's disk.

`configEdit.js` is the part that could not be done naively. JavaScript cannot
tell `1` from `1.0`, and both mod frameworks deserialize a config into typed C#
classes — so a read-modify-write silently rewrites every whole-numbered float as
an integer on fields nobody touched, and a plugin that then throws at load does
not come back. It never parses, mutates and re-serialises: it records the SOURCE
SPAN of every value and splices literals into them, so an untouched `1.0` is
still `1.0` and a number an admin types travels as text the whole way (D35/D36).

The bridge's own config is editable with `Host`, `Port` and `ServerId` locked,
in the form and in the raw tier, because either would cut the link carrying the
edit or strand every row this site holds (D38). Credentials render masked with a
reveal; the raw tier shows them (D37) and the audit trail never does.

`rust_config_writes` records every save including the refused and the rolled
back — an operator asking why a setting is not what they set needs to see that
somebody tried.

Three defects a browser walk found that 179 green tests did not:

* every save of the bridge's own config was refused while the page said the
  opposite — a `<select>` whose value matches no `<option>` shows the first one,
  so the reload guess `RunicGateway` was on the wire and "nothing" was on the
  screen;
* `btn ghost` is not a class this platform defines (`.btn-ghost` is), so every
  secondary button in this module has rendered as a primary one since phase 7 —
  here it made the open file and the active tier indistinguishable;
* a save's refusal rendered at the top of a long form, far from the button.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-22 08:55:28 -05:00
b1abd87c3d Merge pull request 'feat(rust): site-owned permissions — the site is the author, the game is the cache' (#8) from feat/phase-7-permissions into edge
Reviewed-on: #8
2026-09-22 06:53:21 +00:00
f35e70e7d3 docs(rust): record why a nested router needs nothing from the fragment generator
All checks were successful
PR Checks / client-build (pull_request) Successful in 14s
PR Checks / server-tests (pull_request) Successful in 15s
PR Checks / frozen-manifest (pull_request) Successful in 35s
The opposite of the hole phase 6 found: the registration walk cannot see a
router mounted with `use()`, and swagger-autogen can — it reads a file and
follows its requires, so `/rust/permissions` is generated with the right prefix
from `rust.router.js` alone. Worth a comment where somebody will otherwise add
a fifth constant to make it work.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-21 18:28:58 -05:00
43147b796a feat(rust): site-owned permissions — the site is the author, the game is the cache
R2, and the first phase where this module WRITES to a game. Groups and grants are
authored on the website and pushed into each server's own permission store, so
every plugin that already calls `UserHasPermission` honours them with no adapter,
and a wipe stops being a data-loss event.

**Seven org-lead decisions (D28-D34).** A grant is keyed to the website USER and
resolved to every Steam id they have linked at push time (D28); every authored row
carries a scope — a server or `*` (D29); groups are mirrored as real groups rather
than flattened (D30); a holder the site did not author is REPORTED, never undone,
with adopt and revoke offered (D31); one verb, with the plugin diffing locally
(D32); a permission no server has registered is reported unresolved and never
self-registered (D33); authoring is people and groups by hand, with rules deferred
(D34).

**Three sets, and every interesting question is a difference between two.**
`desired − pushed` is what to apply; `pushed − desired` is what to RETIRE, because
the site put it there and has since withdrawn it; `present − desired` is drift. The
middle one is why `rust_perm_pushed` exists: a name in the store that is not in the
desired set is either something the site retired or something a human granted, and
those two have opposite correct answers.

**What lands is not what was sent.** A grant naming a permission the server has not
registered did not land — `GrantUserPermission` no-ops silently — and a member the
store has never seen could not be placed. Neither is recorded as pushed, so the
site never believes it gave a privilege it did not.

The loop asks a cheap question every thirty seconds — does the digest of the
desired set still equal what this server last confirmed — and syncs on a change, a
restart, a wipe, a drift hook, a failed attempt past its backoff, or the
fifteen-minute audit that finds drift on a server nobody has touched.

**This module's first admin page**, because a permission model is the first thing
here that has to be composed rather than configured. What is on it is decided by
what an operator can get wrong: four states are invisible from the game and from a
list of grants, and each is a sentence rather than a number.

Walked end to end against a real core at the pinned ref, the real sidecar, and a
stand-in speaking protocol 4 — including a restart that emptied the store and was
fully re-pushed. Four defects the browser found that 133 green tests did not.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-21 18:28:32 -05:00
a1b6d155a1 Merge pull request 'fix(rust): answer refusals in the field core reads, and show the name the game last saw' (#7) from fix/phase-6-refusal-sentences into edge
Reviewed-on: #7
2026-09-21 22:39:43 +00:00
0876a1d568 fix(rust): answer refusals in the field core reads, and show the name the game last saw
All checks were successful
PR Checks / server-tests (pull_request) Successful in 15s
PR Checks / frozen-manifest (pull_request) Successful in 48s
PR Checks / client-build (pull_request) Successful in 7m49s
The two defects the phase 6 browser walk found and #6 described but did not
carry. They were written, walked and left uncommitted; `edge` still has the
shapes the walk condemned.

**Every refusal sentence was invisible.** Core's request primitive reads one
field — `(data && data.message) || res.statusText` — and this module has
answered `{ error: … }` since phase 1. It got away with it because every
failure until phase 6 landed in `ErrorState` on a page whose whole content was
missing, where a generic sentence is honest. A form is different: the sentence
IS the outcome, and the link page showed *Service Unavailable* for all four of
the refusals phase 6 exists to write. All 23 bodies now answer in `message` —
core's `Error` schema, which these routes' own `#swagger.responses` already
referenced, so the annotations stop being a claim the handlers contradict.

`test/errorShape.test.js` drives each outcome rather than grepping for the
field, and asserts the half that is easy to leave behind: a body carrying BOTH
fields renders correctly in a browser and keeps the wrong shape alive for the
next route that copies it.

**The player saw a stale name.** `/player/rust` showed the name recorded at
link time while the admin panel showed the one the game last saw — the same
person labelled two ways on one site, because a Rust name changes on a whim and
only the admin read joined `rust_players`. A LEFT JOIN, because an account can
be linked and never played on.

123 server tests, 39 client tests, `check:imports`, `check:bundle`,
`check:swagger`, `check:externals` — all green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-21 17:34:21 -05:00
f3e274b33d Merge pull request 'feat(rust): identity — a link code from the game, and the Steam id inside core's user page' (#6) from feat/phase-6-identity into edge
Reviewed-on: #6
2026-09-21 22:25:15 +00:00
0a1e558942 test(rust): grow the mount check for the slot it predicted
All checks were successful
PR Checks / server-tests (pull_request) Successful in 42s
PR Checks / client-build (pull_request) Successful in 44s
PR Checks / frozen-manifest (pull_request) Successful in -50s
`the manifest and the module's declared mounts agree` was written in phase 1 with
its own exception named in a comment: when `admin.users.detail` arrives, its
routes live on a resource core owns and the test must grow the exception
deliberately rather than let a route outside every declared mount arrive
unnoticed. This is that growth, and the test did its job — it failed on the first
run after the slot was filled.

A route is now legitimate if it is under a declared prefix OR under the mount of
a slot `module.json` declares, and a declared slot that contributes no route
fails too: core never checks that a declared slot was filled (`checkDeclared`
covers `mounts` alone), so this is the only place an exception widening the check
for nothing is noticed. Verified by pointing the slot mount at a path nothing
serves and watching it fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-21 08:19:41 -05:00
baffaa46c9 feat(rust): identity — a link code from the game, and the Steam id inside core's user page
R1's identity link, site-side, and R13's first extension slot. A player types
/link in game, the plugin hands them a six-character code privately, and they
enter it here; the site records who owns which Steam account, and an operator
sees that on core's own `/admin/users/:id` page.

**The site is the author of record and the game holds nothing.** There is no
per-account store in Rust that survives a wipe, and phase 7 needs the site
authoritative anyway — it pushes permissions INTO the game keyed by Steam id. A
copy in the game would be a second thing to reconcile every wipe, for no question
it could answer better.

## D24 — a code is minted by ONE server, so every server is asked

Nothing in six characters says where it came from. The fleet is asked in turn and
the first `link.ok` wins; the others answer `unknown` and nothing happens there,
because a code is only spent at the server that actually holds it. Asking the
player to pick was rejected: a wrong pick would come back indistinguishable from
a wrong code, and that is the one refusal which must not be ambiguous.

**"Every reachable server refused" is not the same answer as "a server was
unreachable."** Collapsing them tells a player whose server is down that their
code is wrong — so they run /link again on that same server and are told the same
thing for as long as it stays down. `unsure` is that case, and it says to try
again rather than to fetch a new code.

## D23 — a Steam id another account holds is refused, never moved

The primary key is `steam_id`, and it is load-bearing rather than tidy: phase 7
grants permissions against a link and phase 13 hangs entitlements off it, so a
silent move is an account takeover performed by typing six characters. The
refusal names the holder, because the advice is unusable without it. The INSERT
is a plain INSERT for the same reason — `ON DUPLICATE KEY UPDATE` here would BE
that move — and the duplicate-key error is the refusal for the race the check
above cannot close.

The way out is `/unlink` in game, which reaches the site off the ingest feed
rather than through a route (the plugin has no link to delete). D25 adds the
other way out: staff can sever a link from the admin panel, for a player who
cannot reach that Steam account in game.

## The slot, and the hole it found in this repo's own generator

`admin.users.detail` is declared in `module.json` AND registered in `index.js`
AND filled by the chunk — three places, because the server half and the client
half are different registrations that share one name.

`swaggerFragment.js` knew only about tier routers, so the two routes under
`/admin/users/:id` were generated by nothing: a fragment that was internally
consistent and described two routes fewer than the module serves. A slot's mount
is core's and cannot be derived here, so it is a fourth constant beside
`TIER_BASE` — held to account by the frozen-manifest job, which was verified to
catch exactly this by removing the two paths and watching it fail.

## Smaller things worth knowing

- **Core's `useAsync` has no `refresh`.** A counter in the deps is how a page
  re-reads after its own write; it blanks while it re-reads, which is right here
  and is exactly what made it wrong for a poll.
- **Every player-portal nav row needs an `icon`** — core draws one on every row,
  and the client suite says so. This module had no icons file until now, because
  the public header is text buttons.
- The two new frame kinds are STAFF-only. Neither carries a code, but both name a
  Steam id beside a website account's activity, and that join is not a public
  fact about what happened on a server.
- The link code route carries its own rate limiter rather than core's
  `accountChangeLimiter`: this is guessing somebody else's secret, not changing
  your own password, and a shared counter would let one policy set the other.

Protocol 3 on all three declaration sites; 17 new tests, 136 green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMH6bw1jXMgbyF3ZWGEzSM
2026-09-21 08:18:48 -05:00
28e46771b1 Merge pull request 'feat: declare rust as the module's identity capability (phase 5, D16)' (#5) from feat/phase-5-capability into edge
Reviewed-on: #5
2026-09-17 09:22:12 +00:00
8df850f73e feat: declare rust as the module's identity capability
All checks were successful
PR Checks / server-tests (pull_request) Successful in 14s
PR Checks / client-build (pull_request) Successful in 14s
PR Checks / frozen-manifest (pull_request) Successful in -1m4s
Phase 5 is the Android app's leg of this module's read path (R10), and it
gates its Rust navigation on one capability string the way `module-uo`'s five
shard rows gate on `shard`. There was no such string here: the five this module
declared all name a SURFACE, and core flattens every started module's
capabilities into one list, so `servers` is a word another module could declare
tomorrow and silently reveal these screens on a site that does not run Rust.

`rust` is the string only this module can mean. It is asserted against
`module.json`'s own `id` rather than a literal, so the two cannot drift.

The README says why it is not redundant with `id`: `id` is a mount prefix, and
MODULE_API.md §2.9 forbids a client inferring a route from a capability. Gating
on `id` would quietly make those the same thing.

Decided by the org lead as D16, 2026-09-16.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016wDDVXWMDz82WqE1i969r4
2026-09-16 21:55:17 -05:00
7e1f037aad Merge pull request 'feat: the first pages, and what a browser walk found behind them' (#4) from feat/phase-4-first-pages into main
All checks were successful
Release / release (push) Successful in 20s
Reviewed-on: #4
2026-09-17 02:43:27 +00:00
22fd8c5da7 feat: the first pages, and what a browser walk found behind them
All checks were successful
PR Checks / client-build (pull_request) Successful in 15s
PR Checks / frozen-manifest (pull_request) Successful in 36s
PR Checks / server-tests (pull_request) Successful in 7m58s
Phase 4. `/rust` is the server list and the module's landing page (D12);
`/rust/servers/:id` is one server with four tabs — feed, leaderboard, who is
on, wipes (D13). Everything selectable lives in the URL, so any view of the
page is a link. The feed and the presence list poll every twenty seconds while
the tab is visible and not at all when it is not (D14); the leaderboard and the
wipe list load once. `site.footer.status` is filled with a live server and
player count (D15).

Nothing on these pages calls a game server. Every field comes from this
module's own tables, which is what the phase criterion is about: the site
renders the last thing each server said while every server is off.

Walking that criterion in a browser against a live rig found four defects, two
of them already shipped in phase 3:

  * An unreachable refresh called `putState` — the whole-row write — with two
    fields, so a host that rebooted lost its hostname, map, size, seed and wipe
    id. The list then read "Offline" with nothing beside it, which is not "here
    is what we know" but "we have never heard of it". `markUnreachable` now
    moves three columns and mentions no others.
  * "Last reported" read `updated_at`, which a FAILED poll writes too — so an
    offline server claimed it had reported just now, every thirty seconds, for
    as long as it stayed down. `last_seen_at` is the new column, moved only by a
    frame that arrived.
  * Feed rows showed a bare time of day, so three events from six weeks ago all
    read as this afternoon once the feed was filtered to a past wipe.
  * `/rust/servers/typo` rendered core's ErrorState under its own heading and
    read "No such server / Something went wrong", sending a reader who mistyped
    a URL looking for an outage.

Also: a detail route (`GET …/servers/:id`), because it is the only route under
that path that can say a server does not exist — the other four answer an empty
list for an id nobody configured, and each of those is a good answer to its own
question.

`useAsync` cannot poll: it blanks its data on every dependency change, so a
twenty-second refresh built on it would clear the killfeed and re-fill it four
times a minute. `hooks/usePolled.js` is the module's own, invisible when it
succeeds and keeping the rows when it fails.

The client test fake was *nearly* core — it prefixed routes without stripping
the trailing separator, so the first module to register an index route failed
the nav check for a link that works in a browser. It now copies core's line
character for character.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016wDDVXWMDz82WqE1i969r4
2026-09-16 21:40:28 -05:00
5ce711048c Merge pull request 'feat: ingest protocol 2, and keep the record a wipe cannot erase' (#3) from feat/phase-3-protocol-2 into main
All checks were successful
Release / release (push) Successful in 20s
Reviewed-on: #3
2026-09-16 16:37:14 +00:00
f211969ee1 feat: ingest protocol 2, and keep the record a wipe cannot erase
All checks were successful
PR Checks / client-build (pull_request) Successful in 17s
PR Checks / frozen-manifest (pull_request) Successful in 44s
PR Checks / server-tests (pull_request) Successful in 7m57s
The module half of the read path. Seven tables, an ingest cursor, four public
routes, and one file whose only job is deciding who may see what.

**The record and the window are different things.** `rust_player_wipe_stats` and
`rust_gather_totals` are permanent and per-wipe, so all-time is those rows SUMmed
rather than a second set of counters that can disagree with them — that is R12's
"per-wipe detail plus all-time rollups" in one table instead of two.
`rust_events` is a bounded 30-day window of raw frames for the killfeed, and
`rust_presence` is a board: replaced wholesale, never appended.

**The feed is a cursor, not a socket, and the header says why.** Core runs Node
20, where a global WebSocket is still behind a flag, so a socket means taking
`ws` — against a release that asserts it has no runtime dependencies (D5). The
deciding argument is the other one though: a socket needs a cursor anyway, for
whatever it missed while the module was restarting, and the catch-up path is the
one that has to be right. A cursor alone is one mechanism exercised every five
seconds rather than two where the second only runs after an outage.

**The cursor advances after the batch, never before.** A crash between the two
re-reads events already counted, which inflates a total; the other order loses
them silently and for ever. One is visible and bounded, the other is invisible
and permanent, so the code fails in the visible direction. A server with no
cursor starts at the sidecar's current END rather than at zero — replaying a
fortnight of deaths into stats for wipes the site never saw is not a catch-up.

**`catalogue.js` is a security boundary, default-deny.** Protocol 2 carries IP
addresses (login attempts, approvals, bans), one player's report about another,
and the grid reference of somebody's base. They are stored, because an operator
chasing ban evasion needs them; they are not served below the admin tier. The
allowlist lives here rather than as a field on the wire, because a boundary
declared by the sender is one a compromised or merely out-of-date game host can
widen — the same reason core's own shard fan-out filters on the serving side. A
kind this build has never heard of is not public, and a test holds the list
against PROTOCOL.md §8.4 so that adding a kind to the protocol without
classifying it fails a build.

`PROTOCOL_VERSION` goes to 2 here in the same change as the emitters, though this
module consumes none of the new frames yet: the sidecar refuses a mismatched
client with a 409, so a module left on 1 would stop being able to read the board
it has been reading all along. A constant that lags the deployment is an outage
with a version number on it.

95 server tests, 20 client tests, every guard green, and `routes.manifest.json`
regenerated against a real core at the pinned ref: 10 routes, all documented,
none of core's moved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016wDDVXWMDz82WqE1i969r4
2026-09-16 08:37:16 -05:00
166 changed files with 54820 additions and 201 deletions

View File

@@ -130,6 +130,9 @@ jobs:
- name: Check the OpenAPI fragment is current (MODULE_API.md §2.8)
run: npm run check:swagger --prefix server
- name: Check the engagement freeze is current (PLAN.md §25)
run: npm run check:engagement --prefix server
client-build:
runs-on: ubuntu-latest
timeout-minutes: 20

View File

@@ -336,10 +336,13 @@ jobs:
cp -r "server/$d" "$OUT/server/"
done
# The client half is the BUILT chunk only. `client/src` is source an
# operator has no use for and core will never read.
# The client half is the BUILT chunks only. `client/src` is source an
# operator has no use for and core will never read. Every `.js`, not
# `entry.js` by name: since D120 the Map tab imports Leaflet's split
# chunk from beside it, and a release that shipped the entry alone
# would load everywhere and spin for ever on that tab.
mkdir -p "$OUT/client/dist"
cp client/dist/entry.js "$OUT/client/dist/"
cp client/dist/*.js "$OUT/client/dist/"
# Prove the bundle is loadable before it is published: these are the
# paths core's loader resolves out of module.json, and a release whose

View File

@@ -36,17 +36,100 @@ rows here; the website core never learns there is more than one.
| Surface | Route |
|---|---|
| Public | `GET /api/v1/public/rust/servers` — every server and what it last reported |
| Player | `GET /api/v1/player/rust/servers` — the same, on the authenticated tier |
| Admin | `GET/PUT/DELETE /api/v1/admin/rust/servers` and `POST …/:id/test` |
| Page | `/rust/servers` |
| Public | `GET …/servers/:id` — one server, or a `404`; the only route under `:id` that can say a server does not exist |
| Public | `GET …/servers/:id/events` — the feed, served from a default-deny allowlist (`server/catalogue.js`) |
| Public | `GET …/servers/:id/leaderboard` — per wipe, or all-time as those rows summed; each row carries the player's chat titles |
| Public | `GET …/servers/:id/wipes` and `…/online` |
| Public | `GET …/servers/:id/clans` — the server's clans, best score first (public: names nobody) |
| Public | `GET /api/v1/public/rust/clans/:externalId` — one clan, and its roster inside the roster audience |
| Player | `GET /api/v1/player/rust/servers` — the server list, on the authenticated tier |
| Admin | `GET/PUT/DELETE /api/v1/admin/rust/servers` and `POST …/:id/test` — the `PUT` carries the wipe schedule |
| Admin | `GET/PUT /api/v1/admin/rust/visibility` — who may see who is online, fleet-wide and per server |
| Admin | `PUT …/servers/:id/titles`, `GET …/servers/:id/integrations`, `GET/PUT /api/v1/admin/rust/voice` — chat titles, the optional mods a server has, and the announcement voice |
| Pages | `/rust` — the server list, and the module's landing page |
| Pages | `/rust/servers/:id` — one server: feed, leaderboard, who is on, wipes, clans |
| Pages | `/rust/clans/:externalId` — one clan, with core's Team notify, activity and forum in three module slots |
| Pages | `/admin/rust/servers` — add, edit, test and remove servers, set each one's wipe schedule and chat titles, and choose the announcement voice |
| Discord | `/status`, `/wipe`, `/top`, `/online`, `/clan` — read-only, answered from this module's tables |
| Teams | The deployment's Team provider: a first-party Rust clan is a Team |
| Slot | `site.footer.status` — a live server/player count in core's footer |
Two tables, `rust_servers` (configuration) and `rust_server_state` (what each sidecar reported).
**Nothing names who is online by default.** The Online list, every feed item that says a named
player was on the server (connects, respawns, deaths, chat, gather tallies) and the leaderboard's
"last seen" reach **staff** unless an operator widens them in Admin → Rust visibility — fleet-wide,
with an optional override per server. How many players are online is public at every setting. The
viewer's standing is re-read from the database on each request, so a demotion or a ban applies at
once rather than when a token expires.
The rest of the module — identity, site-owned permissions, Teams from Rust's clans, notifications,
events, the live map, Discord commands — arrives phase by phase. **Nothing is registered before it
Every page reads this module's own tables and never calls a game server, which is what lets the
whole surface render while every server in the fleet is off. Tab, feed filter, wipe and leaderboard
sort all live in the URL, so any view of it is a link.
Seven tables: `rust_servers` (configuration), `rust_server_state` and `rust_presence` (observed
state), `rust_wipes`, `rust_players`, `rust_player_wipe_stats` and `rust_gather_totals` (the record a
wipe does not erase), plus the bounded `rust_events` window and the `rust_ingest_cursor`.
**Teams come from Rust's own clans**, not from the uMod Clans plugin, which is optional and whose
clans never become Teams. A clan's roster reaches its own members and staff unless an operator
widens it in Admin → Rust visibility; its name, colour, score and count are public. The game lists
at most 100 clans per server, and a server at that ceiling answers core partially, so core never
removes a Team on its word. Core holds one Team provider per site, which is one reason **a site runs
one module**: core's installer refuses a second.
**The next wipe is the operator's to state** (Admin → Rust servers): a rule — the monthly forced
wipe only, weekly or every other week, each in the server's own time zone and always including the
forced wipe (first Thursday, 19:00 UK time) — plus an optional one-off date that replaces the next
computed wipe. It is computed on every read and never stored, so it cannot go stale after a wipe.
The server list, the server page, the Android app and `/wipe` all show it.
**Two uMod plugins are optional, and the module works without either** (`docs/modules/rust/PLAN.md`
§33). The bridge plugin's hard requirements are **Kits** and **ZoneManager**.
- **BetterChat** (LaserHydra, 5.2.15). With it: **chat titles** an operator sets per server — "top 3
playtime", "#1 kills" on the current wipe — shown in game chat and beside the name on the web and
app leaderboards; and a **chat style** on any permission group this site authors, all twelve of
BetterChat's group fields, mirrored like the group's permissions (a field changed in game is
reported, never overwritten). Without it the titles still show on the web and the app, and the
styles wait until it is installed.
- **PopupNotifications** (k1lly0u, 0.2.1). With it: `rust.announce` and a server's news posts can be
a popup instead of a chat line. Without it a popup is refused with a sentence saying so, and chat
works as before.
News and event lines said in chat can wear one styled group's title and colours — the
**announcement voice**, chosen in Admin → Rust servers. The line is said by the bridge plugin with no
player as its sender, so it looks the same with or without BetterChat.
**The Discord commands answer from the tables, never from a game server**, inside core's three-second
budget. Every refusal is private. **An answer narrower than public goes to the caller alone:** a
moderator's `/online` in a public channel shows the names to the moderator, never to the channel, and
the same for a clan roster. Everything else is posted where it was asked.
The rest of the module arrives phase by phase. **Nothing is registered before it
has something behind it:** a declared trigger nothing emits and a declared slot nothing fills are
both surfaces an operator can configure and then wait on, which is worse than an absent one.
### What a client feature-detects on
`module.json` declares six capability strings, and `GET /api/v1/public/modules` hands them to any
client that asks — the website's own nav, and the Android app (`docs/modules/rust/PLAN.md` R10).
Five of them name a surface: `servers`, `killfeed`, `leaderboard`, `presence`, `wipes`.
The sixth is `rust`, and it names **the module itself**. It looks redundant beside `id`, and it is
not, for two reasons worth writing down before somebody tidies it away:
- **A client that asks "is this module installed" has nowhere else to ask.** Core flattens every
started module's capabilities into one list, so `servers` alone is a word another module could
declare tomorrow and silently reveal this one's screens. `rust` is the string that can only mean
this module, and it is the single gate a whole navigation group hangs on — exactly the job `shard`
does for `module-uo`.
- **`id` answers a different question.** It is a *mount prefix* (§2.1 requires it to equal the
directory core loads the module from), and `MODULE_API.md` §2.9 is explicit that a client must
never infer a route from a capability. Gating on `id` would quietly make the two the same thing,
and the day a client builds `/<id>/servers` from it, the contract that lets this module move its
own pages is gone.
An unknown capability is absent, and no route is ever derived from one.
## Build and check
```bash
@@ -128,8 +211,8 @@ directory; a symlink answers no and the module is skipped in complete silence.
Either way, the module appears when the process restarts: the volume is read at require time.
Then, in Admin → Rust, add a server: its name, the sidecar's base URL, and the token the sidecar
printed on first start (`rust-link-sidecar --print-config`). **The token is write-only** — it is
Then, in Admin → Rust servers, add a server: its name, the sidecar's base URL, and the token the
sidecar printed on first start (`rust-link-sidecar --print-config`). **The token is write-only** — it is
stored encrypted through core's own secret box and never returned to any client; the panel reports
only whether one is set.

View File

@@ -28,15 +28,29 @@
],
"server": [
"boot.js",
"catalogue.js",
"commands",
"configEdit.js",
"core.js",
"db",
"engagement",
"eventLeases.js",
"eventRewards.js",
"eventWorld.js",
"index.js",
"ingest.js",
"mapImages.js",
"mapLive.js",
"model",
"npcSync.js",
"package.json",
"permSync.js",
"router",
"sidecarClient.js"
"sidecarClient.js",
"titleSync.js"
],
"root": [
"engagement-triggers.json",
"swagger-fragment.json",
"LICENSE.md",
"README.md"

View File

@@ -1,6 +1,6 @@
{
"$comment": "The core this module is proved against. MODULE_API.md §5.3: the frozen-manifest job clones RunicGateway/website at this exact ref, drops this module in as modules/rust and runs CORE's own routeManifest.js — nothing else can answer whether the URLs the module claims are the URLs it actually serves, because a mount prefix is a string in server/index.js and a documented path is a string in a JSON file, and whether those name the same URL is a fact about a running core. It also answers the blind spot phase 1 had to check by hand: core mounts several routes at the TIER ROOT (/status, /version), which the loader's collision probe cannot see, so /rust being free is asserted here by a core rather than by a reading. Pinned rather than tracking a branch on purpose: core moves for reasons that have nothing to do with this module, and a bump is then a deliberate commit saying which core the module was last proved against, instead of an unexplained red X on someone else's PR. Bump it, regenerate routes.manifest.json, and commit both together. This module needs MODULE_API 1.10.0 (module.json's coreApi is ^1.10.0), which the Event System cutover put on `main` — so unlike Module-uo, which spent the Event System window pinned to `edge`, this repo starts pinned to `main` and should stay there unless it comes to depend on a contract member that has not shipped yet.",
"$comment": "The core this module is proved against. MODULE_API.md §5.3: the frozen-manifest job clones RunicGateway/website at this exact ref, drops this module in as modules/rust and runs CORE's own routeManifest.js — nothing else can answer whether the URLs the module claims are the URLs it actually serves, because a mount prefix is a string in server/index.js and a documented path is a string in a JSON file, and whether those name the same URL is a fact about a running core. It also answers the blind spot phase 1 had to check by hand: core mounts several routes at the TIER ROOT (/status, /version), which the loader's collision probe cannot see, so /rust being free is asserted here by a core rather than by a reading. Pinned rather than tracking a branch on purpose: core moves for reasons that have nothing to do with this module, and a bump is then a deliberate commit saying which core the module was last proved against, instead of an unexplained red X on someone else's PR. Bump it, regenerate routes.manifest.json, and commit both together. This module needs MODULE_API 1.10.0 (module.json's coreApi is ^1.10.0), which the Event System cutover put on `main` — so unlike Module-uo, which spent the Event System window pinned to `edge`, this repo starts pinned to `main` and should stay there unless it comes to depend on a contract member that has not shipped yet. **2026-09-27, protocol 13 step 2:** this module calls ctx.events.expired (MODULE_API 1.11.0, PLAN_FIXES D183), so coreApi is ^1.11.0. It was pinned to website#209's branch head while that PR was open — a 1.10.0 core refuses to load it — and is back on `main` at the sha #209 merged as.",
"repo": "https://gitea.whitlocktech.com/RunicGateway/website.git",
"ref": "efa9db73304552dd8bb7a84030b258c6320f79f7",
"refName": "main @ MODULE_API 1.10.0, the Asset Bridge cutover 2 of 5 (website#202)"
"ref": "f0e7d2aa2a4dbdd848f92648085181611b7418f0",
"refName": "main @ MODULE_API 1.11.0 (website#209 merged)"
}

View File

@@ -10,6 +10,7 @@
"license": "GPL-3.0-or-later",
"devDependencies": {
"@vitejs/plugin-react": "^4.3.2",
"leaflet": "1.9.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2",
@@ -1448,6 +1449,13 @@
"node": ">=6"
}
},
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"dev": true,
"license": "BSD-2-Clause"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",

View File

@@ -16,6 +16,7 @@
"//dependencies": "Deliberately none that ship. react, react-dom/client, react/jsx-runtime and react-router-dom are aliased to the shims in src/shim/ and arrive at runtime on window.__rg - there is exactly one React in the page and core owns it (MODULE_API.md 3.2, 3.6). They are devDependencies so that Vite and the JSX transform can resolve them during the build, and for no other reason.",
"devDependencies": {
"@vitejs/plugin-react": "^4.3.2",
"leaflet": "1.9.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2",

View File

@@ -82,9 +82,10 @@ export function stringMask(src) {
return inString
}
// Static and dynamic imports that survived into the output. A relative or
// absolute specifier is a chunk that was split, which this build does not do —
// `lib` mode with one entry emits one file — so anything here is a bare name.
// Static and dynamic imports that survived into the output. A relative
// specifier is a chunk that was split — since D120 there is one, Leaflet's,
// which the Map tab imports with `import()` — and is `relativeImports`'s
// concern below; a bare name is this check's.
//
// **This pattern used to require whitespace after `import`, and so could not see
// the one shape the build actually emits.** Minified Rollup output is
@@ -116,6 +117,28 @@ export function bareImports(chunk) {
return [...bare]
}
/**
* Every relative specifier the chunk imports — its split chunks (D120).
*
* Each one is a file the browser will ask for beside `entry.js`, and core
* serves that directory, so it works in development. Whether it SHIPS is
* `release.yml`'s business, which is why the script below also asserts every
* one of them exists in `dist/`, and `test/build.test.js` asserts the release
* copies every `.js` in `dist/` rather than naming `entry.js`. A split chunk the
* release forgot is a Map tab that spins for ever on an operator's site while
* every check here passes.
*/
export function relativeImports(chunk) {
const masked = stringMask(chunk)
const found = new Set()
for (const match of chunk.matchAll(IMPORTS)) {
const keywordAt = match.index + (match[0].startsWith('import') ? 0 : 1)
if (masked[keywordAt]) continue
if (match[1].startsWith('./')) found.add(match[1].slice(2))
}
return [...found]
}
// Fingerprints from the shared libraries' own source. Each is a string those
// packages ship and this module has no other reason to contain.
//
@@ -161,12 +184,30 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
console.error(`No chunk at ${CHUNK} — run \`npm run build\` first.`)
process.exit(1)
}
const problems = problemsWith(fs.readFileSync(CHUNK, 'utf8'))
const dist = path.dirname(CHUNK)
const entry = fs.readFileSync(CHUNK, 'utf8')
const problems = []
// Every chunk, not only the entry: a split chunk that bundled a second React
// would load on the tab that imports it and fail there, and nowhere else.
for (const file of fs.readdirSync(dist).filter((f) => f.endsWith('.js'))) {
for (const p of problemsWith(fs.readFileSync(path.join(dist, file), 'utf8'))) problems.push(`${file}: ${p}`)
}
for (const name of relativeImports(entry)) {
if (!fs.existsSync(path.join(dist, name))) {
problems.push(`entry.js imports ./${name}, which is not in dist/ — the chunk would load and that import would fail`)
}
}
if (problems.length) {
console.error('\nThe built chunk breaks the shared-dependency rule:\n')
for (const p of problems) console.error(` - ${p}\n`)
process.exit(1)
}
const kb = (fs.statSync(CHUNK).size / 1024).toFixed(1)
console.log(`OK — dist/entry.js (${kb} kB) has no bare imports and bundles no shared dependency.`)
const split = relativeImports(entry)
console.log(
`OK — dist/entry.js (${kb} kB) has no bare imports and bundles no shared dependency` +
(split.length ? `; its ${split.length} split chunk(s) (${split.join(', ')}) are present and clean.` : '.'),
)
}

View File

@@ -25,6 +25,74 @@ const { request: req, BASE } = rg.api
// registers under the `/rust` prefix `module.json` declares.
export const servers = {
list: () => req('/public/rust/servers'),
// One server, and the only route under `/servers/:id` that can answer "no such
// server": the four below answer an empty list for an id nobody ever
// configured, because an unknown server genuinely has no events.
get: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}`),
// `kind` is a comma-separated list and `wipe` a wipe id; both are optional and
// both are built here rather than in a page, so the query string this module
// sends exists in one file.
events: (id, { kinds = null, wipe = null, limit = null } = {}) =>
req(`/public/rust/servers/${encodeURIComponent(id)}/events${query({
kind: kinds && kinds.length ? kinds.join(',') : null,
wipe,
limit,
})}`),
leaderboard: (id, { wipe = null, sort = null, limit = null } = {}) =>
req(`/public/rust/servers/${encodeURIComponent(id)}/leaderboard${query({ wipe, sort, limit })}`),
wipes: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}/wipes`),
online: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}/online`),
// Phase 9. The clan list is public (D58): name, colour, score and member count
// name nobody. `board` says whether the list can be trusted right now.
clans: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}/clans`),
// Phase 14. The map's picture address, geometry and which layers this viewer
// gets; then what moves on it, already cut down to this viewer on the server.
map: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}/map`),
mapLive: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}/map/live`),
// RunicNPC (runicnpc stage 4). The profiles a leaderboard can rank by, one
// profile's ranking counted as the profile says (D247, D250), and one
// player's kills by profile, for an opened leaderboard row (D252).
npcProfiles: (id) => req(`/public/rust/servers/${encodeURIComponent(id)}/npc-profiles`),
npcLeaderboard: (id, { profile, wipe = null, limit = null } = {}) =>
req(`/public/rust/servers/${encodeURIComponent(id)}/npc-leaderboard${query({ profile, wipe, limit })}`),
npcKills: (id, steamId, { wipe = null } = {}) =>
req(`/public/rust/servers/${encodeURIComponent(id)}/players/${encodeURIComponent(steamId)}/npc-kills${query({ wipe })}`),
}
// One clan. Its roster comes back only for a viewer inside the operator's roster
// audience (D48) — clan members and staff by default — and `roster.visible`
// says which answer this was, so a page can explain an empty roster rather than
// imply an empty clan.
//
// The id carries colons (`<server>:<clan>:<created>`). They are legal in a path
// segment, and encoded anyway so that a server slug is never read as structure.
export const clans = {
get: (externalId) => req(`/public/rust/clans/${encodeURIComponent(externalId)}`),
}
/**
* A query string from the parameters that have a value, or `''`.
*
* **An absent parameter must be absent, not empty.** `?wipe=` is not the same
* question as no `wipe` at all — the first asks for a wipe whose id is the empty
* string — and a page that sends one because a `<select>` is on "All time" gets
* an empty leaderboard and no error.
*/
function query(params) {
const search = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value !== null && value !== undefined && value !== '') search.set(key, String(value))
}
const string = search.toString()
return string ? `?${string}` : ''
}
// ── player ────────────────────────────────────────────────────────────────
@@ -35,6 +103,32 @@ export const playerServers = {
list: () => req('/player/rust/servers'),
}
// Your own kills of each RunicNPC profile, current wipes, across your linked accounts (D252).
export const playerNpcKills = {
list: () => req('/player/rust/npc-kills'),
}
// R1's identity link, from the signed-in player's side.
//
// **The code is the whole of what goes up.** The site has no idea which server
// minted it — nothing in six characters says — so the server half asks each
// configured server in turn (D24). A page that asked the player to pick would be
// asking them a question the site can answer itself, and a wrong pick would come
// back indistinguishable from a wrong code.
export const playerLinks = {
list: () => req('/player/rust/links'),
confirm: (code) => req('/player/rust/link', { method: 'POST', body: { code } }),
remove: (steamId) =>
req(`/player/rust/links/${encodeURIComponent(steamId)}`, { method: 'DELETE' }),
}
// What the site has given the caller in game (phase 8). Read-only, and beside
// `playerLinks` rather than under it: an entitlement exists whether or not an
// account is linked yet, which is exactly the state worth showing.
export const playerPermissions = {
list: () => req('/player/rust/permissions'),
}
// ── admin ─────────────────────────────────────────────────────────────────
// **`sidecarToken` goes up and never comes back.** The list answers `hasToken`,
// and a save that omits the field leaves the stored credential alone — so an
@@ -48,10 +142,205 @@ export const admin = {
req(`/admin/rust/servers/${encodeURIComponent(id)}`, { method: 'DELETE' }),
testServer: (id) =>
req(`/admin/rust/servers/${encodeURIComponent(id)}/test`, { method: 'POST' }),
// Phase 14: fetch a server's map picture again, or ask a server with no
// picture to draw one — which stalls that game for seconds (D109).
fetchMap: (id) => req(`/admin/rust/servers/${encodeURIComponent(id)}/map/fetch`, { method: 'POST' }),
renderMap: (id) => req(`/admin/rust/servers/${encodeURIComponent(id)}/map/render`, { method: 'POST' }),
// Phase 17: a server's chat titles, what optional mods it has, and the voice.
saveTitles: (id, body) => req(`/admin/rust/servers/${encodeURIComponent(id)}/titles`, { method: 'PUT', body }),
// PLAN_REDESIGNS §5.5 (D175): a category's title for the whole site; '' resets it.
saveTitleCategory: (stat, text) =>
req(`/admin/rust/title-categories/${encodeURIComponent(stat)}`, { method: 'PUT', body: { text } }),
integrations: (id) => req(`/admin/rust/servers/${encodeURIComponent(id)}/integrations`),
voice: () => req('/admin/rust/voice'),
saveVoice: (group) => req('/admin/rust/voice', { method: 'PUT', body: { group } }),
}
// ── admin · permissions (R2) ──────────────────────────────────────────────
//
// The authoring surface. Every call here writes to the SITE, and none of them
// reaches a game server — the mirror's own loop does that on its own cadence.
// `sync` is the exception and says so in its name: it runs the pass now and
// answers with what each server reported, which is the only call on this screen
// that can be slow or fail because a game host is down.
//
// A write is followed by a re-read rather than a local edit of the model: what
// the screen is showing is partly the game's answer, and the honest way to learn
// the new one is to ask.
const P = '/admin/rust/permissions'
const enc = encodeURIComponent
export const adminPermissions = {
overview: () => req(P),
catalogue: () => req(`${P}/catalogue`),
// One server, as PermissionsManager shows one (D162).
server: (serverId) => req(`${P}/servers/${enc(serverId)}`),
players: (serverId, q) => req(`${P}/servers/${enc(serverId)}/players?q=${enc(q || '')}`),
setPolicy: (serverId, policy) => req(`${P}/servers/${enc(serverId)}/policy`, { method: 'PUT', body: { policy } }),
// A subject is `{ steamId }` or `{ userId }`; `everywhere` reaches every server.
grant: (serverId, subject, permissions, everywhere = false) =>
req(`${P}/servers/${enc(serverId)}/grant`, { method: 'POST', body: { ...subject, permissions, everywhere } }),
revoke: (serverId, subject, permissions, everywhere = false) =>
req(`${P}/servers/${enc(serverId)}/revoke`, { method: 'POST', body: { ...subject, permissions, everywhere } }),
removeException: (id) => req(`${P}/exceptions/${enc(id)}`, { method: 'DELETE' }),
// Groups by id (D189). `here` is `{ onlyHere: true, serverId }` to split a
// shared group's copy off first (D190), or null to change it everywhere.
createGroup: (serverId, body) => req(`${P}/servers/${enc(serverId)}/groups`, { method: 'POST', body }),
updateGroup: (id, body, here = null) => req(`${P}/groups/${enc(id)}`, { method: 'PATCH', body: { ...body, ...(here || {}) } }),
deleteGroup: (id) => req(`${P}/groups/${enc(id)}`, { method: 'DELETE' }),
setGroupPermissions: (id, permissions, here = null) =>
req(`${P}/groups/${enc(id)}/permissions`, { method: 'PUT', body: { permissions, ...(here || {}) } }),
setGroupServers: (id, body) => req(`${P}/groups/${enc(id)}/servers`, { method: 'PUT', body }),
splitGroup: (id, serverId) => req(`${P}/groups/${enc(id)}/split`, { method: 'POST', body: { serverId } }),
addMember: (id, subject, here = null) =>
req(`${P}/groups/${enc(id)}/members`, { method: 'POST', body: { ...subject, ...(here || {}) } }),
removeMember: (id, subject, here = null) =>
req(`${P}/groups/${enc(id)}/members/remove`, { method: 'POST', body: { ...subject, ...(here || {}) } }),
clearMembers: (id, here = null) => req(`${P}/groups/${enc(id)}/members/clear`, { method: 'POST', body: { ...(here || {}) } }),
// What waits for a person (D161).
adoptDrift: (id) => req(`${P}/drift/${enc(id)}/adopt`, { method: 'POST' }),
revokeDrift: (id) => req(`${P}/drift/${enc(id)}/revoke`, { method: 'POST' }),
acceptDrift: (id) => req(`${P}/drift/${enc(id)}/accept`, { method: 'POST' }),
restoreDrift: (id) => req(`${P}/drift/${enc(id)}/restore`, { method: 'POST' }),
dismissDrift: (id) => req(`${P}/drift/${enc(id)}/dismiss`, { method: 'POST' }),
sync: (serverId = null) => req(`${P}/sync`, { method: 'POST', body: serverId ? { serverId } : {} }),
}
// ── admin · visibility ────────────────────────────────────────────────────
//
// Who may see who is online. The org lead's rule is that nothing names who is
// online by default; this is where an operator deliberately widens it. A save
// answers the whole new state, so the screen re-renders from the server's word
// rather than from what it sent.
export const adminVisibility = {
read: () => req('/admin/rust/visibility'),
save: (body) => req('/admin/rust/visibility', { method: 'PUT', body }),
}
// ── admin · zone presets (PLAN_REDESIGNS §3.1, D210) ───────────────────────
//
// An admin's named sets of ZoneManager flags and settings. `read` also carries
// what each server's last hello said about ZoneManager and ZoneDomes, so the
// page works while a server is off.
export const adminZones = {
read: () => req('/admin/rust/zones'),
create: (body) => req('/admin/rust/zones/presets', { method: 'POST', body }),
update: (id, body) => req(`/admin/rust/zones/presets/${encodeURIComponent(id)}`, { method: 'PUT', body }),
remove: (id) => req(`/admin/rust/zones/presets/${encodeURIComponent(id)}`, { method: 'DELETE' }),
}
// ── admin · NPCs (runicnpc stage 4) ─────────────────────────────────────────
//
// The site's RunicNPC profiles (per server, shared or fleet), pushed to each
// server; and each server's placements, which live on the server (D222), so
// every placement call is a live round trip that fails while the game is off.
const npcServer = (serverId) => `/admin/rust/npcs/servers/${encodeURIComponent(serverId)}`
export const adminNpcs = {
read: () => req('/admin/rust/npcs'),
setFactions: (factions) => req('/admin/rust/npcs/factions', { method: 'PUT', body: { factions } }),
create: (body) => req('/admin/rust/npcs/profiles', { method: 'POST', body }),
update: (id, body) => req(`/admin/rust/npcs/profiles/${encodeURIComponent(id)}`, { method: 'PUT', body }),
remove: (id) => req(`/admin/rust/npcs/profiles/${encodeURIComponent(id)}`, { method: 'DELETE' }),
restore: (id) => req(`/admin/rust/npcs/profiles/${encodeURIComponent(id)}/restore`, { method: 'POST' }),
push: (serverId) => req(`${npcServer(serverId)}/push`, { method: 'POST' }),
placements: (serverId) => req(`${npcServer(serverId)}/placements`),
place: (serverId, body) => req(`${npcServer(serverId)}/placements`, { method: 'POST', body }),
setPlacement: (serverId, id, body) => req(`${npcServer(serverId)}/placements/${encodeURIComponent(id)}`, { method: 'PUT', body }),
removePlacement: (serverId, id) => req(`${npcServer(serverId)}/placements/${encodeURIComponent(id)}`, { method: 'DELETE' }),
renamePlacement: (serverId, id, to) =>
req(`${npcServer(serverId)}/placements/${encodeURIComponent(id)}/rename`, { method: 'POST', body: { to } }),
respawnPlacement: (serverId, id) => req(`${npcServer(serverId)}/placements/${encodeURIComponent(id)}/respawn`, { method: 'POST' }),
}
// ── admin · mod configuration (R18) ───────────────────────────────────────
//
// Every call here is a LIVE round trip to a game host, which makes this the only
// section of this file where a call can be slow, or fail because a server is
// off. Nothing is cached anywhere between the browser and the host's disk: a
// cached config is an edit an operator made over SSH that this website then
// silently overwrote.
//
// `save` carries a `version` the host issued with the file. Send a stale one and
// the answer is a 409 with the current file attached, rather than an overwrite
// of whatever somebody else changed in the meantime.
export const adminConfig = {
files: (serverId) => req(`/admin/rust/config/${encodeURIComponent(serverId)}/files`),
file: (serverId, path) =>
req(`/admin/rust/config/${encodeURIComponent(serverId)}/file${query({ path })}`),
// Two tiers, one route. `edits` is the generated form — pointers and literals,
// type-preserving — and `text` is the raw document. A number travels as TEXT
// in both: `1.0` parsed into a JavaScript number and sent back as `1` is the
// whole failure this feature was designed around.
save: (serverId, body) =>
req(`/admin/rust/config/${encodeURIComponent(serverId)}/file`, { method: 'POST', body }),
writes: (serverId, limit = null) =>
req(`/admin/rust/config/${encodeURIComponent(serverId)}/writes${query({ limit })}`),
// One write, polled while its reload settles (protocol 13). A save that
// reloads a plugin answers before the reload has finished — behind a cold
// compile that can be many seconds — and this is where the outcome lands.
write: (serverId, id) =>
req(`/admin/rust/config/${encodeURIComponent(serverId)}/writes/${encodeURIComponent(id)}`),
}
// ── the admin.users.detail extension slot ─────────────────────────────────
//
// The client half of R13's first slot. Core hands the component a `userId` and
// NOTHING else — not a client — so an extension builds its own bindings for the
// routes it registered at the other end (§3.5). These two are the only calls in
// this file whose path is core's rather than this module's: the resource is
// core's user, and the module's own segment is the part after it.
export const adminUserLinks = {
list: (userId) => req(`/admin/users/${encodeURIComponent(userId)}/rust/links`),
remove: (userId, steamId) =>
req(`/admin/users/${encodeURIComponent(userId)}/rust/links/${encodeURIComponent(steamId)}`, {
method: 'DELETE',
}),
}
// The same panel's phase 7 half: what this person may do in game. The id in the
// path is the one the slot handed the component, so these send `userId` rather
// than a name — the screen already knows who it is looking at.
export const adminUserPermissions = {
list: (userId) => req(`/admin/users/${encodeURIComponent(userId)}/rust/permissions`),
grant: (userId, body) =>
req(`/admin/users/${encodeURIComponent(userId)}/rust/permissions/grants`, {
method: 'POST',
body,
}),
revoke: (userId, grantId) =>
req(
`/admin/users/${encodeURIComponent(userId)}/rust/permissions/grants/${encodeURIComponent(grantId)}`,
{ method: 'DELETE' },
),
}
// Exported for the rare caller that needs the base itself — an `<img src>`, a
// download link, an EventSource. Reach for `request` first.
export { BASE }
export { BASE, query }
export default { servers, playerServers, admin, BASE }
export default {
servers,
clans,
playerServers,
playerLinks,
playerPermissions,
admin,
adminPermissions,
adminConfig,
adminVisibility,
adminZones,
adminNpcs,
playerNpcKills,
adminUserLinks,
adminUserPermissions,
BASE,
}

View File

@@ -0,0 +1,118 @@
// ── The clans on one server ───────────────────────────────────────────────
//
// Rust's OWN clans (R5), best score first. Public at every setting (D58): a
// clan's name, colour, score and member count name nobody. Who is IN a clan is
// the roster, and that lives on the clan's own page behind the operator's
// roster audience (D48).
//
// **The list is only as good as the board it came from**, and the answer says
// how good that is. Three cases would all look like an empty list if rendered
// bare, and they are three different sentences:
//
// • the bridge cannot read this server's clans at all (an older plugin, or a
// Nexus server whose clans live elsewhere) — "unavailable";
// • the game's clan system is switched off — "this server has no clans";
// • it can, and there are none — "nobody has founded one yet".
//
// And a board at the game's 100-clan ceiling (D55) says there may be more.
import { Link } from 'react-router-dom'
import { ErrorState, Loading, useAsync } from '../core.js'
import Empty from './Empty.jsx'
import { count } from '../lib/format.js'
import api from '../api.js'
export default function Clans({ serverId }) {
const { data, loading, error } = useAsync(() => api.servers.clans(serverId), [serverId])
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
const clans = (data && data.clans) || []
const board = (data && data.board) || {}
if (clans.length === 0) {
if (!board.supported) {
return (
<Empty
title="Clans are unavailable for this server"
message={board.reason ? `${capitalise(board.reason)}.` : 'The bridge has not reported this server’s clans yet.'}
/>
)
}
if (board.enabled === false) {
return <Empty title="This server has no clans" message="Its operator has switched the game’s clan system off." />
}
return <Empty title="No clans yet" message="Nobody on this server has founded a clan." />
}
return (
<>
{board.truncated && (
<p className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem', marginTop: 0 }}>
The game lists at most 100 clans, by score, so there may be more on this server than are shown here.
</p>
)}
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{clans.map((clan, index) => (
<li
key={clan.externalId}
style={{
display: 'flex',
alignItems: 'baseline',
gap: 12,
padding: '10px 0',
borderBottom: '1px solid var(--line-soft, var(--line))',
}}
>
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.78rem', minWidth: 22, textAlign: 'right' }}>
{index + 1}
</span>
<Swatch color={clan.color} />
<Link to={clanPath(clan.externalId)} style={{ fontWeight: 600, flex: 1, minWidth: 0 }}>
{clan.name}
</Link>
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem', whiteSpace: 'nowrap' }}>
{count(clan.memberCount)} {clan.memberCount === 1 ? 'member' : 'members'}
</span>
<span className="sans" style={{ fontSize: '0.8rem', whiteSpace: 'nowrap', minWidth: 70, textAlign: 'right' }}>
{count(clan.score)} pts
</span>
</li>
))}
</ul>
</>
)
}
/** Where a clan's page is: the same template the Team provider hands core. */
export function clanPath(externalId) {
return `/rust/clans/${encodeURIComponent(externalId)}`
}
/**
* A clan's colour, as a small square. The server has already checked it is a
* `#rrggbb` — it ends up in a style — and a clan with no colour gets an outline
* rather than a guess.
*/
export function Swatch({ color, size = 12 }) {
return (
<span
aria-hidden="true"
style={{
display: 'inline-block',
flex: 'none',
width: size,
height: size,
borderRadius: 3,
background: color || 'transparent',
border: color ? 'none' : '1px solid var(--line)',
alignSelf: 'center',
}}
/>
)
}
function capitalise(text) {
return text ? text.charAt(0).toUpperCase() + text.slice(1) : text
}

View File

@@ -0,0 +1,26 @@
// ── An empty state with a heading and a sentence ──────────────────────────
//
// Core's `EmptyState` renders its CHILDREN and nothing else. This module passed
// it `title` and `message` from phase 4 onwards — the shape the Integration Kit's
// template teaches — and React drops an unknown prop without a word, so every
// empty panel in the module rendered as a blank box: "Nobody is on", "No scores
// yet", "No servers yet", all of them. Found by the presence fix's browser walk,
// when the "12 players online" it depended on came out as nothing.
//
// Fixed here rather than in core: core's component is shared by every module,
// and a module-side wrapper changes nothing anybody else renders. The client
// suite (`test/uiKitProps.test.js`) refuses a titled EmptyState so the mistake
// cannot come back.
import { EmptyState } from '../core.js'
export default function Empty({ title, message }) {
return (
<EmptyState>
{title && (
<strong style={{ display: 'block', color: 'var(--head)', marginBottom: message ? 6 : 0 }}>{title}</strong>
)}
{message && <span>{message}</span>}
</EmptyState>
)
}

View File

@@ -0,0 +1,157 @@
// ── The feed: what happened on one server ─────────────────────────────────
//
// Rows come from `/public/rust/servers/:id/events`, which serves a default-deny
// ALLOWLIST (`server/catalogue.js`). Everything carrying an IP address, a
// player's report about another player, or the grid square somebody's base is in
// is stored and never answered here — so this component cannot leak one by
// forgetting to filter, which is the point of the boundary living on the server.
//
// It polls (org lead, phase 4): every twenty seconds while the tab is visible,
// paused when it is not. `usePolled` keeps the rows on screen across a refresh —
// see the comment at the top of that file for why core's `useAsync` cannot do
// this job.
import { ErrorState, Loading } from '../core.js'
import Empty from './Empty.jsx'
import { describe, FILTERS, kindsFor } from '../lib/feed.js'
import { ago, clock } from '../lib/format.js'
import usePolled from '../hooks/usePolled.js'
import api from '../api.js'
import { hiddenMessage } from './Online.jsx'
const TONE = {
kill: 'var(--accent-bright)',
death: 'var(--muted)',
join: 'var(--mode-live, #5fb98a)',
leave: 'var(--dim)',
chat: 'var(--text)',
server: 'var(--mode-maint, #e6c26a)',
other: 'var(--muted)',
}
export default function Feed({ serverId, wipeId, filter, onFilter }) {
const kinds = kindsFor(filter)
const { data, error, loading, at } = usePolled(
() => api.servers.events(serverId, { kinds, wipe: wipeId, limit: 100 }),
// The key is the QUESTION. Changing server, wipe or filter blanks the rows,
// because what is on screen is an answer to a different one; a poll tick
// does not, because it is the same question asked again.
{ key: `${serverId}|${wipeId || ''}|${filter}`, intervalMs: 20_000 },
)
const events = data ? data.events : []
return (
<div>
<div
className="sans"
style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center', marginBottom: 16 }}
>
<label style={{ color: 'var(--dim)', fontSize: '0.78rem' }}>
Showing{' '}
<select
value={filter}
onChange={(e) => onFilter(e.target.value)}
style={selectStyle}
>
{FILTERS.map((f) => (
<option key={f.id} value={f.id}>{f.label}</option>
))}
</select>
</label>
{/* What a refresh is FOR: saying when the page last managed one. Without
it a feed that stopped updating looks exactly like a quiet server. */}
{at && (
<span style={{ color: 'var(--dim)', fontSize: '0.74rem' }}>updated {ago(at)}</span>
)}
{error && (
<span style={{ color: 'var(--mode-maint, #e6c26a)', fontSize: '0.74rem' }}>
the last refresh failed — showing what we had
</span>
)}
</div>
{loading && <Loading />}
{/* An error with nothing to fall back on is the only case that takes over
the panel. A failed REFRESH keeps the rows and says so in the line
above, because a site whose premise is "it renders while the game is
off" must not blank itself the first time a request does. */}
{error && !data && <ErrorState error={error} />}
{/* Below the operator's presence audience the server withholds every item
that names a player who was on — the killfeed, chat, joins — and keeps
only the server's own story. Said once, above the rows, so a thin feed
reads as withheld rather than as a quiet server. */}
{data && data.presenceHidden && (
<p className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem', marginTop: 0 }}>
Joins, deaths and chat are not shown. {hiddenMessage(data.presenceAudience, 'what players did')}
</p>
)}
{data && events.length === 0 && (
<Empty
title="Nothing here yet"
message={
data.presenceHidden
? 'Nothing this server has reported about itself matches.'
: 'Nothing this server has reported matches. A server that has just been added has no history until it says something.'
}
/>
)}
{events.length > 0 && (
<ol style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{events.map((event) => {
const line = describe(event)
return (
<li
key={event.id}
style={{
display: 'flex',
gap: 12,
alignItems: 'baseline',
padding: '7px 0',
borderBottom: '1px solid var(--line-soft, var(--line))',
}}
>
<time
className="sans"
dateTime={new Date(event.t).toISOString()}
title={new Date(event.t).toLocaleString()}
style={{ flex: 'none', color: 'var(--dim)', fontSize: '0.74rem', minWidth: '5.6rem' }}
>
{clock(event.t)}
</time>
<span style={{ color: TONE[line.tone] || 'var(--muted)', fontSize: '0.92rem' }}>
{line.actor && <strong style={{ color: 'var(--ink)' }}>{line.actor}</strong>}
{line.actor && (line.join || ' ')}
{line.verb}
{line.subject && ' '}
{line.subject && <strong style={{ color: 'var(--ink)' }}>{line.subject}</strong>}
{line.detail && (
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.76rem' }}>
{' · '}
{line.detail}
</span>
)}
</span>
</li>
)
})}
</ol>
)}
</div>
)
}
const selectStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input, 6px)',
padding: '3px 8px',
fontSize: '0.78rem',
}

View File

@@ -0,0 +1,73 @@
// ── This module's fill for core's `site.footer.status` slot ───────────────
//
// R13, and the contract is MODULE_API.md §3.7. Core owns the position in the
// footer's info row and the separator around it, and passes `linkStyle` so the
// row stays visually one row. **The label, the destination, the data and whether
// anything renders at all are this component's** — that is the whole division,
// and it is why the slot is named for a place rather than for a meaning.
//
// ── The live count, and what it costs ─────────────────────────────────────
//
// The org lead chose a live count ("3 servers · 42 online") over a static link,
// so this fetches. Be clear-eyed about where it fetches from: core renders
// `SiteFooter` inside `PublicLayout`, and every public page renders
// `PublicLayout` ITSELF (§3.3) — so this component mounts once per public page
// view, not once per session. Every public page on the site therefore carries one
// `/public/rust/servers` request, including pages that have nothing to do with
// Rust.
//
// Two things keep that honest rather than merely cheap:
//
// • **It renders NOTHING until it has an answer, and nothing again if the
// request fails.** An unfilled slot renders nothing and core's `wrap` takes
// the separator with it, so a failed fetch degrades to exactly the footer an
// instance with no module installed has. A spinner in a footer would be worse
// than silence on every page of the site.
// • **It never polls.** One request per page view is a cost; a timer in the
// footer of every page would be a different kind of thing entirely.
//
// If that per-page request ever shows up in an operator's logs as a problem, the
// fix is a short-lived module-scope cache here — the decision to keep the number
// live stays intact, and nothing else on the site has to change.
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import api from '../api.js'
export default function FooterStatus({ linkStyle }) {
const [summary, setSummary] = useState(null)
useEffect(() => {
let live = true
api.servers
.list()
.then(({ servers }) => {
if (!live) return
// `online` already accounts for staleness — the model refuses to let a
// row that has not been written in five minutes claim a server is up —
// so this is a sum, not a judgement.
setSummary({
servers: servers.length,
players: servers.reduce((total, server) => total + (server.online ? server.players : 0), 0),
})
})
// Silence, deliberately. This is the footer of every page on the site; a
// module that cannot reach its own API has nothing to say there.
.catch(() => {})
return () => {
live = false
}
}, [])
if (!summary || summary.servers === 0) return null
return (
<Link to="/rust" style={linkStyle}>
{summary.servers === 1 ? '1 server' : `${summary.servers} servers`}
{' · '}
{summary.players === 1 ? '1 online' : `${summary.players} online`}
</Link>
)
}

View File

@@ -0,0 +1,269 @@
// ── The leaderboard ───────────────────────────────────────────────────────
//
// Per wipe when a wipe is selected, all-time when it is not (R12). The two are
// the same rows summed differently rather than two sets of counters, so they can
// never disagree — which is worth knowing here because it means "All time" is
// not a slower or less accurate answer, it is the same table without a WHERE.
//
// It does NOT poll. A leaderboard moves on the scale of a session; a table that
// re-sorted itself under the reader's cursor every twenty seconds would be worse
// than one that is four minutes old, and the page has a `Refresh` on the tab
// strip for anybody who disagrees.
//
// RunicNPC (runicnpc stage 4). Where the server has NPC profiles, "Rank by"
// offers each one's kills, counted as the profile says (D247, D250), and opening
// a player's row shows their kills of each profile for the wipe shown (D252).
import { useState } from 'react'
import { ErrorState, Loading, useAsync } from '../core.js'
import Empty from './Empty.jsx'
import { ago, contrastInk, count, duration, shortId } from '../lib/format.js'
import api from '../api.js'
// `sort` is the API's own vocabulary (`kills`, `deaths`, `npcKills`, `playtime`),
// and the column it maps to is this file's. Keeping them in one list is what
// stops a header that sorts by something other than what it says.
const COLUMNS = [
{ key: 'kills', label: 'Kills', sort: 'kills', value: (r) => count(r.kills) },
{ key: 'deaths', label: 'Deaths', sort: 'deaths', value: (r) => count(r.deaths) },
{ key: 'npcKills', label: 'NPC kills', sort: 'npcKills', value: (r) => count(r.npcKills) },
{ key: 'structures', label: 'Structures', sort: null, value: (r) => count(r.structures) },
{ key: 'playtimeSec', label: 'Played', sort: 'playtime', value: (r) => duration(r.playtimeSec) },
]
export default function Leaderboard({ serverId, wipeId, sort, onSort }) {
const { data: npc } = useAsync(() => api.servers.npcProfiles(serverId).catch(() => ({ profiles: [] })), [serverId])
const [profileId, setProfileId] = useState('')
const profiles = (npc && npc.profiles) || []
const picked = profiles.find((p) => String(p.id) === String(profileId))
const picker = profiles.length > 0 && (
<label className="sans" style={{ display: 'flex', gap: 8, alignItems: 'baseline', fontSize: '0.82rem', marginBottom: 10 }}>
<span style={{ color: 'var(--dim)' }}>Rank by</span>
<select
value={profileId}
onChange={(e) => setProfileId(e.target.value)}
style={{ background: 'transparent', color: 'var(--ink)', border: '1px solid var(--line)', borderRadius: 6, padding: '4px 6px', font: 'inherit' }}
>
<option value="">Overall</option>
{profiles.map((p) => <option key={p.id} value={p.id}>{p.label} kills</option>)}
</select>
{picked && <span style={{ color: 'var(--dim)' }}>{SCOPE_NOTE[picked.killsScope] || ''}</span>}
</label>
)
if (picked) {
return (
<div>
{picker}
<ProfileBoard serverId={serverId} wipeId={wipeId} profile={picked} />
</div>
)
}
return (
<div>
{picker}
<Overall serverId={serverId} wipeId={wipeId} sort={sort} onSort={onSort} />
</div>
)
}
/** How a profile's kills are counted, in the reader's words (D247). */
const SCOPE_NOTE = {
server: 'Counted on this server.',
name: 'Counted on every server with this NPC.',
profile: 'Counted wherever this NPC is placed.',
}
function Overall({ serverId, wipeId, sort, onSort }) {
const [open, setOpen] = useState(null)
const { data, loading, error } = useAsync(
() => api.servers.leaderboard(serverId, { wipe: wipeId, sort, limit: 50 }),
[serverId, wipeId, sort],
)
const rows = data ? data.leaderboard : []
// Present on every row or on none — the server decides per request.
const showLastSeen = rows.some((row) => 'lastSeen' in row)
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
if (rows.length === 0) {
return (
<Empty
title="No scores yet"
message={
wipeId
? 'Nobody has done anything countable on this wipe yet.'
: 'This server has not reported anything countable yet.'
}
/>
)
}
return (
<div style={{ overflowX: 'auto' }}>
<table className="sans" style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.86rem' }}>
<thead>
<tr style={{ textAlign: 'left', color: 'var(--dim)', fontSize: '0.72rem', letterSpacing: '0.08em' }}>
<th style={{ ...cell, textTransform: 'uppercase' }}>Player</th>
{COLUMNS.map((column) => (
<th key={column.key} style={{ ...cell, textAlign: 'right', textTransform: 'uppercase' }}>
{column.sort ? (
<button
type="button"
onClick={() => onSort(column.sort)}
aria-label={`Sort by ${column.label}`}
style={{
cursor: 'pointer',
background: 'none',
border: 'none',
padding: 0,
font: 'inherit',
letterSpacing: 'inherit',
textTransform: 'inherit',
color: column.sort === sort ? 'var(--accent-bright)' : 'var(--dim)',
}}
>
{column.label}
</button>
) : (
column.label
)}
</th>
))}
{/* The server withholds `lastSeen` below the operator's presence
audience — a gather tally refreshes it every minute somebody plays,
so it would name who is online. The column goes with it rather
than rendering a row of dashes that look like "never". */}
{showLastSeen && (
<th style={{ ...cell, textAlign: 'right', textTransform: 'uppercase' }}>Last seen</th>
)}
</tr>
</thead>
<tbody>
{rows.map((row, index) => [
<tr
key={row.steamId}
onClick={() => setOpen(open === row.steamId ? null : row.steamId)}
title="Open for this player’s kills of each NPC"
style={{ borderTop: '1px solid var(--line-soft, var(--line))', cursor: 'pointer' }}
>
<td style={cell}>
<span style={{ color: 'var(--dim)', marginRight: 8 }}>{open === row.steamId ? '▾' : '▸'} {index + 1}</span>
{/* A player this module has never seen NAMED is shown by the tail
of their id rather than as a blank: the row is real, and a
nameless one reads as a rendering fault. */}
<strong style={{ color: 'var(--ink)' }}>{row.name || shortId(row.steamId)}</strong>
{/* The chat titles this player holds now (phase 17, D137) — the
same ones the game shows, ranked on the current wipe whichever
wipe this table is showing. Absent on an older module. */}
{(row.titles || []).map((title, i) => (
<span
key={`${title.text}-${i}`}
className="sans"
style={{
marginLeft: 6,
padding: '1px 6px',
borderRadius: 999,
fontSize: '0.7rem',
fontWeight: 600,
background: title.color,
color: contrastInk(title.color),
}}
>
{title.text}
</span>
))}
</td>
{COLUMNS.map((column) => (
<td key={column.key} style={{ ...cell, textAlign: 'right' }}>
{column.value(row)}
</td>
))}
{showLastSeen && (
<td style={{ ...cell, textAlign: 'right', color: 'var(--dim)' }}>{ago(row.lastSeen)}</td>
)}
</tr>,
open === row.steamId && (
<tr key={`${row.steamId}-npcs`}>
<td colSpan={COLUMNS.length + 1 + (showLastSeen ? 1 : 0)} style={{ ...cell, whiteSpace: 'normal', paddingLeft: 34 }}>
<PlayerNpcKills serverId={serverId} steamId={row.steamId} wipeId={wipeId} />
</td>
</tr>
),
])}
</tbody>
</table>
</div>
)
}
/** An opened row (D252): the player's kills of each RunicNPC profile, for the wipe shown. */
function PlayerNpcKills({ serverId, steamId, wipeId }) {
const { data, loading, error } = useAsync(() => api.servers.npcKills(serverId, steamId, { wipe: wipeId }), [serverId, steamId, wipeId])
if (loading) return <span className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem' }}>Loading…</span>
if (error) return <span className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem' }}>Their NPC kills could not be loaded.</span>
const kills = (data && data.kills) || []
if (kills.length === 0) return <span className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem' }}>No kills of this server’s NPC profiles{wipeId ? ' this wipe' : ''}.</span>
return (
<span className="sans" style={{ fontSize: '0.82rem' }}>
{kills.map((k, i) => (
<span key={k.profile}>
{i > 0 && <span style={{ color: 'var(--dim)' }}> · </span>}
{k.label} <strong style={{ color: 'var(--ink)' }}>{count(k.kills)}</strong>
</span>
))}
</span>
)
}
/** One profile's ranking (D250): who has killed the most of it. */
function ProfileBoard({ serverId, wipeId, profile }) {
const { data, loading, error } = useAsync(
() => api.servers.npcLeaderboard(serverId, { profile: profile.id, wipe: wipeId, limit: 50 }),
[serverId, wipeId, profile.id],
)
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
const rows = (data && data.leaderboard) || []
if (rows.length === 0) {
return <Empty title="No kills yet" message={`Nobody has killed a ${profile.label}${wipeId ? ' this wipe' : ''} yet.`} />
}
return (
<div style={{ overflowX: 'auto' }}>
<table className="sans" style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.86rem' }}>
<thead>
<tr style={{ textAlign: 'left', color: 'var(--dim)', fontSize: '0.72rem', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
<th style={cell}>Player</th>
<th style={{ ...cell, textAlign: 'right' }}>{profile.label} kills</th>
</tr>
</thead>
<tbody>
{rows.map((row, index) => (
<tr key={row.steamId} style={{ borderTop: '1px solid var(--line-soft, var(--line))' }}>
<td style={cell}>
<span style={{ color: 'var(--dim)', marginRight: 8 }}>{index + 1}</span>
<strong style={{ color: 'var(--ink)' }}>{row.name || shortId(row.steamId)}</strong>
{(row.titles || []).map((title, i) => (
<span
key={`${title.text}-${i}`}
style={{ marginLeft: 6, padding: '1px 6px', borderRadius: 999, fontSize: '0.7rem', fontWeight: 600, background: title.color, color: contrastInk(title.color) }}
>
{title.text}
</span>
))}
</td>
<td style={{ ...cell, textAlign: 'right' }}>{count(row.kills)}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
const cell = { padding: '8px 10px', whiteSpace: 'nowrap' }

View File

@@ -0,0 +1,390 @@
// ── The live map ──────────────────────────────────────────────────────────
//
// R9's page, as PLAN.md §30.2 drew it: the picture of the current map under
// four layers, each with its own switch, polled every ten seconds while the tab
// is visible (D14) and not at all while it is hidden.
//
// **Nothing here decides who may see what.** The server sends only the layers
// this viewer may see — a hidden one is absent from the answer, not present and
// hidden — so the checkboxes below are a reader's convenience and never a
// boundary. A layer the viewer cannot see is still LISTED, disabled, with who
// can: "staff only" explains an empty map where silence would imply an empty
// server (§23.3's shape).
//
// Leaflet arrives in a chunk of its own when this tab first mounts (D120, see
// `lib/leaflet.js`). The page draws with circle and div markers only, so
// Leaflet's image assets are never needed.
import { useEffect, useMemo, useRef, useState } from 'react'
import { ErrorState, Loading, useAsync } from '../core.js'
import Empty from './Empty.jsx'
import usePolled from '../hooks/usePolled.js'
import { ago } from '../lib/format.js'
import { boundsOf, countdown, fromLatLng, grid, gridLabel, toLatLng } from '../lib/mapGeometry.js'
import api, { BASE } from '../api.js'
const STYLE_ID = 'rust-leaflet-css'
/** The narrowest a grid cell may be on screen, in pixels, and still carry its label. */
const LABEL_MIN_CELL_PX = 30
/** The layers, in the order the legend lists them, with their marker colours. */
const LAYERS = [
{ id: 'world', label: 'Monuments & world events' },
{ id: 'events', label: 'Site events' },
{ id: 'players', label: 'Players' },
{ id: 'bases', label: 'Bases' },
]
const COLOURS = {
monument: '#e8d9a8',
cargo: '#4fc3f7',
heli: '#ef5350',
chinook: '#ffa726',
bradley: '#a1887f',
supply: '#66bb6a',
crate: '#ffee58',
event: '#ce93d8',
online: '#ffffff',
sleeping: '#9e9e9e',
tc: '#ff7043',
vending: '#26a69a',
self: '#00e5ff',
mate: '#7cffb2',
}
const WORLD_NAMES = {
cargo: 'Cargo ship',
heli: 'Patrol helicopter',
chinook: 'Chinook',
bradley: 'Bradley APC',
supply: 'Supply drop',
crate: 'Locked crate',
}
const AUDIENCE_WORDS = { public: 'everyone', signed_in: 'signed-in players', staff: 'staff only' }
/**
* `onPick` and `pins` are for an admin page that places things on the map (the NPC
* placements page, runicnpc stage 4, D245): a click answers the world point under
* it, and `pins` (`{ x, z, label, colour, ring }`) are drawn above every layer. The
* public page passes neither.
*/
export default function MapView({ serverId, online, onPick = null, pins = null }) {
const { data: meta, loading, error } = useAsync(() => api.servers.map(serverId), [serverId])
const geometry = meta ? meta.geometry : null
const [leaflet, setLeaflet] = useState(null)
const [leafletError, setLeafletError] = useState(null)
const [shown, setShown] = useState({ grid: true, world: true, events: true, players: true, bases: true, mates: true })
useEffect(() => {
let alive = true
import('../lib/leaflet.js')
.then((mod) => {
if (!alive) return
if (typeof document !== 'undefined' && !document.getElementById(STYLE_ID)) {
const style = document.createElement('style')
style.id = STYLE_ID
style.textContent = mod.css
document.head.appendChild(style)
}
setLeaflet(mod)
})
.catch((err) => alive && setLeafletError(err))
return () => {
alive = false
}
}, [])
const anyLive = Boolean(meta && (LAYERS.some((l) => meta.layers[l.id].visible) || meta.mates.visible))
const live = usePolled(() => api.servers.mapLive(serverId), {
key: serverId,
intervalMs: (meta && meta.pollMs) || 10_000,
enabled: Boolean(geometry) && anyLive,
})
const container = useRef(null)
const mapRef = useRef(null)
const groups = useRef(null)
const pickRef = useRef(onPick)
pickRef.current = onPick
// The map itself: made once per server and geometry, torn down with them.
useEffect(() => {
if (!leaflet || !geometry || !container.current) return undefined
const { L } = leaflet
const bounds = boundsOf(geometry)
const map = L.map(container.current, {
crs: L.CRS.Simple,
minZoom: -4,
maxZoom: 2,
zoomSnap: 0.25,
attributionControl: false,
// Some things sail off the edge: the rig's cargo ship spent the probe
// outside the picture entirely. The view may follow them a little way.
maxBounds: L.latLngBounds(bounds).pad(0.5),
})
if (meta.picture) L.imageOverlay(`${BASE}${meta.picture.path}`, bounds).addTo(map)
map.fitBounds(bounds)
const made = {}
for (const id of ['grid', 'monuments', 'world', 'events', 'players', 'bases', 'mates', 'pins']) made[id] = L.layerGroup().addTo(map)
// The labels are a layer of their own inside the grid's, shown only when a cell
// is wide enough on screen to hold one: at the fitted zoom a 20-cell map's
// labels overlap into a wall of text (found on the phase 14 walk).
const labels = L.layerGroup()
const cellPx = () => geometry.gridCellSize * ((geometry.width - 2 * geometry.oceanMargin) / geometry.worldSize) * 2 ** map.getZoom()
const fitLabels = () => {
const want = cellPx() >= LABEL_MIN_CELL_PX
if (want && !made.grid.hasLayer(labels)) made.grid.addLayer(labels)
if (!want && made.grid.hasLayer(labels)) made.grid.removeLayer(labels)
}
map.on('zoomend', fitLabels)
const g = grid(geometry)
for (const [[x1, z1], [x2, z2]] of g.lines) {
L.polyline([toLatLng(geometry, x1, z1), toLatLng(geometry, x2, z2)], {
color: '#ffffff',
weight: 1,
opacity: 0.18,
interactive: false,
}).addTo(made.grid)
}
for (const label of g.labels) {
L.marker(toLatLng(geometry, label.x, label.z), {
interactive: false,
keyboard: false,
icon: L.divIcon({
className: '',
html: `<span style="font:600 10px/1 system-ui,sans-serif;color:rgba(255,255,255,.55);padding:2px 3px;display:block;white-space:nowrap">${label.text}</span>`,
iconSize: null,
iconAnchor: [0, 0],
}),
}).addTo(labels)
}
fitLabels()
for (const m of meta.monuments || []) {
L.circleMarker(toLatLng(geometry, m.x, m.z), {
radius: 4,
color: '#000',
weight: 1,
fillColor: COLOURS.monument,
fillOpacity: 0.9,
})
.bindTooltip(`${escape(m.label)} · ${escape(m.grid || gridLabel(geometry, m.x, m.z) || '')}`)
.addTo(made.monuments)
}
mapRef.current = map
groups.current = made
pickRef.current = onPick
if (onPick) {
container.current.style.cursor = 'crosshair'
map.on('click', (e) => {
const at = fromLatLng(geometry, e.latlng.lat, e.latlng.lng)
const half = geometry.worldSize / 2
if (at && pickRef.current && Math.abs(at.x) <= half && Math.abs(at.z) <= half) {
pickRef.current({ x: Math.round(at.x * 10) / 10, z: Math.round(at.z * 10) / 10, grid: gridLabel(geometry, at.x, at.z) })
}
})
}
return () => {
map.remove()
mapRef.current = null
groups.current = null
}
// `meta` is replaced only when the server changes, with the geometry.
}, [leaflet, geometry]) // eslint-disable-line react-hooks/exhaustive-deps
// What moves: every group cleared and redrawn from the latest answer. The
// counts are small — a busy server is a few hundred markers — and a redraw is
// simpler to get right than a diff.
useEffect(() => {
const made = groups.current
if (!leaflet || !made || !geometry) return
const { L } = leaflet
const answer = live.data || {}
const at = (p) => toLatLng(geometry, p.x, p.z)
for (const id of ['world', 'events', 'players', 'bases', 'mates']) made[id].clearLayers()
for (const w of answer.world || []) {
let tip = WORLD_NAMES[w.kind] || w.kind
if (w.kind === 'crate' && w.hackLeftSec != null) tip += ` — ${countdown(w.hackLeftSec)} left on the hack`
if (w.kind === 'crate' && w.hacked) tip += ' — hacked'
dot(L, at(w), COLOURS[w.kind] || COLOURS.crate, w.kind === 'cargo' ? 7 : 5).bindTooltip(escape(tip)).addTo(made.world)
}
const px = (metres) => metres * ((geometry.width - 2 * geometry.oceanMargin) / geometry.worldSize)
for (const e of answer.events || []) {
if (e.kind === 'zone') {
L.circle(at(e), { radius: px(Number(e.radius) || 0), color: COLOURS.event, weight: 2, fillOpacity: 0.12 })
.bindTooltip(escape(e.name ? `Event zone · ${e.name}` : 'Event zone'))
.addTo(made.events)
} else {
dot(L, at(e), COLOURS.event, 5).bindTooltip(e.kind === 'npc' ? 'Event NPC' : 'Event crate').addTo(made.events)
}
}
for (const p of answer.players || []) {
dot(L, at(p), p.online ? COLOURS.online : COLOURS.sleeping, p.online ? 5 : 4)
.bindTooltip(escape(`${p.name || p.steamId}${p.online ? (p.sleeping ? ' · sleeping' : '') : ' · asleep, offline'}`))
.addTo(made.players)
}
for (const b of answer.bases || []) {
dot(L, at(b), COLOURS[b.kind] || COLOURS.tc, 4).bindTooltip(b.kind === 'tc' ? 'Tool cupboard' : 'Vending machine').addTo(made.bases)
}
for (const m of answer.mates || []) {
dot(L, at(m), m.self ? COLOURS.self : COLOURS.mate, m.self ? 8 : 6, 2)
.bindTooltip(escape(m.self ? `You${m.online ? '' : ' (asleep, offline)'}` : m.name || 'Clan mate'))
.addTo(made.mates)
}
}, [leaflet, geometry, live.data])
// An admin page's own pins, above everything else.
useEffect(() => {
const made = groups.current
if (!leaflet || !made || !geometry) return
const { L } = leaflet
made.pins.clearLayers()
for (const p of pins || []) {
const marker = dot(L, toLatLng(geometry, p.x, p.z), p.colour || '#ffd54f', p.ring ? 9 : 6, p.ring ? 3 : 1)
if (p.label) marker.bindTooltip(escape(p.label))
marker.addTo(made.pins)
}
}, [leaflet, geometry, pins])
// The legend's checkboxes: a group is on the map or off it.
useEffect(() => {
const map = mapRef.current
const made = groups.current
if (!map || !made) return
const want = { grid: shown.grid, monuments: shown.world, world: shown.world, events: shown.events, players: shown.players, bases: shown.bases, mates: shown.mates }
for (const [id, on] of Object.entries(want)) {
if (on && !map.hasLayer(made[id])) made[id].addTo(map)
if (!on && map.hasLayer(made[id])) map.removeLayer(made[id])
}
}, [shown, leaflet, geometry])
const status = useMemo(() => liveStatus(live, anyLive, online), [live, anyLive, online])
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
if (!geometry) {
return (
<Empty
title="No map yet"
message="This server has not described its map to the site yet. It will appear once the server is up and has said which map it is on."
/>
)
}
if (leafletError) return <ErrorState error={leafletError} />
return (
<div className="sans">
{!meta.picture && (
<p style={{ color: 'var(--dim)', fontSize: '0.8rem', marginTop: 0 }}>
This server has no picture of its map, so the layers are drawn on a plain background.
</p>
)}
<div style={{ position: 'relative', zIndex: 0 }}>
<div
ref={container}
role="application"
aria-label="Map of the server"
style={{
height: 'min(70vh, 760px)',
minHeight: 320,
borderRadius: 8,
border: '1px solid var(--line)',
background: geometry.background || '#0b3b4a',
}}
/>
{!leaflet && (
<div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
<Loading />
</div>
)}
</div>
<p style={{ color: 'var(--dim)', fontSize: '0.78rem', margin: '8px 0 16px' }}>{status}</p>
<Legend meta={meta} live={live.data} shown={shown} onToggle={(id) => setShown((s) => ({ ...s, [id]: !s[id] }))} />
</div>
)
}
function Legend({ meta, live, shown, onToggle }) {
const row = (id, label, swatches, visible, note) => (
<li key={id} style={{ display: 'flex', alignItems: 'baseline', gap: 10, padding: '6px 0', borderBottom: '1px solid var(--line-soft, var(--line))' }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: visible ? 'pointer' : 'default', color: visible ? 'var(--ink)' : 'var(--dim)' }}>
<input type="checkbox" checked={visible && shown[id]} disabled={!visible} onChange={() => onToggle(id)} />
{label}
</label>
<span style={{ display: 'inline-flex', gap: 4 }}>
{swatches.map((c) => (
<span key={c} aria-hidden="true" style={{ width: 10, height: 10, borderRadius: '50%', background: c, display: 'inline-block', border: '1px solid rgba(0,0,0,.4)' }} />
))}
</span>
{note && <span style={{ color: 'var(--dim)', fontSize: '0.76rem', marginLeft: 'auto', textAlign: 'right' }}>{note}</span>}
</li>
)
const hiddenNote = (layer) => {
const words = AUDIENCE_WORDS[layer.audience] || AUDIENCE_WORDS.staff
if (layer.audience === 'signed_in') return 'Sign in to see this layer.'
return `Shown to ${words}.`
}
const swatches = {
world: [COLOURS.monument, COLOURS.cargo, COLOURS.heli, COLOURS.crate],
events: [COLOURS.event],
players: [COLOURS.online, COLOURS.sleeping],
bases: [COLOURS.tc, COLOURS.vending],
}
return (
<ul style={{ listStyle: 'none', margin: 0, padding: 0, fontSize: '0.86rem' }}>
{row('grid', 'Grid', [], true, null)}
{LAYERS.map((l) => {
const layer = meta.layers[l.id]
let note = layer.visible ? null : hiddenNote(layer)
if (l.id === 'players' && layer.cappedByPresence && !layer.visible) {
note = `${note} Limited by who may see who is online.`
}
if (layer.visible && l.id === 'players' && live && live.playersTruncated) note = 'Not every sleeper is shown.'
if (layer.visible && l.id === 'bases' && live && live.basesTruncated) note = 'Not every base is shown.'
return row(l.id, l.label, swatches[l.id], layer.visible, note)
})}
{meta.mates.visible &&
row('mates', 'You and your clan', [COLOURS.self, COLOURS.mate], true, 'Your own position, and clan mates who are online.')}
{!meta.mates.visible && meta.mates.on && meta.mates.signedIn && !meta.mates.linked &&
row('mates', 'You and your clan', [COLOURS.self, COLOURS.mate], false, 'Link your Steam account to see yourself and your clan here.')}
</ul>
)
}
function dot(L, latlng, colour, radius, weight = 1) {
return L.circleMarker(latlng, { radius, color: '#000', weight, fillColor: colour, fillOpacity: 0.95 })
}
/** Tooltips are HTML in Leaflet, and a player's name is text they typed. */
function escape(text) {
return String(text).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
}
function liveStatus(live, anyLive, online) {
if (!anyLive) return 'No moving layers are shown to you on this server.'
if (live.loading) return 'Asking the server where things are…'
const data = live.data
if (data && data.live === false) {
return online
? 'The server did not say where things are just now; it is asked again every ten seconds.'
: 'The server is offline, so nothing is moving on its map.'
}
if (live.error && !data) return 'Positions could not be loaded.'
return live.at ? `Positions as of ${ago(new Date(live.at).toISOString())}, refreshed every ten seconds while this tab is open.` : ''
}

View File

@@ -0,0 +1,122 @@
// ── Who is on the server right now ────────────────────────────────────────
//
// Read from the presence BOARD, not counted from connect and disconnect events:
// the bridge re-sends the whole board on every connect and every sixty seconds,
// so this is right even after the website has missed something (PROTOCOL.md
// §8.3). Counting transitions instead would drift, and drift in the direction
// people notice — players who never left.
//
// It polls with the feed, because "who is on" is the one thing on this page that
// is a live question.
import { ErrorState, Loading } from '../core.js'
import Empty from './Empty.jsx'
import { duration, shortId } from '../lib/format.js'
import usePolled from '../hooks/usePolled.js'
import api from '../api.js'
export default function Online({ serverId, online }) {
const { data, error, loading } = usePolled(() => api.servers.online(serverId), {
key: serverId,
intervalMs: 20_000,
})
const players = data ? data.players : []
if (loading) return <Loading />
if (error && !data) return <ErrorState error={error} />
// Nothing names who is online by default (the org lead's rule). Below the
// operator's audience the server answers a count and no names, and the page
// says so — an empty list here would read as "nobody is on", which is a
// different claim and a false one.
if (data && data.hidden) {
const count = Number(data.count) || 0
return (
<Empty
title={online ? `${count.toLocaleString()} ${count === 1 ? 'player' : 'players'} online` : 'The server is offline'}
message={hiddenMessage(data.audience)}
/>
)
}
if (players.length === 0) {
return (
<Empty
title={online ? 'Nobody is on' : 'The server is offline'}
message={
online
? 'The server is up and the island is empty. Somebody has to be first.'
: 'Presence is the one thing on this page that cannot be answered from the record — it is who is connected now, and nothing is.'
}
/>
)
}
return (
<>
{/* A board is the last one that ARRIVED, and an unreachable sidecar does not
clear it — deliberately, because the rows are still the best answer
anybody has. But presented bare they read as "these people are on right
now", which is the one thing an offline server cannot be saying. The
page walk found this with a fixture server whose header said Offline
above three apparently-connected players. */}
{!online && (
<p className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem', marginTop: 0 }}>
This server is offline. Below is the last board it sent, not who is on it now.
</p>
)}
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{players.map((player) => (
<li
key={player.steamId}
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'baseline',
gap: 12,
padding: '8px 0',
borderBottom: '1px solid var(--line-soft, var(--line))',
}}
>
<span>
<strong style={{ color: 'var(--ink)' }}>{player.name || shortId(player.steamId)}</strong>
{/* Sleeping is not idle and not offline — a sleeping player's body is
in the world and can be killed, which is why the board carries the
flag at all. */}
{player.sleeping && (
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.76rem' }}> · sleeping</span>
)}
</span>
{/* `connectedAt` is absent for a player who was already on when the
plugin loaded — an unknown session length, which is not a session of
no length. Saying nothing is the honest render of that. */}
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.78rem', whiteSpace: 'nowrap' }}>
{player.connectedAt ? `on for ${sessionSoFar(player.connectedAt)}` : ''}
</span>
</li>
))}
</ul>
</>
)
}
/** How long a player has been on, from the DATETIME the board reported. */
function sessionSoFar(connectedAt) {
const since = Date.parse(connectedAt)
if (Number.isNaN(since)) return ''
return duration((Date.now() - since) / 1000)
}
/**
* Why something was withheld, in words a visitor can act on.
*
* `what` completes the sentence — "who they are", "what players did". The
* audience is the operator's (`staff` unless widened), and only `signed_in` is
* something a visitor can do anything about.
*/
export function hiddenMessage(audience, what = 'who they are') {
if (audience === 'signed_in') return `Sign in to see ${what}.`
if (audience === 'public') return `This site is not showing ${what} right now.`
return `Only this site’s staff can see ${what}.`
}

View File

@@ -0,0 +1,63 @@
// ── Tabs, bundled rather than borrowed ────────────────────────────────────
//
// The shared kit is nine members and it is CLOSED (MODULE_API.md §3.4): layout,
// headings, the three data-page states, the fetch hook, the session, the site
// and `Slot`. A tab strip is not in it, so it is here — which is the kit working
// as designed rather than a gap in it. What the kit guarantees is that a module
// page looks like the site while it loads and while it fails; everything a page
// builds on top of that is the module's own.
//
// It is styled with core's CSS VARIABLES and its `.pill` class rather than with
// colours of its own, so it re-themes with the instance (THEMING_AND_NAV.md).
// The one class this module must never write by hand is the shell wrapper —
// `PublicLayout`'s `shell` prop exists precisely so that one stays core's.
//
// **The selected tab lives in the URL, not in this component.** A tab strip that
// owned its own state would make every panel on this page unlinkable: "look at
// the leaderboard for this server" would be a sentence rather than a link, back
// would leave the page entirely, and a refresh would land on the first tab. So
// this is a controlled component and `ServerDetail` keeps the state in a search
// parameter.
export default function Tabs({ tabs, active, onSelect, label = 'Sections' }) {
return (
<div
role="tablist"
aria-label={label}
className="sans"
style={{
display: 'flex',
flexWrap: 'wrap',
gap: 8,
borderBottom: '1px solid var(--line)',
paddingBottom: 12,
marginBottom: 20,
}}
>
{tabs.map((tab) => {
const selected = tab.id === active
return (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={selected}
onClick={() => onSelect(tab.id)}
style={{
cursor: 'pointer',
padding: '6px 14px',
borderRadius: 'var(--radius-pill, 999px)',
fontSize: '0.82rem',
letterSpacing: '0.04em',
border: `1px solid ${selected ? 'var(--accent)' : 'var(--line)'}`,
background: selected ? 'var(--blue)' : 'transparent',
color: selected ? 'var(--accent-bright)' : 'var(--muted)',
}}
>
{tab.label}
</button>
)
})}
</div>
)
}

View File

@@ -0,0 +1,54 @@
// ── "This wipe" or "All time" ─────────────────────────────────────────────
//
// One control, used by two panels, because the wipe is a property of the PAGE
// rather than of the feed or the leaderboard — a reader who has chosen last
// month's map means it for both, and two selects that could disagree is a page
// that shows one wipe's kills next to another's leaderboard.
//
// It loads the wipe list itself. That is a second request for the same list the
// Wipes tab fetches, and it is the right trade: the alternative is the page
// fetching it on mount for a control most visitors never touch, on every visit,
// for every server.
import { useAsync } from '../core.js'
import { day } from '../lib/format.js'
import api from '../api.js'
/** The value that means "no wipe filter at all". Never the empty string — see `api.js`'s `query`. */
export const ALL_TIME = 'all'
export default function WipeSelect({ serverId, value, onChange, currentWipeId }) {
const { data } = useAsync(() => api.servers.wipes(serverId), [serverId])
const wipes = data ? data.wipes : []
// A server with one wipe has nothing to choose between, so the control is not
// offered. "All time" and "this wipe" are the same answer there, and a select
// with one real option is furniture that invites a question with no answer.
if (wipes.length < 2) return null
return (
<label className="sans" style={{ color: 'var(--dim)', fontSize: '0.78rem' }}>
Wipe{' '}
<select
value={value || ALL_TIME}
onChange={(event) => onChange(event.target.value)}
style={{
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input, 6px)',
padding: '3px 8px',
fontSize: '0.78rem',
}}
>
<option value={ALL_TIME}>All time</option>
{wipes.map((wipe) => (
<option key={wipe.wipeId} value={wipe.wipeId}>
{day(wipe.saveCreatedAt || wipe.firstSeen)}
{wipe.wipeId === currentWipeId ? ' (current)' : ''}
</option>
))}
</select>
</label>
)
}

View File

@@ -0,0 +1,86 @@
// ── Every wipe this server has had ────────────────────────────────────────
//
// The list is what makes the rest of the page navigable — picking a wipe here
// filters the feed and the leaderboard — and it is also the proof R12 asks for:
// a wipe that ended is still here, with its record still attached. A Rust server
// wipes monthly, and a community site that forgot the previous map every time
// would throw away most of what it knows about its own players.
//
// `wipeId` is derived by the bridge PLUGIN from the save's creation time and
// stamped on every frame (PROTOCOL.md §8.2), so the id in this list is the same
// id the events and the leaderboard filter by. There is no second derivation
// anywhere that could disagree.
import { ErrorState, Loading, useAsync } from '../core.js'
import Empty from './Empty.jsx'
import { ago, day } from '../lib/format.js'
import api from '../api.js'
export default function Wipes({ serverId, currentWipeId, selected, onSelect }) {
const { data, loading, error } = useAsync(() => api.servers.wipes(serverId), [serverId])
const wipes = data ? data.wipes : []
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
if (wipes.length === 0) {
return (
<Empty
title="No wipes recorded"
message="A wipe appears here once this server has reported something during it."
/>
)
}
return (
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{wipes.map((wipe) => {
const current = wipe.wipeId === currentWipeId
const active = wipe.wipeId === selected
return (
<li key={wipe.wipeId} style={{ borderBottom: '1px solid var(--line-soft, var(--line))' }}>
<button
type="button"
onClick={() => onSelect(wipe.wipeId)}
style={{
display: 'flex',
width: '100%',
gap: 12,
alignItems: 'baseline',
justifyContent: 'space-between',
padding: '10px 6px',
cursor: 'pointer',
background: active ? 'var(--blue)' : 'transparent',
border: 'none',
color: 'inherit',
font: 'inherit',
textAlign: 'left',
}}
>
<span>
<strong style={{ color: 'var(--ink)' }}>
{/* The save's creation time is the wipe's own date; `firstSeen`
is when THIS website first heard about it, and they differ
by however long the module was not installed. The first is
the wipe, so it leads. */}
{day(wipe.saveCreatedAt || wipe.firstSeen)}
</strong>
{current && (
<span className="sans" style={{ color: 'var(--mode-live, #5fb98a)', fontSize: '0.74rem' }}>
{' · current'}
</span>
)}
<span className="sans" style={{ display: 'block', color: 'var(--dim)', fontSize: '0.74rem' }}>
{wipe.wipeId}
</span>
</span>
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.78rem', whiteSpace: 'nowrap' }}>
last heard {ago(wipe.lastSeen)}
</span>
</button>
</li>
)
})}
</ul>
)
}

View File

@@ -19,6 +19,19 @@
import { registry, coreApiVersion } from './core.js'
import Servers from './routes/public/Servers.jsx'
import ServerDetail from './routes/public/ServerDetail.jsx'
import Clan from './routes/public/Clan.jsx'
import Account from './routes/player/Account.jsx'
import Permissions from './routes/admin/Permissions.jsx'
import ModConfig from './routes/admin/ModConfig.jsx'
import Visibility from './routes/admin/Visibility.jsx'
import ServerSettings from './routes/admin/ServerSettings.jsx'
import ZonePresets from './routes/admin/ZonePresets.jsx'
import NpcProfiles from './routes/admin/NpcProfiles.jsx'
import NpcPlacements from './routes/admin/NpcPlacements.jsx'
import UserRustSections from './routes/admin/UserRustSections.jsx'
import FooterStatus from './components/FooterStatus.jsx'
import { IconEye, IconKey, IconLink, IconNpc, IconPlacement, IconServer, IconSliders, IconZone } from './icons.jsx'
// The module id, exactly as `module.json` spells it. Core keys the registry by it
// and prefixes every route path with it.
@@ -33,7 +46,7 @@ const ID = 'rust'
// installed side by side cannot collide, and an operator can see from a URL which
// module served it.
//
// So this page is at `/rust/servers`.
// So the list below is at `/rust` and the detail page at `/rust/servers/:id`.
//
// **Note what is NOT here: an auth wrapper.** `gate: { roles: [...] }` is
// available and core applies it as its own `RoleGate`; supplying your own is not
@@ -41,11 +54,72 @@ const ID = 'rust'
// see what, and they only do if one thing decides.
//
// R8's landing page is the server list, and `/rust/servers/:id` hangs beneath it.
// The detail route is a later phase's, and it is deliberately not stubbed here: a
// registered route that renders nothing is a 200 with a blank page, which is
// worse than the 404 an unregistered one gives.
//
// **The list is registered with an EMPTY path**, which core renders as the
// module's namespace root: `/rust`. The prefixing code strips the separator it
// would otherwise leave behind (`registry.js`: `${id}/${path}` with trailing
// slashes trimmed), so a module can own its own root without being able to spell
// its way out of it. Phase 1 served this page at `/rust/servers` and left `/rust`
// to core's CMS catch-all; the org lead settled it at `/rust` in phase 4, so the
// address an operator links to is the module's name.
//
// React Router ranks a static segment above a dynamic one, so `/rust` wins
// against core's `/:slug` CMS route without depending on registration order.
//
// The player route is registered with an empty path for the same reason the
// public list is: `/player/rust` is the whole of what this module asks a player
// to do, and a landing page above one page is a page nobody wants. Core applies
// its own portal chrome and its own auth gate to the tier, so the component
// renders no layout and re-implements no check.
//
// **The admin route arrives in phase 7 and is this module's first.** Everything
// before it was configured through the API — the server rows still are — because
// nothing until now had to be AUTHORED. A permission model is different in kind:
// it is a thing an operator composes and keeps looking at, and there is no
// version of "grant somebody VIP" that belongs in a terminal.
//
// It is registered with an empty path, so it lands at `/admin/rust`, and core
// applies the admin tier's own gate. The routes underneath it are stricter than
// that gate (`requireRole('admin')` on every one), which is a server-side answer
// rather than a client one: a moderator who reached this page would see it fail
// honestly rather than be quietly shown a page that cannot save.
registry.registerRoutes(ID, {
public: [{ path: 'servers', element: <Servers /> }],
public: [
{ path: '', element: <Servers /> },
{ path: 'servers/:id', element: <ServerDetail /> },
// Phase 9 (D56). Not nested under its server: core links here from Team
// notification email through `pageUrlTemplate`, which substitutes
// `{externalId}` and nothing else — and the server is inside that id.
{ path: 'clans/:externalId', element: <Clan /> },
],
player: [{ path: '', element: <Account /> }],
admin: [
{ path: '', element: <Permissions /> },
// Phase 7b (R18). A second admin page rather than a tab on the first: the
// permission mirror decides who may do what inside the game, and this edits
// the game host's own files. They are neighbours, not halves of one screen,
// and the nav says so with two rows.
//
// A static segment under the module's namespace, so it lands at
// `/admin/rust/config` and core's admin gate applies to it exactly as it
// does to the page above.
{ path: 'config', element: <ModConfig /> },
// Who may see who is online — a third neighbour. The org lead's rule is that
// nothing names who is online by default; this is where an operator widens
// it on purpose, fleet-wide or per server.
{ path: 'visibility', element: <Visibility /> },
// The servers themselves (phase 16, D133): the page that was missing. Until
// it, a server row was written only through the API, and D130's wipe
// schedule needed somewhere to be typed.
{ path: 'servers', element: <ServerSettings /> },
// Zone presets (PLAN_REDESIGNS §3.1, D210). Core's step editor has single-
// value fields, so a zone's flags are ticked here and a step copies the set.
{ path: 'zones', element: <ZonePresets /> },
// RunicNPC (runicnpc stage 4): the site's NPC profiles, pushed to each
// server, and each server's placements, created by clicking its live map.
{ path: 'npcs', element: <NpcProfiles /> },
{ path: 'npcs/placements', element: <NpcPlacements /> },
],
})
// ── Nav ───────────────────────────────────────────────────────────────────
@@ -67,9 +141,80 @@ registry.registerRoutes(ID, {
// one is the only row in its sidebar with no glyph, which reads as breakage.
registry.registerNav(ID, {
area: 'public',
items: [{ label: 'Servers', to: '/rust/servers' }],
items: [{ label: 'Servers', to: '/rust' }],
})
// The player portal's row. It carries an `icon` because core draws one on every
// portal row — a row without one is the only text in a column of glyphs, and
// core used to render `<n.icon />` unguarded, which blanked the whole portal.
//
// No `order`: an unordered row appends after core's own rather than claiming a
// position it was not given. Account, appeals and notifications are what a player
// came to the portal for; linking a game account is what they do once.
registry.registerNav(ID, {
area: 'player',
items: [{ label: 'Rust', to: '/player/rust', icon: IconLink }],
})
// The admin sidebar's row. `group` names an existing core group — an unknown name
// appends a new group at the end rather than dropping the row, which is the
// failure mode to avoid here: a row nobody can find is a feature nobody has.
//
// It carries an icon for the same reason the player row does: core draws one on
// every sidebar row, and the one without is the only text in a column of glyphs.
registry.registerNav(ID, {
area: 'admin',
items: [
{ label: 'Rust permissions', to: '/admin/rust', icon: IconKey },
{ label: 'Rust mod config', to: '/admin/rust/config', icon: IconSliders },
{ label: 'Rust visibility', to: '/admin/rust/visibility', icon: IconEye },
{ label: 'Rust servers', to: '/admin/rust/servers', icon: IconServer },
{ label: 'Rust zone presets', to: '/admin/rust/zones', icon: IconZone },
{ label: 'Rust NPC profiles', to: '/admin/rust/npcs', icon: IconNpc },
{ label: 'Rust NPC placements', to: '/admin/rust/npcs/placements', icon: IconPlacement },
],
})
// ── Extension slots ───────────────────────────────────────────────────────
//
// Core declares a slot, only core may declare one, and at most one module may
// fill it (§3.7). `site.footer.status` is the status-ish spot in core's footer
// info row: core owns the position and passes `linkStyle`; the label, the
// destination, the data and whether anything renders at all are the module's.
//
// It is a CLIENT slot and cannot be named in `module.json`'s `extensions` —
// that array is validated against the SERVER registry, and naming a client slot
// there fails the load outright with `unknown extension slot`. Phase 1 found
// that the hard way; the two halves of R13 are declared in different places on
// purpose.
registry.registerExtension(ID, 'site.footer.status', FooterStatus)
// R13's other slot, and the one that IS named in `module.json` — because it has
// a server half too (`server/router/admin/usersRust.router.js`). The two halves
// carry one name on purpose: a module that adds routes under
// `/api/v1/admin/users/:id` is the module with something to show on that page.
//
// Core passes `userId` and nothing else, so the component builds its own client
// for the routes the server half registered. It renders NOTHING for a user with
// no linked Steam account, which is most of them.
registry.registerExtension(ID, 'admin.users.detail', UserRustSections)
// ── Inverted slots: core's Team contributions on OUR clan page ─────────────
//
// §3.7a. A clan is a Team (R5), and core renders no Team page because it does
// not own the word "clan". So the page is `routes/public/Clan.jsx` and core
// contributes the three things only it can render — into places this module
// names, in this module's vocabulary. Core offers a CONTRIBUTION; it never names
// a slot, which is what lets a second game use the same contract as module-uo.
//
// One slot per PLACE (D56): a slot holds one component, and a collapsed slot
// would hand core the decision about where each part sits on a page it does not
// own. Asking for a contribution core does not offer throws here, at
// registration — a typo fails loudly rather than rendering nothing for ever.
registry.declareModuleSlot(ID, 'rust.clan.header', { core: 'team.notify' })
registry.declareModuleSlot(ID, 'rust.clan.detail', { core: 'team.activity' })
registry.declareModuleSlot(ID, 'rust.clan.forum', { core: 'team.forum' })
// `module.json`'s `coreApi` range was checked by the loader before this file was
// ever served, so there is nothing to re-check here. Log it anyway: a mismatch
// between the core that validated the manifest and the core that published this

View File

@@ -0,0 +1,116 @@
// ── A poll that keeps what it already had ─────────────────────────────────
//
// **Why this is not `useAsync`.** Core's hook (MODULE_API.md §3.4, and
// `client/src/lib/useAsync.js` in core) is `useState({loading:true,error:null,data:null})`
// re-run on a dependency change — and the first thing it does on every run is
// blank `data` and set `loading`. That is right for a page load and wrong for a
// poll: bumping a dependency every twenty seconds would clear the killfeed,
// render `<Loading />` in its place and re-fill it, four times a minute, for ever.
//
// So a poll needs a hook whose refresh is INVISIBLE when it succeeds. It keeps
// the previous rows on screen, replaces them when the new ones arrive, and keeps
// them *and* reports the error when the fetch fails — because a site whose whole
// premise is "it renders while the game is off" must not blank the page the
// first time a request does.
//
// `useAsync` is still the right hook for everything that loads once, and the
// pages here use it for exactly that. Bundling this beside it is the kit working
// as intended: the nine shared members are the chrome every module must share,
// not a ceiling on what a module may write.
//
// ── Two behaviours worth knowing ──────────────────────────────────────────
//
// 1. **A backgrounded tab does not poll.** Page Visibility, plus an immediate
// refresh when the viewer comes back — which is also the moment stale rows
// are most visible. A tab left open overnight is otherwise a request every
// twenty seconds until the laptop dies.
// 2. **`key` resets, dependencies do not.** Switching server or wipe SHOULD
// blank the rows: what is on screen belongs to a different question. That is
// what `key` is for, and it is separate from the interval.
import { useCallback, useEffect, useRef, useState } from 'react'
/**
* @param {() => Promise<any>} fetcher called with no arguments; must not throw synchronously
* @param {object} options
* @param {string} options.key changes when the QUESTION changes, blanking the answer
* @param {number} options.intervalMs 0 disables polling — the hook then loads once
* @param {boolean} options.enabled false while the page has nothing to ask about yet
*/
export function usePolled(fetcher, { key = '', intervalMs = 20000, enabled = true } = {}) {
const [state, setState] = useState({ data: null, error: null, loading: enabled, at: null })
// The fetcher is rebuilt on every render — it closes over props — and a hook
// that listed it as a dependency would restart its interval every render. The
// ref is how the timer keeps calling the CURRENT one without depending on it.
const latest = useRef(fetcher)
latest.current = fetcher
// Guards a reply from a question nobody is asking any more: a slow request
// whose page has moved on, or one still in flight at unmount.
const generation = useRef(0)
const run = useCallback(
async (mine) => {
try {
const data = await latest.current()
if (mine !== generation.current) return
setState({ data, error: null, loading: false, at: Date.now() })
} catch (error) {
if (mine !== generation.current) return
// `data` is carried forward deliberately. A failed refresh is a page that
// says "this is what we last knew, and it did not refresh", which is the
// same promise the server list makes about a game server being down.
setState((prev) => ({ data: prev.data, error, loading: false, at: prev.at }))
}
},
[],
)
const refresh = useCallback(() => run(generation.current), [run])
useEffect(() => {
generation.current += 1
const mine = generation.current
if (!enabled) {
setState({ data: null, error: null, loading: false, at: null })
return undefined
}
setState({ data: null, error: null, loading: true, at: null })
run(mine)
if (!intervalMs) return () => { generation.current += 1 }
let timer = null
const visible = () => typeof document === 'undefined' || document.visibilityState === 'visible'
const start = () => {
if (timer === null) timer = setInterval(() => run(mine), intervalMs)
}
const stop = () => {
if (timer !== null) { clearInterval(timer); timer = null }
}
const onVisibility = () => {
if (visible()) { run(mine); start() } else stop()
}
if (visible()) start()
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibility)
return () => {
// Bumping the generation on teardown is what makes an in-flight reply from
// the old question land nowhere. Clearing the timer alone would not.
generation.current += 1
stop()
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility)
}
}, [key, intervalMs, enabled, run])
return { ...state, refresh }
}
export default usePolled

148
client/src/icons.jsx Normal file
View File

@@ -0,0 +1,148 @@
// ── The nav glyph for this module's player-portal row ─────────────────────
//
// `icon` is part of the nav-item contract (MODULE_API.md §3.3, 1.3.0): core
// renders whatever component a row carries, exactly as it renders its own rows'
// icons — and core's player portal draws a glyph on every row, so a row without
// one reads as breakage rather than as a design. The client suite asserts it.
//
// The public header is text buttons and carries no icons, which is why this file
// arrives with the player row and not before it.
//
// **The frame is copied from core's `PlayerPortalLayout`, deliberately and by
// copy rather than by import** — 16px, `currentColor`, stroke 2. Four attributes
// of presentation are not a component: putting them in the shared kit would
// freeze core's icon sizing into the contract, where changing it later would be a
// major bump. A module that wants to look like the nav it is in matches that nav.
const Icon = ({ children }) => (
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
>
{children}
</svg>
)
/**
* A chain link — what the row is for.
*
* Not a gem, a person or a server: the portal's rows say what a player does
* there, and what a player does at `/player/rust` is link an account. Core's own
* neighbours are a gear (account), a shield (appeals) and a bell (notifications),
* so the row has to read as a verb in that company.
*/
export const IconLink = () => (
<Icon>
<path d="M10 13a5 5 0 007.07 0l2.83-2.83a5 5 0 00-7.07-7.07L11.5 4.5" />
<path d="M14 11a5 5 0 00-7.07 0L4.1 13.83a5 5 0 007.07 7.07L12.5 19.5" />
</Icon>
)
/**
* A key — the admin sidebar's row for the permission mirror.
*
* Core's admin groups are labelled by subject and drawn with glyphs of the same
* weight, so this is the same 16px frame as the portal's. A key rather than a
* shield: a shield is protection from something, and this row is about handing
* somebody the right to do something.
*/
export const IconKey = () => (
<Icon>
<circle cx="7.5" cy="15.5" r="4.5" />
<path d="M10.7 12.3L20 3" />
<path d="M17 6l2.5 2.5" />
</Icon>
)
/**
* Sliders — the admin sidebar's row for the mod-configuration editor.
*
* Not a gear: core's account row is a gear, and two gears in one sidebar say
* "settings" twice without saying whose. Sliders read as values being tuned,
* which is exactly what that page does to somebody else's game host.
*/
export const IconSliders = () => (
<Icon>
<path d="M4 6h10" />
<path d="M18 6h2" />
<circle cx="16" cy="6" r="2" />
<path d="M4 12h4" />
<path d="M12 12h8" />
<circle cx="10" cy="12" r="2" />
<path d="M4 18h10" />
<path d="M18 18h2" />
<circle cx="16" cy="18" r="2" />
</Icon>
)
/**
* An eye — the admin sidebar's row for who may see who is online.
*
* The page decides what the public can SEE, so the glyph is the act of seeing.
*/
export const IconEye = () => (
<Icon>
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
<circle cx="12" cy="12" r="3" />
</Icon>
)
/**
* Two stacked units — the admin sidebar's row for the servers themselves.
*
* The one row that is about the machines rather than what happens on them: the
* sidecar each one answers through, and when each one wipes.
*/
export const IconServer = () => (
<Icon>
<rect x="3" y="4" width="18" height="7" rx="1.5" />
<rect x="3" y="13" width="18" height="7" rx="1.5" />
<path d="M7 7.5h.01" />
<path d="M7 16.5h.01" />
</Icon>
)
export default { IconLink, IconKey, IconSliders, IconEye, IconServer }
/**
* A circle inside a dashed ring — the admin sidebar's row for zone presets.
*
* A zone is an area with rules at its edge, so the glyph is a place and its
* boundary rather than a map pin, which the live map already means.
*/
export const IconZone = () => (
<Icon>
<circle cx="12" cy="12" r="9" strokeDasharray="3 3" />
<circle cx="12" cy="12" r="3" />
</Icon>
)
/**
* A figure — the admin sidebar's row for RunicNPC's profiles (runicnpc stage 4).
* A head and shoulders: the page is about who the NPCs are.
*/
export const IconNpc = () => (
<Icon>
<circle cx="12" cy="8" r="3.5" />
<path d="M5 20c0-3.9 3.1-7 7-7s7 3.1 7 7" />
</Icon>
)
/**
* A figure on a spot — the admin sidebar's row for NPC placements: where they stand.
*/
export const IconPlacement = () => (
<Icon>
<circle cx="12" cy="6" r="2.5" />
<path d="M8 15c0-2.2 1.8-4 4-4s4 1.8 4 4" />
<ellipse cx="12" cy="19" rx="7" ry="2" />
</Icon>
)

180
client/src/lib/feed.js Normal file
View File

@@ -0,0 +1,180 @@
// ── One stored frame as one line of a feed ────────────────────────────────
//
// `GET /public/rust/servers/:id/events` answers rows shaped
// `{ id, kind, t, wipeId, steamId, frame }`, where `frame` is the whole frame
// the plugin emitted — this module stores what it is given and indexes only the
// columns it serves (PROTOCOL.md §8.4, and the `raw` column in schema.sql). So
// everything a killfeed line needs is in `frame`, under the names the plugin
// wrote, and this file is the one place that knows them.
//
// **It returns PARTS, not a sentence.** A component wants the names emphasised
// and the detail muted, and a function returning `"Alice killed Bob"` forces
// either a `dangerouslySetInnerHTML` or a re-parse. Parts also make this
// testable without a DOM, which is the whole reason it is not a component.
//
// ── The rule for an unknown kind ──────────────────────────────────────────
//
// It renders as itself. A later protocol adds kinds, an operator's module may be
// older than their game host, and a feed that DROPPED what it did not recognise
// would be a page that quietly says less than the truth. The server's allowlist
// has already decided this row may be seen (`server/catalogue.js`); what is left
// here is presentation, and the honest presentation of a kind we have no words
// for is its own name.
import { attacker, duration, prefab } from './format.js'
/**
* Kinds this feed asks for.
*
* `player.tally` is public and deliberately NOT here: it is an aggregate the
* plugin flushes every sixty seconds per active player (§8.6), so a feed
* including it would be mostly wood counts. It is the leaderboard's input, and
* the leaderboard is where it shows up.
*/
export const FEED_KINDS = Object.freeze([
'player.death',
'player.connected',
'player.disconnected',
'player.respawned',
'player.chat',
'server.wipe',
'server.initialized',
'server.shutdown',
])
/** The filters the feed offers, and the kinds each one asks the API for. */
export const FILTERS = Object.freeze([
{ id: 'all', label: 'Everything', kinds: FEED_KINDS },
{ id: 'kills', label: 'Kills', kinds: ['player.death'] },
{ id: 'chat', label: 'Chat', kinds: ['player.chat'] },
{
id: 'sessions',
label: 'Comings and goings',
kinds: ['player.connected', 'player.disconnected', 'player.respawned'],
},
{ id: 'server', label: 'Server', kinds: ['server.wipe', 'server.initialized', 'server.shutdown'] },
])
export function kindsFor(filterId) {
const filter = FILTERS.find((f) => f.id === filterId)
return (filter || FILTERS[0]).kinds
}
/**
* One row as `{ tone, actor, join, verb, subject, detail }`.
*
* `actor` and `subject` are names and are emphasised; `verb` and `detail` are
* prose. Any of them may be empty. `tone` is the row's category, for the small
* colour the component gives it — never for deciding what a row means.
*
* `join` is what goes between the actor and the verb, and it exists for exactly
* one case: chat. "Brannock see you in september" is not a sentence anybody
* writes, and putting the colon in the message would put presentation inside the
* text a player typed.
*/
export function describe(row) {
const frame = (row && row.frame) || {}
const name = frame.name || null
switch (row && row.kind) {
case 'player.death':
return death(frame, name)
case 'player.connected':
return { tone: 'join', actor: name, verb: 'connected', subject: null, detail: '' }
case 'player.disconnected':
return {
tone: 'leave',
actor: name,
verb: 'disconnected',
subject: null,
// Two optional halves, and the session is the interesting one: the plugin
// omits `sessionSec` for a player who was already on when it loaded, so an
// absent value means "unknown", never zero (§8.4's note, and OnPlayerDisconnected).
detail: [frame.reason || null, frame.sessionSec ? `after ${duration(frame.sessionSec)}` : null]
.filter(Boolean)
.join(' · '),
}
case 'player.respawned':
return { tone: 'join', actor: name, verb: 'respawned', subject: null, detail: '' }
case 'player.chat':
return {
tone: 'chat',
actor: name,
join: ': ',
// The message is the row, so it goes in `verb` where a component renders
// it unemphasised — and it is the one field on this wire a player chooses
// the bytes of. React escapes it; nothing here may ever stop doing that.
verb: frame.message || '',
subject: null,
detail: frame.channel && frame.channel !== 'Global' ? frame.channel : '',
}
case 'server.wipe':
return {
tone: 'server',
actor: null,
verb: 'The map was wiped',
subject: null,
detail: frame.wipeId ? `new wipe ${frame.wipeId}` : '',
}
case 'server.initialized':
return { tone: 'server', actor: null, verb: 'The server came up', subject: null, detail: '' }
case 'server.shutdown':
return { tone: 'server', actor: null, verb: 'The server went down', subject: null, detail: '' }
default:
return { tone: 'other', actor: name, verb: String((row && row.kind) || 'unknown'), subject: null, detail: '' }
}
}
/**
* A death, which is four different sentences.
*
* The plugin distinguishes `player`, `self`, `npc` and `environment` precisely so
* that a reader does not have to guess from an absent field, and collapsing any
* two of them loses something (see `DescribeAttacker` in the bridge plugin). A
* killfeed that reported a fall as a kill by nobody is the failure this avoids.
*/
function death(frame, name) {
const where = [
frame.weapon ? `with ${prefab(frame.weapon)}` : null,
frame.distance ? `${Math.round(frame.distance)}m` : null,
frame.grid || null,
frame.sleeping ? 'while sleeping' : null,
]
.filter(Boolean)
.join(' · ')
switch (frame.attackerType) {
case 'player':
return { tone: 'kill', actor: frame.attackerName || null, verb: 'killed', subject: name, detail: where }
case 'self':
return { tone: 'death', actor: name, verb: 'died by their own hand', subject: null, detail: where }
case 'npc':
return {
tone: 'death',
// One of RunicNPC's (runicnpc stage 4): its own name, as typed on its profile,
// rather than the prefab it is built from. Older frames carry only the prefab.
actor: frame.attackerNpc || attacker(frame.attackerName) || 'Something',
verb: 'killed',
subject: name,
detail: where,
}
// `environment` and anything else: falling, drowning, the world. `HitInfo`
// is legitimately null on this path, so an absent attacker type is this case
// rather than a missing field to complain about.
default:
return { tone: 'death', actor: name, verb: 'died', subject: null, detail: where }
}
}
export default { describe, FEED_KINDS, FILTERS, kindsFor }

231
client/src/lib/format.js Normal file
View File

@@ -0,0 +1,231 @@
// ── Formatting, with no dependencies and no React ─────────────────────────
//
// Every function here is pure and takes what the API answered, so the suite next
// door can ask all of it without a DOM. That is deliberate: the client half's
// real failures are timing and resolution (see `test/build.test.js`), which a
// DOM-less runner cannot see — so the way to have any test coverage at all on
// this side is to keep the parts that CAN be tested free of React.
//
// `Intl` does the work. It is in every browser core supports, it knows the
// viewer's locale and their clock, and it is one fewer thing in a chunk an
// operator ships.
const RELATIVE = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
const UNITS = [
['year', 31536000],
['month', 2592000],
['week', 604800],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1],
]
/**
* "3 minutes ago", from an ISO string or an epoch-millisecond number.
*
* Both shapes arrive from this module's own API: `updatedAt` is an ISO string
* the model produced, and an event's `t` is the millisecond stamp the plugin put
* on the frame. Accepting both here is what stops every caller remembering which
* is which.
*/
export function ago(value, now = Date.now()) {
const at = toMillis(value)
if (at === null) return 'never'
const seconds = Math.round((at - now) / 1000)
const magnitude = Math.abs(seconds)
// Under a minute, "in 0 seconds" is what `numeric: 'auto'` produces and it is
// not what anybody means. Say the thing.
if (magnitude < 45) return 'just now'
const [unit, size] = UNITS.find(([, s]) => magnitude >= s) || ['second', 1]
return RELATIVE.format(Math.round(seconds / size), unit)
}
/**
* The stamp on a feed row.
*
* **Today's rows get a time; everything older gets a date as well.** The feed can
* be filtered to a past wipe, and a row from six weeks ago rendered as `02:03 PM`
* reads as this afternoon — which the page walk found the moment it looked at the
* previous wipe: three events from August, all apparently a few minutes old.
*
* `now` is a parameter so the boundary is testable rather than a property of the
* machine the test runs on.
*/
export function clock(value, now = Date.now()) {
const at = toMillis(value)
if (at === null) return ''
const when = new Date(at)
const time = when.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
const today = new Date(now)
const sameDay =
when.getFullYear() === today.getFullYear() &&
when.getMonth() === today.getMonth() &&
when.getDate() === today.getDate()
if (sameDay) return time
return `${when.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })} ${time}`
}
/** A date, for a wipe: the thing people actually compare wipes by. */
export function day(value) {
const at = toMillis(value)
if (at === null) return 'unknown'
return new Date(at).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
}
/**
* A session or a playtime, as `4h 12m`.
*
* Seconds are dropped above a minute and kept below it, because a two-hour
* session reported to the second is noise and a forty-second one reported as
* "0m" is wrong.
*/
export function duration(seconds) {
const total = Number(seconds)
if (!Number.isFinite(total) || total <= 0) return '—'
if (total < 60) return `${Math.round(total)}s`
const hours = Math.floor(total / 3600)
const minutes = Math.round((total % 3600) / 60)
if (hours === 0) return `${minutes}m`
return minutes === 0 ? `${hours}h` : `${hours}h ${minutes}m`
}
/** Thousands separators, in the viewer's locale. */
export function count(value) {
const n = Number(value)
return Number.isFinite(n) ? n.toLocaleString() : '0'
}
/**
* A prefab short name as something readable — `patrolhelicopter` stays itself,
* `rifle.ak` becomes `rifle ak`.
*
* Deliberately a light touch rather than a lookup table. A table mapping every
* Rust prefab to a pretty name is a second copy of the game's item list that
* goes stale every wipe, and the short name is what a Rust player reads on their
* own server console anyway.
*/
export function prefab(name) {
if (!name) return ''
return String(name).replace(/[_.]+/g, ' ').trim()
}
/**
* The NPC families whose prefab reads badly as words, by the prefix the game's
* short names share. First match wins, so a longer prefix sits above a shorter
* one it starts with.
*/
const NPC_FAMILIES = [
['scientistnpc_heavy', 'Heavy scientist'],
['scientistnpc', 'Scientist'],
['npc_bandit_guard', 'Bandit guard'],
['bandit_guard', 'Bandit guard'],
['npc_tunneldweller', 'Tunnel dweller'],
['npc_underwaterdweller', 'Underwater dweller'],
['bradleyapc', 'Bradley APC'],
['patrolhelicopter', 'Patrol helicopter'],
['ch47scientists', 'Chinook'],
['sentry.scientist', 'Outpost sentry'],
['sentry.bandit', 'Bandit Camp sentry'],
['autoturret', 'Auto turret'],
['flameturret', 'Flame turret'],
['guntrap', 'Shotgun trap'],
['sam_site', 'SAM site'],
['sam_static', 'SAM site'],
['polarbear', 'Polar bear'],
['simpleshark', 'Shark'],
]
/**
* What killed somebody, when it was not a player (PLAN_FIXES F2, D185) — the
* killfeed's `npc` attacker, which the plugin sends as a prefab short name.
*
* The first walk read "killed by wolf2". `prefab` keeps its light touch for a
* weapon, where the short name is what a Rust player reads on their own console;
* an ATTACKER is a creature or a machine, and a number stuck to its name is the
* game's variant, not something a reader needs. So a known family is named
* (above), and anything else has its variant digits and deploy suffixes trimmed
* and reads as capitalised words — `wolf2` is "Wolf", `boar` is "Boar". Still no
* table of every prefab: a new animal reads fine without one.
*/
export function attacker(name) {
if (!name) return ''
const text = String(name).toLowerCase()
const family = NPC_FAMILIES.find(([prefix]) => text.startsWith(prefix))
if (family) return family[1]
const words = text
.replace(/(\.deployed|_deployed|\.entity|\.prefab)$/, '')
.replace(/\d+$/, '')
.replace(/[_.]+/g, ' ')
.trim()
return words ? words[0].toUpperCase() + words.slice(1) : ''
}
/** A steam id, shortened for a table cell, without pretending it is a name. */
export function shortId(steamId) {
const id = String(steamId || '')
return id.length > 10 ? `…${id.slice(-6)}` : id
}
/**
* The next wipe (phase 16, D130), as `Thu, Oct 1, 7:00 PM (in 6 days)` in the
* VIEWER's locale and clock — or `null` when the server has no schedule.
*
* The server computes the instant from the operator's rule in the operator's
* zone; the page only says it the reader's way. A `once` source is an operator
* moving a wipe, and says so, because "the wipe is not when it usually is" is
* the thing a regular needs to notice.
*/
export function nextWipe(value, now = Date.now()) {
if (!value || !value.at) return null
const at = toMillis(value.at)
if (at === null) return null
const when = new Date(at).toLocaleString(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
})
return `${when} (${ago(at, now)})${value.source === 'once' ? ' — rescheduled' : ''}`
}
function toMillis(value) {
if (value === null || value === undefined || value === '') return null
if (typeof value === 'number') return Number.isFinite(value) ? value : null
const parsed = Date.parse(value)
return Number.isNaN(parsed) ? null : parsed
}
/**
* The ink that reads on a background of `hex` — black or white, whichever has
* the higher WCAG contrast. A chat title's colour is the operator's, chosen for
* a dark game chat, and this page is drawn in the reader's theme: yellow text on
* a white page is unreadable, so the colour becomes the chip and the text is
* picked for it (phase 17, D137). Anything that is not `#rrggbb` gets black on
* the caller's fallback.
*/
export function contrastInk(hex) {
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(String(hex || ''))
if (!m) return '#000000'
const linear = (c) => {
const v = parseInt(c, 16) / 255
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
}
const L = 0.2126 * linear(m[1]) + 0.7152 * linear(m[2]) + 0.0722 * linear(m[3])
// Contrast against white is 1.05 / (L + 0.05); against black (L + 0.05) / 0.05.
return (L + 0.05) / 0.05 >= 1.05 / (L + 0.05) ? '#000000' : '#ffffff'
}
export default { ago, clock, day, duration, count, prefab, shortId, nextWipe, contrastInk }

28
client/src/lib/leaflet.js Normal file
View File

@@ -0,0 +1,28 @@
// ── Leaflet, and only when the Map tab asks for it ────────────────────────
//
// D116 put Leaflet on the map; D120 put it HERE, in a chunk of its own that the
// Map tab imports with `import()`. Two reasons, and both are about `entry.js`:
//
// • `entry.js` is loaded on EVERY page of the site, because core injects every
// started module's chunk into its shell. Leaflet in it would be ~40 KB gz on
// the home page, the forum and the news, for a tab most visitors never open.
// • Leaflet touches `document` and `window` the moment it is evaluated. The
// chunk is evaluated in Node by `test/registration.test.js`, with a
// `window` and nothing else — so Leaflet in the entry chunk fails that test
// at import, before a single registration is checked.
//
// Vite emits this as `dist/map-<hash>.js` beside `entry.js`. Core serves the
// directory `client.entry` sits in (MODULE_API.md §3.1), and `release.yml`
// copies every `.js` in it — `test/build.test.js` holds both ends of that.
//
// The ESM build is imported by path: Leaflet 1.9.4's package.json names only its
// UMD file, and the UMD one would go through CommonJS interop for nothing.
//
// The stylesheet comes in as a STRING and is injected once as a `<style>` by the
// page (core's CSP allows `style-src 'unsafe-inline'`). The map uses circle and
// div markers only, so the images Leaflet's CSS names are never shown.
import * as L from 'leaflet/dist/leaflet-src.esm.js'
import css from 'leaflet/dist/leaflet.css?inline'
export { L, css }

View File

@@ -0,0 +1,101 @@
// ── How a world position reaches a pixel ──────────────────────────────────
//
// PLAN.md §30.3, in the one place the page computes it. Rust's world is centred
// on the origin, x east and z north; the picture is the world at a scale, with
// an ocean margin around it that is measured in PIXELS and is not scaled (the
// rig's 3000 map is 3000 × 0.5 + 2 × 500 = 2500 pixels). So:
//
// s = (width − 2 × margin) / worldSize
// px = (x + worldSize / 2) × s + margin
// py = (z + worldSize / 2) × s + margin measured UP from the bottom edge
//
// Up from the bottom because Leaflet's `CRS.Simple` has y growing north, which
// is Rust's z — so the picture's bounds are `[[0, 0], [height, width]]` and a
// position is `[py, px]` with no flip anywhere.
//
// The grid is the GAME's (D119): `gridCells` cells of `gridCellSize` metres per
// side, lettered from the west and numbered from the north, `A0` at the
// north-west corner. Both numbers come from the plugin, which asks the game's own
// `MapHelper`; nothing here assumes a cell size.
//
// Pure, and free of Leaflet, so it is tested in Node.
/** Pixels per metre, or 0 for a geometry that cannot place anything. */
export function scaleOf(g) {
if (!g || !(g.worldSize > 0) || !(g.width > 0)) return 0
return (g.width - 2 * (g.oceanMargin || 0)) / g.worldSize
}
/** A world position as `[lat, lng]` in the map's pixel space. */
export function toLatLng(g, x, z) {
const s = scaleOf(g)
const half = g.worldSize / 2
const m = g.oceanMargin || 0
return [(Number(z) + half) * s + m, (Number(x) + half) * s + m]
}
/** The inverse of `toLatLng`: a point on the picture as world `{ x, z }` in metres (a click on the map). */
export function fromLatLng(g, lat, lng) {
const s = scaleOf(g)
if (!(s > 0)) return null
const half = g.worldSize / 2
const m = g.oceanMargin || 0
return { x: (Number(lng) - m) / s - half, z: (Number(lat) - m) / s - half }
}
/** The picture's bounds in the same space. */
export function boundsOf(g) {
return [[0, 0], [g.height, g.width]]
}
/** A column number as Rust spells it: 0 is A, 25 is Z, 26 is AA. */
export function column(index) {
let name = ''
let n = index + 1
while (n > 0) {
const r = (n - 1) % 26
name = String.fromCharCode(65 + r) + name
n = Math.floor((n - 1) / 26)
}
return name
}
/** The grid label for a world position, the way the in-game map writes it. */
export function gridLabel(g, x, z) {
if (!g || !(g.gridCells > 0) || !(g.gridCellSize > 0)) return null
const half = g.worldSize / 2
const clamp = (v) => Math.max(0, Math.min(g.gridCells - 1, v))
const col = clamp(Math.floor((Number(x) + half) / g.gridCellSize))
const row = clamp(Math.floor((half - Number(z)) / g.gridCellSize))
return `${column(col)}${row}`
}
/**
* The grid as lines and labels in world metres: `lines` are `[[x1, z1], [x2,
* z2]]` pairs, `labels` sit at each cell's north-west corner.
*/
export function grid(g) {
if (!g || !(g.gridCells > 0) || !(g.gridCellSize > 0)) return { lines: [], labels: [] }
const half = g.worldSize / 2
const n = g.gridCells
const c = g.gridCellSize
const lines = []
for (let i = 0; i <= n; i += 1) {
const at = -half + i * c
lines.push([[at, half], [at, half - n * c]])
lines.push([[-half, half - i * c], [-half + n * c, half - i * c]])
}
const labels = []
for (let col = 0; col < n; col += 1) {
for (let row = 0; row < n; row += 1) {
labels.push({ text: `${column(col)}${row}`, x: -half + col * c, z: half - row * c })
}
}
return { lines, labels }
}
/** Seconds as `m:ss`, for a locked crate's hack. */
export function countdown(seconds) {
const s = Math.max(0, Math.round(Number(seconds) || 0))
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
}

View File

@@ -0,0 +1,91 @@
// ── Which monument labels a map draws (PLAN_REDESIGNS §4, D196) ───────────
//
// The admin card's half of the rule `model/map/map.model.js` applies on the
// server: a switch per monument LABEL, the minor labels off unless somebody
// turns them on, every other label on. A server's switch wins over the fleet's,
// the fleet's over the built-in list.
//
// The form holds only the EXPLICIT switches, as the server does — `{ key: bool }`
// — so a label nobody touched keeps following the default above it. Setting the
// fleet back to what the built-in list says clears the row rather than storing a
// copy of the default: the next change to the list then reaches that label.
//
// Pure, and free of React, so it is tested in Node.
/** A label as its switch's key: trimmed, single-spaced, lower case. The server's rule exactly. */
export function markerKey(label) {
return String(label == null ? '' : label).trim().replace(/\s+/g, ' ').toLowerCase()
}
/** The built-in answer for one key: hidden for the minor labels, drawn for everything else. */
export function builtIn(minorLabels, key) {
return !(minorLabels || []).some((l) => markerKey(l) === key)
}
const has = (o, k) => Boolean(o) && Object.prototype.hasOwnProperty.call(o, k)
/** Whether the fleet draws one key: its own switch, or the built-in list. */
export function fleetShows(minorLabels, fleetMarkers, key) {
return has(fleetMarkers, key) ? fleetMarkers[key] : builtIn(minorLabels, key)
}
/** Whether one server draws one key: its switch, or the fleet's answer. */
export function serverShows(minorLabels, fleetMarkers, serverMarkers, key) {
return has(serverMarkers, key) ? serverMarkers[key] : fleetShows(minorLabels, fleetMarkers, key)
}
/**
* Every label the fleet list offers, sorted by name: each server's current
* labels and the minor list, each once. A minor label no map has yet is still
* listed, so it can be decided before a wipe brings it.
*/
export function fleetLabels(minorLabels, servers) {
const byKey = new Map()
// A capitalised spelling wins over the game's lower-case one ("jungle swamp").
const add = (key, label, count) => {
const seen = byKey.get(key)
if (!seen) byKey.set(key, { key, label, count })
else {
seen.count += count
if (seen.label === seen.label.toLowerCase() && label !== label.toLowerCase()) seen.label = label
}
}
for (const s of servers || []) {
for (const l of s.markerLabels || []) add(l.key, l.label, l.count || 0)
}
for (const label of minorLabels || []) add(markerKey(label), label, 0)
return [...byKey.values()].sort((a, b) => a.label.localeCompare(b.label))
}
/** The fleet form after ticking one key: an explicit switch, or none where it matches the built-in list. */
export function setFleet(minorLabels, fleetMarkers, key, shown) {
const next = { ...(fleetMarkers || {}) }
if (shown === builtIn(minorLabels, key)) delete next[key]
else next[key] = shown
return next
}
/** A server form after choosing one key: `null` follows the fleet, otherwise an explicit switch. */
export function setServer(serverMarkers, key, shown) {
const next = { ...(serverMarkers || {}) }
if (shown === null) delete next[key]
else next[key] = shown
return next
}
/**
* What changed between two explicit maps, as the PUT takes it: `{ key: bool }`
* for a switch set or changed, `{ key: null }` for one cleared. Null when
* nothing changed.
*/
export function markerDiff(before, now) {
const out = {}
const keys = new Set([...Object.keys(before || {}), ...Object.keys(now || {})])
for (const key of keys) {
const was = has(before, key) ? before[key] : undefined
const is = has(now, key) ? now[key] : undefined
if (was === is) continue
out[key] = is === undefined ? null : is
}
return Object.keys(out).length ? out : null
}

View File

@@ -0,0 +1,163 @@
// ── Admin · Rust · Permissions — a group's chat style (phase 17, D138) ─────
//
// All twelve of BetterChat's group fields, on a group this site authors. A style
// is the whole of a BetterChat group or nothing, so the editor always shows all
// twelve, starting from BetterChat's own defaults.
//
// Three things the section says out loud, because each looks like success from
// here:
//
// • a server where BetterChat is not loaded holds nothing yet — the style
// lands when BetterChat does, at the next sync;
// • a field somebody changed in game is NOT overwritten — it shows under
// "Changed in game", to adopt or put back;
// • a field BetterChat refused (`InvalidValue`) is named with its server.
//
// Removing a style removes the group from BetterChat on the next sync (D139),
// which is BetterChat's own `chat group remove` — it has no quieter way.
import { useState } from 'react'
const LABELS = {
Priority: 'Priority (lower wins when a player is in several groups)',
Title: 'Title',
TitleColor: 'Title colour',
TitleSize: 'Title size',
TitleHidden: 'Hide the title',
TitleHiddenIfNotPrimary: 'Hide the title unless this is the player’s main group',
UsernameColor: 'Name colour',
UsernameSize: 'Name size',
MessageColor: 'Message colour',
MessageSize: 'Message size',
ChatFormat: 'Chat format',
ConsoleFormat: 'Console format',
}
/** BetterChat's defaults for this group, from the field list the server sent. */
function defaultsFor(group, fields) {
const out = {}
for (const f of fields) out[f.name] = f.default === null ? '' : f.default
out.Title = group === 'default' ? '[Player]' : `[${group}]`
return out
}
/** What each server's last sync said about this group's style. */
function styleNotes(group, servers) {
const notes = []
for (const s of servers) {
const chat = s.report && s.report.chat
if (!chat) continue
if (chat.loaded === false) {
notes.push(`${s.serverId}: BetterChat is not loaded, so nothing is styled there yet.`)
continue
}
for (const f of chat.failed || []) {
if (f.group !== group) continue
notes.push(`${s.serverId}: BetterChat refused ${f.field || 'the group'} (${f.reason}).`)
}
}
return notes
}
export default function ChatStyleSection({ group, fields, servers, busy, onSave }) {
const [editing, setEditing] = useState(null)
if (!fields || !fields.length) return null
const notes = group.chat ? styleNotes(group.name, servers) : []
const set = (name, value) => setEditing((e) => ({ ...e, [name]: value }))
return (
<>
<div className="field-label" style={{ marginTop: 18 }}>
Chat style (BetterChat)
</div>
{!editing && !group.chat && (
<p className="sans dim" style={{ fontSize: '0.8rem', margin: '4px 0' }}>
No chat style. BetterChat, where it is installed, styles this group’s members as it does anybody else.
</p>
)}
{!editing && group.chat && (
<p className="sans" style={{ fontSize: '0.82rem', margin: '4px 0' }}>
<span style={{ color: /^#[0-9a-f]{6}$/i.test(group.chat.TitleColor) ? group.chat.TitleColor : undefined, fontWeight: 600 }}>
{group.chat.TitleHidden === 'true' ? '(title hidden)' : group.chat.Title}
</span>{' '}
<span className="dim" style={{ fontSize: '0.76rem' }}>
priority {group.chat.Priority} · <code>{group.chat.ChatFormat}</code>
</span>
</p>
)}
{notes.map((n) => (
<p key={n} className="sans" style={{ color: '#d08a2a', fontSize: '0.76rem', margin: '2px 0' }}>{n}</p>
))}
{!editing && (
<div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
<button
type="button"
className="btn"
disabled={busy}
onClick={() => setEditing({ ...defaultsFor(group.name, fields), ...(group.chat || {}) })}
>
{group.chat ? 'Edit the style' : 'Give it a chat style'}
</button>
{group.chat && (
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => onSave(null)}>
Remove the style
</button>
)}
</div>
)}
{editing && (
<form
onSubmit={async (event) => {
event.preventDefault()
if (await onSave(editing)) setEditing(null)
}}
className="sans"
style={{ display: 'grid', gap: 8, marginTop: 8, fontSize: '0.82rem' }}
>
{fields.map((f) => (
<label key={f.name} style={{ display: 'grid', gridTemplateColumns: 'minmax(160px, 1fr) 2fr', gap: 8, alignItems: 'center' }}>
<span>{LABELS[f.name] || f.name}</span>
{f.type === 'bool' ? (
<select className="input" value={editing[f.name]} onChange={(e) => set(f.name, e.target.value)}>
<option value="false">No</option>
<option value="true">Yes</option>
</select>
) : f.type === 'color' ? (
<span style={{ display: 'flex', gap: 6 }}>
<input
type="color"
value={/^#[0-9a-f]{6}$/i.test(editing[f.name]) ? editing[f.name] : '#ffffff'}
onChange={(e) => set(f.name, e.target.value)}
aria-label={LABELS[f.name]}
style={{ width: 36, height: 28, padding: 0, border: 'none', background: 'none' }}
/>
<input className="input" value={editing[f.name]} onChange={(e) => set(f.name, e.target.value)} style={{ flex: 1 }} />
</span>
) : (
<input
className="input"
type={f.type === 'int' || f.type === 'size' ? 'number' : 'text'}
value={editing[f.name]}
onChange={(e) => set(f.name, e.target.value)}
/>
)}
</label>
))}
<p className="dim" style={{ fontSize: '0.74rem', margin: 0 }}>
A format must hold <code>{'{Message}'}</code> exactly once; <code>{'{Title}'}</code> and <code>{'{Username}'}</code>{' '}
are where the title and name go. A hand edit in game is reported rather than overwritten.
</p>
<div style={{ display: 'flex', gap: 8 }}>
<button type="submit" className="btn" disabled={busy}>Save the style</button>
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => setEditing(null)}>Cancel</button>
</div>
</form>
)}
</>
)
}

View File

@@ -0,0 +1,328 @@
// ── Admin · Rust · Servers — chat titles and the voice (phase 17) ─────────
//
// Two things the servers page gained with BetterChat and PopupNotifications
// becoming optional (PLAN.md §33):
//
// • **A server's chat titles** (D135, D136): rules that rank the current wipe,
// in the operator's order, and how many a player shows. Saved with their own
// PUT, because they are not part of the server row — an operator retitling
// "Top Killer" must not have to re-type a sidecar address.
// • **The voice** (D140): the one styled permission group news and event lines
// are said in. A fleet setting, so it sits once at the foot of the page.
//
// Neither needs BetterChat to save. Titles are held by the plugin until BetterChat
// arrives, and the voice is said by our own plugin whether BetterChat is there or
// not; the "What this server has" line says which is which.
import { useState } from 'react'
import { ErrorState, Loading, useAsync } from '../../core.js'
import api from '../../api.js'
import { contrastInk } from '../../lib/format.js'
const MODES = [
{ id: 'first', label: 'The first title they earn', hint: 'The rule highest in the list wins.' },
{ id: 'all', label: 'Every title they earn' },
{ id: 'upto', label: 'Up to a number of titles', hint: 'In list order.' },
]
/**
* What a rule can rank (PLAN_REDESIGNS §5): the server's categories, each with
* the title it shows now (D175), then playtime, which has no title of its own.
*/
export function statOptions(categories) {
return [
...(categories || []).map((c) => ({ id: c.stat, label: c.label, title: c.current })),
{ id: 'playtime', label: 'Playtime', title: null },
// RunicNPC (runicnpc stage 4, D250): one NPC profile's kills. The rule names the profile.
{ id: 'profilekills', label: 'Kills of an NPC profile', title: null },
]
}
const statOf = (categories, id) => statOptions(categories).find((s) => s.id === id) || { id, label: id, title: null }
/** A rule's title as players see it: its own text, else its category's. */
export const ruleTitle = (rule, categories) => rule.text || statOf(categories, rule.stat).title || ''
/** One line summarising a server's titles, for its row on the list. */
export function titlesSummary(titles, push, categories) {
const rules = (titles && titles.rules) || []
if (!rules.length) return 'No chat titles.'
const list = rules.map((r) => `${ruleTitle(r, categories)} (top ${r.topN} ${statOf(categories, r.stat).label.toLowerCase()})`).join(', ')
const shown = push ? ` Last pushed: ${push.count} player${push.count === 1 ? '' : 's'} hold one${push.betterChat ? '' : ' — BetterChat is not loaded, so they are not showing in game yet'}.` : ''
return `Chat titles: ${list}.${shown}`
}
/** A title as the leaderboard will show it. */
function Chip({ text, color }) {
return (
<span
className="sans"
style={{ padding: '1px 6px', borderRadius: 999, fontSize: '0.72rem', fontWeight: 600, background: color, color: contrastInk(color) }}
>
{text || '…'}
</span>
)
}
export function TitlesForm({ server, categories, onSaved, onCancel }) {
const start = server.titles || { mode: 'first', max: 2, rules: [] }
const stats = statOptions(categories)
const { data: npc } = useAsync(() => api.servers.npcProfiles(server.id).catch(() => ({ profiles: [] })), [server.id])
const profiles = (npc && npc.profiles) || []
const [mode, setMode] = useState(start.mode)
const [max, setMax] = useState(start.max)
const [rules, setRules] = useState(start.rules.map((r) => ({ ...r })))
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const setRule = (i, key) => (e) => {
const value = e.target.value
setRules((list) => list.map((r, n) => (n === i ? { ...r, [key]: key === 'topN' || key === 'profile' ? Number(value) : value } : r)))
}
const move = (i, by) => setRules((list) => {
const next = [...list]
const [r] = next.splice(i, 1)
next.splice(i + by, 0, r)
return next
})
const save = async (e) => {
e.preventDefault()
setBusy(true)
setError('')
try {
await api.admin.saveTitles(server.id, { mode, max: Number(max), rules })
onSaved()
} catch (err) {
setError(err.message || 'That did not save.')
} finally {
setBusy(false)
}
}
return (
<form onSubmit={save} className="panel" style={{ padding: '16px 18px', display: 'grid', gap: 12, marginBottom: 18 }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>Chat titles on {server.name}</h2>
<p className="sans dim" style={{ fontSize: '0.78rem', margin: 0 }}>
Each rule gives a title to the top players on this wipe for one stat. A stat of zero earns nothing, so a fresh wipe
has no titles until somebody plays. Titles show in game chat when BetterChat is installed, and beside the name on
the leaderboard here and in the app. Up to ten rules; a title is at most 24 characters and cannot carry markup.
Leave a title blank to use the category’s title, which is set once for every server below the list.
</p>
{rules.map((r, i) => {
const fallback = statOf(categories, r.stat).title
return (
<div key={i} className="sans" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center', fontSize: '0.84rem' }}>
<span className="dim" style={{ width: 18 }}>{i + 1}</span>
<span>Top</span>
<input type="number" min={1} max={10} value={r.topN} onChange={setRule(i, 'topN')} style={{ ...inputStyle, width: 60 }} aria-label="How many players" />
<select value={r.stat} onChange={setRule(i, 'stat')} style={inputStyle} aria-label="Stat">
{stats.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
</select>
{r.stat === 'profilekills' && (
<select value={r.profile || ''} onChange={setRule(i, 'profile')} style={inputStyle} aria-label="NPC profile" required>
<option value="" disabled>{profiles.length ? 'Which NPC?' : 'No NPC profile on this server'}</option>
{profiles.map((p) => <option key={p.id} value={p.id}>{p.label} ({p.name})</option>)}
</select>
)}
<span>earn</span>
{/* The category's title is a PLACEHOLDER, never a value: saved as the rule's own text it would stop a rename reaching this rule (§5.5). */}
<input value={r.text} onChange={setRule(i, 'text')} maxLength={24} required={!fallback} placeholder={fallback || 'A title'} style={{ ...inputStyle, width: 160 }} aria-label="Title" />
<input type="color" value={r.color} onChange={setRule(i, 'color')} aria-label="Colour" style={{ width: 36, height: 28, padding: 0, border: 'none', background: 'none' }} />
<Chip text={r.text || fallback} color={r.color} />
<span style={{ marginLeft: 'auto', display: 'flex', gap: 4 }}>
<button type="button" className="btn" disabled={i === 0} onClick={() => move(i, -1)} aria-label="Move up">↑</button>
<button type="button" className="btn" disabled={i === rules.length - 1} onClick={() => move(i, 1)} aria-label="Move down">↓</button>
<button type="button" className="btn" onClick={() => setRules((list) => list.filter((_, n) => n !== i))}>Remove</button>
</span>
</div>
)
})}
{rules.length < 10 && (
<div>
<button type="button" className="btn" onClick={() => setRules((list) => [...list, { stat: 'kills', topN: 1, text: '', color: '#ffaa55' }])}>
Add a rule
</button>
</div>
)}
<div className="sans" style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center', fontSize: '0.84rem' }}>
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
A player shows
<select value={mode} onChange={(e) => setMode(e.target.value)} style={inputStyle}>
{MODES.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</select>
</label>
{mode === 'upto' && (
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
at most
<input type="number" min={1} max={5} value={max} onChange={(e) => setMax(e.target.value)} style={{ ...inputStyle, width: 60 }} />
</label>
)}
<span className="dim" style={{ fontSize: '0.74rem' }}>{(MODES.find((m) => m.id === mode) || {}).hint || ''}</span>
</div>
<div className="sans" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<button type="submit" className="btn" disabled={busy}>{busy ? 'Saving…' : 'Save titles'}</button>
<button type="button" className="btn" onClick={onCancel} disabled={busy}>Cancel</button>
{error && <span style={{ color: '#d08a2a', fontSize: '0.8rem' }}>{error}</span>}
</div>
</form>
)
}
/**
* The category titles (D175): one title per category for the whole site, which
* every rule of that category without its own text shows. Each row saves on its
* own, and Reset brings the module's default back.
*/
export function CategoryTitles({ categories, onSaved }) {
const [drafts, setDrafts] = useState({})
const [busy, setBusy] = useState('')
const [errors, setErrors] = useState({})
if (!categories || !categories.length) return null
const save = async (stat, text) => {
setBusy(stat)
setErrors((e) => ({ ...e, [stat]: '' }))
try {
await api.admin.saveTitleCategory(stat, text)
setDrafts((d) => {
const next = { ...d }
delete next[stat]
return next
})
onSaved()
} catch (err) {
setErrors((e) => ({ ...e, [stat]: err.message || 'That did not save.' }))
} finally {
setBusy('')
}
}
return (
<section className="panel sans" style={{ padding: '16px 18px', marginBottom: 18, fontSize: '0.84rem' }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: '0 0 6px', color: 'var(--head)' }}>Category titles</h2>
<p className="dim" style={{ fontSize: '0.78rem', margin: '0 0 10px' }}>
The title each category gives, on every server. A rule that has its own title keeps it; every other rule of the
category shows this one from the next push. Reset brings back the default.
</p>
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(140px, 1fr) minmax(110px, auto) minmax(160px, 1.2fr) auto', gap: '6px 10px', alignItems: 'center' }}>
<span className="dim" style={{ fontSize: '0.74rem' }}>Category</span>
<span className="dim" style={{ fontSize: '0.74rem' }}>Default</span>
<span className="dim" style={{ fontSize: '0.74rem' }}>This site’s title</span>
<span />
{categories.map((c) => {
const draft = drafts[c.stat]
const value = draft !== undefined ? draft : c.text || ''
const changed = draft !== undefined && draft !== (c.text || '')
return (
<Row key={c.stat}>
<span>{c.label}</span>
<span className="dim">{c.default}</span>
<span style={{ display: 'grid', gap: 2 }}>
<input
value={value}
placeholder={c.default}
maxLength={24}
onChange={(e) => setDrafts((d) => ({ ...d, [c.stat]: e.target.value }))}
style={inputStyle}
aria-label={`${c.label} title`}
/>
{errors[c.stat] && <span style={{ color: '#d08a2a', fontSize: '0.74rem' }}>{errors[c.stat]}</span>}
</span>
<span style={{ display: 'flex', gap: 4 }}>
<button type="button" className="btn" disabled={!changed || busy === c.stat} onClick={() => save(c.stat, value)}>Save</button>
<button type="button" className="btn" disabled={!c.text || busy === c.stat} onClick={() => save(c.stat, '')}>Reset</button>
</span>
</Row>
)
})}
</div>
</section>
)
}
/** A grid row's cells, without a wrapper element the grid would lay out as one cell. */
function Row({ children }) {
return <>{children}</>
}
/** What a server says it has loaded, as one sentence (§33.2 `integrations`). */
export function integrationsLine(r) {
if (!r || !r.integrations) {
return r && r.ok === false
? `The game could not be asked (${r.status}).`
: 'This server’s plugin is older than protocol 12, so it cannot say which optional mods it has.'
}
const one = (name, x, without) => (x && x.loaded ? `${name} ${x.version || ''} is loaded`.trim() : `${name} is not loaded — ${without}`)
return `${one('BetterChat', r.integrations.betterChat, 'titles and group styles wait for it')}. ${one('PopupNotifications', r.integrations.popupNotifications, 'a popup is refused, and chat still works')}.`
}
export function VoiceCard() {
const [reloads, setReloads] = useState(0)
const { data, error: loadError } = useAsync(() => api.admin.voice(), [reloads])
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
if (loadError) return <ErrorState error={loadError} />
if (!data) return <Loading />
const choose = async (group) => {
setBusy(true)
setError('')
try {
await api.admin.saveVoice(group)
setReloads((n) => n + 1)
} catch (err) {
setError(err.message || 'That did not save.')
} finally {
setBusy(false)
}
}
const current = data.options.find((o) => o.group === data.voice)
return (
<section className="panel sans" style={{ padding: '16px 18px', marginBottom: 18, fontSize: '0.84rem' }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: '0 0 6px', color: 'var(--head)' }}>Announcement voice</h2>
<p className="dim" style={{ fontSize: '0.78rem', margin: '0 0 10px' }}>
News posts and event announcements said in game chat can wear the title and colours of one permission group that
has a chat style. The line has no sender, so no player’s name appears. It works whether or not BetterChat is
installed. Popups are plain text.
</p>
<label style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
Say them as
<select value={data.voice} onChange={(e) => choose(e.target.value)} disabled={busy} style={inputStyle}>
<option value="">Plain chat</option>
{data.options.map((o) => (
<option key={o.group} value={o.group}>{o.name} — {o.title} ({o.where})</option>
))}
</select>
</label>
{data.voice && !current && (
<p style={{ color: '#d08a2a', fontSize: '0.78rem', margin: '8px 0 0' }}>
The chosen group no longer has a chat style, so lines are said in plain chat until it has one again or another
voice is chosen.
</p>
)}
{current && <p className="dim" style={{ fontSize: '0.74rem', margin: '8px 0 0' }}>The line: <code>{current.format}</code></p>}
{!data.options.length && (
<p className="dim" style={{ fontSize: '0.76rem', margin: '8px 0 0' }}>No group has a chat style yet. Give one a style under Permissions.</p>
)}
{error && <p style={{ color: '#d08a2a', fontSize: '0.8rem', margin: '8px 0 0' }}>{error}</p>}
</section>
)
}
const inputStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input, 6px)',
padding: '5px 8px',
fontSize: '0.84rem',
}

View File

@@ -0,0 +1,641 @@
// ── Admin · Rust · Mod configuration ──────────────────────────────────────
//
// R18. An admin picks a server, a plugin and a file, changes something, and the
// plugin reloads. This module's second admin page, and the first that writes to
// somebody's filesystem.
//
// **What is on the screen is decided by what is dangerous about the action.**
// Four things are true here that are not true anywhere else in this module, and
// each of them is a piece of the page rather than a line in a doc:
//
// • a save can take a required plugin DOWN. So the reload target is a
// deliberate choice with the folder name as a guess, the result is reported
// as its own panel, and a rollback shows the server's own log line.
// • the form cannot express everything a config holds. A `null`, an empty
// array and anything past the depth limit are marked and sent to the raw
// tier rather than half-drawn.
// • three keys in the bridge's own config would cut the link carrying the
// edit, or split the server's history. They render read-only, with the
// reason (D38).
// • configs hold API keys and Discord webhooks. Those fields render masked
// with a reveal, which is about the shoulder rather than the wire: an admin
// can already read the file over SSH (D37), and the audit trail never
// records the values either way.
import { useCallback, useEffect, useState } from 'react'
import { ErrorState, Loading, useAsync } from '../../core.js'
import { ago } from '../../lib/format.js'
import api from '../../api.js'
function Card({ title, subtitle, children, actions }) {
return (
<section className="panel" style={{ padding: '16px 18px', marginBottom: 18 }}>
<header style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>
{title}
</h2>
{subtitle && (
<span className="sans dim" style={{ fontSize: '0.76rem' }}>
{subtitle}
</span>
)}
<span style={{ flex: 1 }} />
{actions}
</header>
{children}
</section>
)
}
function Warn({ children, tone = '#d08a2a' }) {
return (
<p className="sans" style={{ color: tone, fontSize: '0.78rem', margin: '6px 0 0' }}>
{children}
</p>
)
}
/** A value the form can edit: one row, typed by what the file already holds. */
function Field({ field, value, onChange, revealed, onReveal }) {
const indent = 12 * Math.max(0, field.depth - 1)
const label = (
<label
className="sans"
style={{
flex: '0 0 300px',
paddingLeft: indent,
color: field.locked ? 'var(--ink)' : 'var(--head)',
fontSize: '0.84rem',
wordBreak: 'break-word',
}}
title={field.path}
>
{field.key}
{field.locked && (
<span className="dim" style={{ fontSize: '0.72rem' }}>
{' '}
· read-only
</span>
)}
</label>
)
if (field.type === 'object' || field.type === 'array') {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0 2px' }}>
<span
className="sans"
style={{ paddingLeft: indent, color: 'var(--head)', fontSize: '0.86rem', fontWeight: 500 }}
>
{field.key || '(the file)'}
</span>
<span className="sans dim" style={{ fontSize: '0.72rem' }}>
{field.type === 'array' ? `${field.count} entries` : `${field.count} settings`}
{field.advanced && field.reason ? ` · ${field.reason}` : ''}
</span>
</div>
)
}
if (field.advanced) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0' }}>
{label}
<span className="sans dim" style={{ fontSize: '0.78rem' }}>
{field.reason} — edit it in Raw JSON
</span>
</div>
)
}
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0' }}>
{label}
{field.type === 'boolean' ? (
<input
type="checkbox"
checked={Boolean(value)}
disabled={field.locked}
onChange={(event) => onChange(field, event.target.checked)}
/>
) : (
<input
className="input"
style={{ flex: 1, minWidth: 0 }}
type={field.secret && !revealed ? 'password' : 'text'}
value={value === undefined || value === null ? '' : String(value)}
disabled={field.locked}
onChange={(event) => onChange(field, event.target.value)}
/>
)}
{field.secret && !field.locked && (
<button type="button" className="btn btn-ghost" onClick={() => onReveal(field.path)}>
{revealed ? 'Hide' : 'Show'}
</button>
)}
</div>
)
}
/** How often a save that is still reloading asks how it went. */
const POLL_MS = 2000
/**
* A settled write row as the report panel reads it.
*
* The row is this module's audit record, not the plugin's frame, so it carries
* no per-file `rewritten` — the file is re-read after either way, which is what
* the panel's note about rewriting was for.
*/
function reportFromWrite(write) {
return {
pending: write.outcome === 'reloading',
lost: write.outcome === 'lost',
reload: write.reloadTarget,
reloaded: Boolean(write.reloaded),
rolledBack: write.outcome === 'rolled-back',
restored: write.restored,
reason: write.detail,
log: write.log,
files: [],
}
}
/** The sentence at the top of the panel. */
function headline(report) {
if (report.pending) {
return `Saved. Reloading ${report.reload || 'the plugin'}… a first compile after a quiet spell can take a while.`
}
if (report.lost) {
return 'The server never said how the reload went — the bridge may have been reloaded, or the link dropped. Re-read the file to see what is on disk.'
}
if (report.rolledBack) {
return report.restored === false
? 'The plugin did not come back, so the old file was put back — and it did not come back on the old file either. It is down: check the server console.'
: 'The plugin did not come back, so the old file was put back automatically.'
}
return report.reloaded ? 'Saved, and the plugin reloaded.' : `Saved. ${report.reason || 'Nothing was reloaded.'}`
}
/** What the game said happened. The rollback case is the one worth reading. */
function Report({ report }) {
if (!report) return null
const tone = report.rolledBack || report.lost ? '#e05a5a' : 'var(--ink)'
return (
<div style={{ borderTop: '1px solid var(--line-soft)', paddingTop: 10, marginTop: 10 }}>
<p className="sans" style={{ color: tone, fontSize: '0.84rem', margin: 0 }}>
{headline(report)}
</p>
{report.rolledBack && report.reason && (
<p className="sans dim" style={{ fontSize: '0.78rem', margin: '4px 0 0' }}>
{report.reason}
</p>
)}
{report.log && (
<pre
className="sans"
style={{
background: 'var(--line-soft)',
padding: 10,
marginTop: 8,
fontSize: '0.74rem',
maxHeight: 200,
overflow: 'auto',
whiteSpace: 'pre-wrap',
}}
>
{report.log}
</pre>
)}
{report.files.some((f) => f.rewritten) && (
<Warn>
The plugin rewrote the file as it loaded — both frameworks add any settings a config is
missing and save it back, so what is on disk now is not byte-for-byte what was sent.
</Warn>
)}
</div>
)
}
export default function ModConfig() {
const [serverId, setServerId] = useState('')
const [path, setPath] = useState('')
const [tier, setTier] = useState('form')
const [edits, setEdits] = useState({})
const [raw, setRaw] = useState('')
const [reload, setReload] = useState('')
const [revealed, setRevealed] = useState({})
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [report, setReport] = useState(null)
const [fileNonce, setFileNonce] = useState(0)
// The write a save left reloading, polled until it settles (protocol 13, D179).
const [watching, setWatching] = useState(null)
const { data: servers, error: serverError } = useAsync(() => api.admin.listServers(), [])
// The tree is asked for per server and never cached across one: what is on a
// host's disk has no stale answer worth showing, and a plugin loaded a minute
// ago has to be able to appear.
const { data: tree, error: treeError } = useAsync(
() => (serverId ? api.adminConfig.files(serverId) : Promise.resolve(null)),
[serverId],
)
const { data: file, error: fileError } = useAsync(
() => (serverId && path ? api.adminConfig.file(serverId, path) : Promise.resolve(null)),
[serverId, path, fileNonce],
)
const reset = useCallback(() => {
setEdits({})
setRevealed({})
setError('')
}, [])
// A freshly opened file starts from what the host holds: the raw editor's text
// and the reload target's guess both come from the answer rather than from
// whatever the previous file left behind.
//
// **The guess is only taken when the dropdown actually offers it.** A `<select>`
// whose value matches no `<option>` displays the first one, so a guess of
// `RunicGateway` — which is deliberately not offered, because the bridge cannot
// reload itself — put "nothing — just write the file" on the screen while the
// request carried `reload: RunicGateway`, and every save of our own config was
// refused for a reason the page had just said did not apply.
useEffect(() => {
if (!file) return
setRaw(file.text)
const offered = (tree ? tree.loaded : []).some(
(p) => p.name === file.plugin && p.name !== (tree && tree.self),
)
setReload(offered ? file.plugin : '')
reset()
}, [file, tree, reset])
useEffect(() => {
setPath('')
setReport(null)
setWatching(null)
}, [serverId])
// A save that reloads a plugin comes back before the reload has finished.
// Ask how it went every couple of seconds until the row leaves `reloading` —
// the server calls it `lost` once twice the plugin's ceiling has passed, so
// this always ends — then re-read the file, because a reload rewrites it and a
// rollback puts the old one back.
useEffect(() => {
if (!watching) return undefined
let stopped = false
let handle = null
const poll = async () => {
try {
const { write } = await api.adminConfig.write(watching.serverId, watching.id)
if (stopped) return
setReport(reportFromWrite(write))
if (write.outcome !== 'reloading') {
setWatching(null)
setFileNonce((n) => n + 1)
return
}
} catch {
// One failed poll is a blip, not an answer; the next one asks again.
if (stopped) return
}
handle = setTimeout(poll, POLL_MS)
}
handle = setTimeout(poll, POLL_MS)
return () => {
stopped = true
clearTimeout(handle)
}
}, [watching])
if (serverError) return <ErrorState error={serverError} />
if (!servers) return <Loading />
const rows = servers.servers || servers || []
const change = (field, value) => setEdits((current) => ({ ...current, [field.path]: { field, value } }))
const save = async () => {
setBusy(true)
setError('')
setReport(null)
try {
const body =
tier === 'form'
? {
path,
version: file.version,
...(reload ? { reload } : {}),
// A number goes up as the TEXT that was typed. `2.50` stays
// `2.50` and `1.0` stays `1.0`; turning either into a JavaScript
// number here is precisely the bug the server half exists to
// avoid, and it would be reintroduced in the browser.
edits: Object.values(edits).map(({ field, value }) =>
field.type === 'number'
? { pointer: field.pointer, raw: String(value) }
: { pointer: field.pointer, value },
),
}
: { path, version: file.version, ...(reload ? { reload } : {}), text: raw }
const answer = await api.adminConfig.save(serverId, body)
if (answer.pending && answer.write && answer.write.id) {
setReport({ ...(answer.report || {}), pending: true, reload: reload || null, files: [] })
setWatching({ serverId, id: answer.write.id })
} else {
setReport(answer.report || null)
}
if (!answer.changed) setError('Nothing changed, so nothing was written.')
// Re-read either way: a successful reload usually rewrites the file with
// the defaults it was missing, and a rollback means what is on disk is no
// longer what is on the screen.
setFileNonce((n) => n + 1)
} catch (err) {
setError(err.message || 'That save did not work.')
} finally {
setBusy(false)
}
}
const pending = Object.keys(edits).length
return (
<div style={{ maxWidth: 980 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
These are the configuration files on the game host itself, read live through the bridge. A
save backs the file up, writes it, reloads the plugin you name, and <strong>puts the old
file back automatically</strong> if the plugin does not come back. The game’s data
directory — kit cooldowns, zone definitions, the permission store — is not settings and is
never listed here.
</p>
<Card title="Server" subtitle={`${rows.length} configured`}>
<select className="input" value={serverId} onChange={(event) => setServerId(event.target.value)}>
<option value="">Choose a server…</option>
{rows.map((row) => (
<option key={row.id} value={row.id}>
{row.name || row.id}
</option>
))}
</select>
{tree && tree.root && (
<p className="sans dim" style={{ fontSize: '0.74rem', margin: '10px 0 0' }}>
{tree.root}
{tree.truncated ? ' · the walk stopped at its limit, so this is not the whole tree' : ''}
</p>
)}
</Card>
{serverId && treeError && <ErrorState error={treeError} />}
{serverId && !treeError && !tree && <Loading />}
{tree && (
<Card title="Files" subtitle="grouped by the plugin each one probably belongs to">
{tree.plugins.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: 0 }}>
This server reports no configuration files.
</p>
)}
{tree.plugins.map((group) => (
<div key={group.plugin} style={{ padding: '8px 0', borderTop: '1px solid var(--line-soft)' }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
<strong className="sans" style={{ fontSize: '0.88rem', fontWeight: 500 }}>
{group.title || group.plugin}
</strong>
<span className="sans dim" style={{ fontSize: '0.74rem' }}>
{group.loaded ? `loaded · ${group.version}` : 'not loaded'}
{group.isBridge ? ' · this bridge' : ''}
</span>
</div>
{group.files.map((entry) => (
<div
key={entry.path}
style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 0 4px 12px' }}
>
<button
type="button"
className={entry.path === path ? 'btn btn-primary' : 'btn btn-ghost'}
disabled={!entry.editable}
onClick={() => {
setPath(entry.path)
setReport(null)
setTier('form')
}}
>
{entry.path}
</button>
<span className="sans dim" style={{ fontSize: '0.72rem' }}>
{Math.round(entry.bytes / 102.4) / 10} KB
{entry.modified ? ` · changed ${ago(entry.modified)}` : ''}
{entry.reason ? ` · ${entry.reason}` : ''}
</span>
</div>
))}
{!group.loaded && (
<Warn>
Nothing on this server is loaded under that name, so a save here is written and
not reloaded. It applies the next time the plugin loads.
</Warn>
)}
</div>
))}
</Card>
)}
{path && fileError && <ErrorState error={fileError} />}
{path && !fileError && !file && <Loading />}
{file && (
<Card
title={file.path}
subtitle={tier === 'form' ? `${pending} unsaved` : 'raw JSON'}
actions={
<>
<button
type="button"
className={tier === 'form' ? 'btn btn-primary' : 'btn btn-ghost'}
onClick={() => setTier('form')}
>
Settings
</button>
<button
type="button"
className={tier === 'raw' ? 'btn btn-primary' : 'btn btn-ghost'}
onClick={() => setTier('raw')}
>
Raw JSON
</button>
</>
}
>
{file.parseError && (
<Warn tone="#e05a5a">
This file is not valid JSON on the server ({file.parseError}), so there is nothing to
draw a form from. Raw JSON is the tier that can fix it.
</Warn>
)}
{file.isBridge && (
<Warn>
This is the bridge’s own configuration. Its address, port and server id are read-only
here — changing any of them from the website would cut the link carrying the change,
or strand every row this site holds for this server. They are editable on the host
itself. This plugin also cannot be reloaded from here.
</Warn>
)}
{tier === 'form' && file.fields && (
<div style={{ marginTop: 6 }}>
{file.fields
.filter((field) => field.path !== '')
.map((field) => (
<Field
key={field.path}
field={field}
value={
edits[field.path]
? edits[field.path].value
: field.type === 'number'
? field.raw
: field.value
}
onChange={change}
revealed={Boolean(revealed[field.path])}
onReveal={(p) => setRevealed((current) => ({ ...current, [p]: !current[p] }))}
/>
))}
</div>
)}
{tier === 'raw' && (
<textarea
className="input"
spellCheck={false}
value={raw}
onChange={(event) => setRaw(event.target.value)}
style={{ width: '100%', minHeight: 360, fontFamily: 'monospace', fontSize: '0.8rem' }}
/>
)}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
marginTop: 12,
borderTop: '1px solid var(--line-soft)',
paddingTop: 12,
}}
>
<label className="sans dim" style={{ fontSize: '0.78rem' }}>
Reload
</label>
{/* A guess, and it says so. The folder a config sits in is convention
rather than contract, so reloading it silently is how the wrong
plugin gets reloaded, reports success, and the edited one never
re-reads anything. */}
<select className="input" value={reload} onChange={(event) => setReload(event.target.value)}>
<option value="">nothing — just write the file</option>
{(tree ? tree.loaded : [])
.filter((p) => p.name !== tree.self)
.map((p) => (
<option key={p.name} value={p.name}>
{p.name}
</option>
))}
</select>
<span style={{ flex: 1 }} />
<button
type="button"
className="btn btn-primary"
disabled={busy || Boolean(watching) || (tier === 'form' && pending === 0) || (tier === 'raw' && raw === file.text)}
onClick={save}
>
{busy ? 'Saving…' : watching ? 'Reloading…' : 'Save and reload'}
</button>
</div>
{/* Beside the button, not at the top of the page. A save is made at the
bottom of a long form, and a refusal rendered above the fold is a
click that visibly did nothing. */}
{error && (
<p className="sans" style={{ color: '#e05a5a', fontSize: '0.82rem', margin: '8px 0 0' }}>
{error}
</p>
)}
<Report report={report} />
</Card>
)}
{serverId && <History serverId={serverId} nonce={fileNonce} />}
</div>
)
}
/** Who changed what, including the saves that were refused or undone. */
function History({ serverId, nonce }) {
const { data } = useAsync(() => api.adminConfig.writes(serverId), [serverId, nonce])
if (!data || !data.writes || data.writes.length === 0) return null
return (
<Card title="Recent changes" subtitle="every save, including the ones that did not land">
{data.writes.map((row) => (
<div
key={row.id}
className="sans"
style={{ padding: '8px 0', borderTop: '1px solid var(--line-soft)', fontSize: '0.82rem' }}
>
<div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
<strong style={{ fontWeight: 500 }}>{row.path}</strong>
<span
className="sans"
style={{ fontSize: '0.74rem', color: row.outcome === 'applied' ? 'var(--ink)' : '#d08a2a' }}
>
{row.outcome}
{row.reloaded ? ' · reloaded' : ''}
</span>
<span className="sans dim" style={{ fontSize: '0.72rem' }}>
{ago(row.createdAt)}
{row.tier === 'raw' ? ' · raw' : ''}
</span>
</div>
{(row.changes || []).map((change, index) => (
<div key={`${row.id}-${index}`} className="dim" style={{ fontSize: '0.74rem' }}>
{change.path}
{change.from !== null && change.to !== null ? `: ${change.from} → ${change.to}` : ''}
</div>
))}
{row.detail && (
<div className="dim" style={{ fontSize: '0.74rem' }}>
{row.detail}
</div>
)}
</div>
))}
</Card>
)
}

View File

@@ -0,0 +1,297 @@
// ── Admin · Rust · NPC placements (docs/runicnpc/PLAN.md stage 4) ─────────
//
// One server's RunicNPC placements. They live on the server (D222) — an admin's
// `/rnpc place` in game and this page edit the same list — so every read and
// write here is a live round trip, and a server whose game is off has nothing
// to show.
//
// A new placement is made by clicking the live map (D245): the server puts the
// point on the ground, checks it against the navmesh, and names it as in game
// (D246). A roof or a building top is placed in game. Every answer that adds
// NPCs carries the cost warning (D227).
import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { ErrorState, Loading, useAsync } from '../../core.js'
import MapView from '../../components/MapView.jsx'
import api from '../../api.js'
const inputStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 6,
padding: '6px 8px',
font: 'inherit',
}
const blank = (profile = '') => ({ profile, count: '1', respawn: '300', respawnMode: 'each', move: '', radius: '', tether: '' })
function formOf(p) {
const v = p.placement || {}
return {
profile: v.profile || '',
count: String(v.count || 1),
respawn: String(v.respawn || 300),
respawnMode: v.respawnMode || 'each',
move: (v.movement && v.movement.mode) || '',
radius: v.movement && v.movement.radius !== undefined ? String(v.movement.radius) : '',
tether: v.tether || '',
}
}
function bodyOf(f) {
return {
profile: f.profile,
count: Number(f.count),
respawn: Number(f.respawn),
respawnMode: f.respawnMode,
...(f.move ? { movement: { mode: f.move, radius: f.radius === '' ? undefined : Number(f.radius) } } : { movement: null }),
// Stage 5 (D272): a ZoneManager zone its NPCs never leave; empty for none.
tether: f.tether.trim() || null,
}
}
export default function NpcPlacements() {
const { data: meta, error: metaError } = useAsync(() => api.adminNpcs.read(), [])
const ready = useMemo(() => ((meta && meta.servers) || []).filter((s) => s.ready), [meta])
const [serverId, setServerId] = useState('')
useEffect(() => {
if (!serverId && ready.length) setServerId(ready[0].id)
}, [ready, serverId])
if (metaError) return <ErrorState error={metaError} />
if (!meta) return <Loading />
const server = ready.find((s) => s.id === serverId)
const profiles = (meta.profiles || []).filter((p) => !p.replaced && (p.allServers || p.servers.includes(serverId)))
return (
<div style={{ maxWidth: 1100 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
Where RunicNPC’s NPCs stand, and come back after they die. These live on the server: <code>/rnpc place</code> in
game changes the same list. Click the map to place NPCs there; the server puts them on the ground and names the
placement. A roof or the top of a building is placed in game. Profiles are on the{' '}
<Link to="/admin/rust/npcs">NPC profiles page</Link>.
</p>
{ready.length === 0 ? (
<section className="panel sans" style={{ padding: '14px 18px', fontSize: '0.84rem' }}>
No server can take placements from the site yet: each needs RunicNPC with API 3.{' '}
{(meta.servers || []).map((s) => `${s.name || s.id}: ${s.absence}`).join(' · ')}
</section>
) : (
<>
<label className="sans" style={{ display: 'flex', gap: 8, alignItems: 'baseline', fontSize: '0.86rem', marginBottom: 12 }}>
<span style={{ color: 'var(--head)' }}>Server</span>
<select value={serverId} onChange={(e) => setServerId(e.target.value)} style={inputStyle}>
{ready.map((s) => <option key={s.id} value={s.id}>{s.name || s.id}</option>)}
</select>
</label>
{server && <ServerPlacements key={server.id} server={server} profiles={profiles} />}
</>
)}
</div>
)
}
function ServerPlacements({ server, profiles }) {
const [reloads, setReloads] = useState(0)
const { data, error: loadError } = useAsync(() => api.adminNpcs.placements(server.id), [server.id, reloads])
const [picked, setPicked] = useState(null)
const [form, setForm] = useState(blank(profiles[0] ? profiles[0].name : ''))
const [editing, setEditing] = useState(null)
const [renaming, setRenaming] = useState(null)
const [confirming, setConfirming] = useState(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [notice, setNotice] = useState('')
const act = async (fn, done) => {
setBusy(true)
setError('')
setNotice('')
try {
const out = await fn()
setNotice(done(out))
setReloads((n) => n + 1)
return true
} catch (err) {
setError(err.message || 'That did not work.')
return false
} finally {
setBusy(false)
}
}
const placements = (data && data.placements) || []
const pins = useMemo(() => {
const out = placements
.filter((p) => p.placement && p.placement.position)
.map((p) => ({
x: p.placement.position.x,
z: p.placement.position.z,
label: `${p.id} · ${p.placement.count} × ${p.placement.profile}${p.waiting ? ` · waits: ${p.waiting}` : ''}`,
colour: p.waiting ? '#9e9e9e' : '#ffd54f',
}))
if (picked) out.push({ x: picked.x, z: picked.z, label: 'New placement', colour: '#00e5ff', ring: true })
return out
}, [placements, picked])
const place = async (e) => {
e.preventDefault()
const ok = await act(
() => api.adminNpcs.place(server.id, { ...bodyOf(form), position: { x: picked.x, z: picked.z } }),
(r) => `Placed ${r.id}${r.position ? ` at ${Math.round(r.position.x)}, ${Math.round(r.position.z)} (${Math.round(r.position.y)} m up)` : ''}.${r.built ? ' It is on something players built: if that is destroyed, its NPCs stand on the nearest navmesh.' : ''} ${r.cost || ''}`,
)
if (ok) setPicked(null)
}
return (
<div style={{ display: 'grid', gap: 16 }}>
{notice && <p className="sans" style={{ fontSize: '0.84rem', color: 'var(--head)', margin: 0 }}>{notice}</p>}
{error && <p className="sans" style={{ color: 'var(--danger, #d98b84)', fontSize: '0.84rem', margin: 0 }}>{error}</p>}
<MapView serverId={server.id} online={server.online !== false} onPick={(at) => { setError(''); setPicked(at) }} pins={pins} />
{picked && (
<form onSubmit={place} className="panel sans" style={{ padding: '14px 18px', display: 'grid', gap: 10, fontSize: '0.84rem' }}>
<strong style={{ color: 'var(--head)' }}>
New placement at {picked.x}, {picked.z}{picked.grid ? ` (${picked.grid})` : ''}
</strong>
{profiles.length === 0 ? (
<span className="dim">No NPC profile is on this server yet.</span>
) : (
<PlacementFields form={form} setForm={setForm} profiles={profiles} routes={(data && data.routes) || []} />
)}
<div style={{ display: 'flex', gap: 8 }}>
<button type="submit" className="btn" disabled={busy || profiles.length === 0}>{busy ? 'Placing…' : 'Place'}</button>
<button type="button" className="btn" disabled={busy} onClick={() => setPicked(null)}>Cancel</button>
</div>
</form>
)}
<section className="panel sans" style={{ padding: '14px 18px', fontSize: '0.84rem' }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: 0, color: 'var(--head)' }}>Placements</h2>
<button type="button" className="btn" style={{ marginLeft: 'auto' }} disabled={busy} onClick={() => setReloads((n) => n + 1)}>Refresh</button>
</div>
{loadError && <p style={{ color: 'var(--danger, #d98b84)' }}>{loadError.message}</p>}
{!data && !loadError && <Loading />}
{data && data.cost && <p className="dim" style={{ fontSize: '0.78rem' }}>{data.cost}</p>}
{data && placements.length === 0 && <p className="dim">None on this server.</p>}
{placements.map((p) => {
const v = p.placement || {}
const move = v.movement ? `${v.movement.mode}${v.movement.mode === 'wander' ? ` ${v.movement.radius} m` : ''}` : 'the profile’s movement'
return (
<div key={p.id} style={{ borderTop: '1px solid var(--line-soft)', padding: '8px 0' }}>
<div style={{ display: 'flex', gap: 10, alignItems: 'baseline', flexWrap: 'wrap' }}>
<strong style={{ color: 'var(--head)' }}>{p.id}</strong>
<span className="dim">
{v.count} × {v.profile} · {p.alive} alive · respawn {v.respawn} s, {v.respawnMode} · {move}
{v.tether ? ` · inside zone ${v.tether}` : ''}
{v.position ? ` · ${Math.round(v.position.x)}, ${Math.round(v.position.z)}` : ''}
</span>
<span style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
<button type="button" className="btn" disabled={busy} onClick={() => { setEditing(editing === p.id ? null : p.id); setForm(formOf(p)) }}>Edit</button>
<button type="button" className="btn" disabled={busy} onClick={() => setRenaming(renaming && renaming.id === p.id ? null : { id: p.id, to: p.id })}>Rename</button>
<button type="button" className="btn" disabled={busy} onClick={() => act(() => api.adminNpcs.respawnPlacement(server.id, p.id), (r) => `Respawning ${r.respawned} NPC(s) of ${p.id}.`)}>Respawn</button>
{confirming === p.id ? (
<button type="button" className="btn" disabled={busy} onClick={() => { setConfirming(null); act(() => api.adminNpcs.removePlacement(server.id, p.id), () => `Removed ${p.id} and its NPCs.`) }}>
Confirm remove
</button>
) : (
<button type="button" className="btn" disabled={busy} onClick={() => setConfirming(p.id)}>Remove</button>
)}
</span>
</div>
{p.waiting && <div style={{ color: 'var(--danger, #d98b84)' }}>Waits: {p.waiting}</div>}
{p.note && <div className="dim">{p.note}</div>}
{p.lastError && <div className="dim">Last spawn failed: {p.lastError}</div>}
{renaming && renaming.id === p.id && (
<form
onSubmit={(e) => { e.preventDefault(); act(() => api.adminNpcs.renamePlacement(server.id, p.id, renaming.to), () => `Renamed ${p.id} to ${renaming.to}.`).then((ok) => ok && setRenaming(null)) }}
style={{ display: 'flex', gap: 8, marginTop: 6 }}
>
<input value={renaming.to} onChange={(e) => setRenaming({ ...renaming, to: e.target.value })} pattern="[a-z0-9_\-]{1,40}" style={{ ...inputStyle, maxWidth: 240 }} />
<button type="submit" className="btn" disabled={busy}>Rename</button>
</form>
)}
{editing === p.id && (
<form
onSubmit={(e) => { e.preventDefault(); act(() => api.adminNpcs.setPlacement(server.id, p.id, bodyOf(form)), (r) => `Changed ${p.id}. ${r.cost || ''}`).then((ok) => ok && setEditing(null)) }}
style={{ display: 'grid', gap: 8, marginTop: 6 }}
>
<PlacementFields form={form} setForm={setForm} profiles={profiles} routes={(data && data.routes) || []} />
<div style={{ display: 'flex', gap: 8 }}>
<button type="submit" className="btn" disabled={busy}>Save</button>
<button type="button" className="btn" disabled={busy} onClick={() => setEditing(null)}>Cancel</button>
</div>
</form>
)}
</div>
)
})}
</section>
</div>
)
}
/** `/rnpc place`'s options (D242, D246): profile, count, respawn, each or group, movement and radius. */
function PlacementFields({ form, setForm, profiles, routes }) {
const set = (key) => (e) => setForm((f) => ({ ...f, [key]: e.target.value }))
const profile = profiles.find((p) => p.name === form.profile)
const sentry = profile && profile.body.role === 'sentry'
const label = { display: 'grid', gap: 4 }
return (
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'end' }}>
<label style={label}>
<span style={{ color: 'var(--head)' }}>Profile</span>
<select value={form.profile} onChange={set('profile')} style={inputStyle} required>
{!profile && <option value={form.profile}>{form.profile || 'Pick one'}</option>}
{profiles.map((p) => <option key={p.id} value={p.name}>{p.label} ({p.name})</option>)}
</select>
</label>
<label style={label}>
<span style={{ color: 'var(--head)' }}>How many</span>
<input value={form.count} onChange={set('count')} inputMode="numeric" style={{ ...inputStyle, maxWidth: 70 }} />
</label>
<label style={label}>
<span style={{ color: 'var(--head)' }}>Respawn (s)</span>
<input value={form.respawn} onChange={set('respawn')} inputMode="numeric" style={{ ...inputStyle, maxWidth: 90 }} />
</label>
<label style={label}>
<span style={{ color: 'var(--head)' }}>Come back</span>
<select value={form.respawnMode} onChange={set('respawnMode')} style={inputStyle}>
<option value="each">each, after its own death</option>
<option value="group">together, once all are dead</option>
</select>
</label>
{!sentry && (
<>
<label style={label}>
<span style={{ color: 'var(--head)' }}>Movement</span>
<select value={form.move} onChange={set('move')} style={inputStyle}>
<option value="">the profile’s own</option>
<option value="wander">wander</option>
<option value="monument">monument</option>
{routes.map((r) => <option key={r} value={`route:${r}`}>route: {r}</option>)}
</select>
</label>
{form.move === 'wander' && (
<label style={label}>
<span style={{ color: 'var(--head)' }}>Radius (m)</span>
<input value={form.radius} onChange={set('radius')} inputMode="decimal" style={{ ...inputStyle, maxWidth: 80 }} />
</label>
)}
<label style={label} title="A ZoneManager zone on this server its NPCs never leave. The server refuses a zone it does not have, or one that does not hold the spot.">
<span style={{ color: 'var(--head)' }}>Keep inside zone</span>
<input value={form.tether} onChange={set('tether')} placeholder="none" maxLength={64} style={{ ...inputStyle, maxWidth: 160 }} />
</label>
</>
)}
</div>
)
}

View File

@@ -0,0 +1,537 @@
// ── Admin · Rust · NPC profiles (docs/runicnpc/PLAN.md stage 4) ──────────
//
// Where RunicNPC's profiles are authored (D216: no in-game editor). A profile is
// for one server, several, or every server, like a zone preset, and the site
// pushes each server its set, which RunicNPC then holds as managed (D221).
//
// The first push to a server adopts that server's own profiles as profiles for
// it alone (D244); one whose name a site profile already had there is kept
// aside as "replaced" (D251), listed below with a Restore. Each profile says how
// its kills are counted on the leaderboard and in titles (D247).
//
// Stage 5: a profile's side (its faction, its own exceptions, its alert radius),
// turrets, the two PVE checkboxes and the kit's extras; and the site's one
// faction table, pushed to every server with the profiles (D254, D268).
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { ErrorState, Loading, useAsync } from '../../core.js'
import api from '../../api.js'
const inputStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 6,
padding: '6px 8px',
font: 'inherit',
}
const SCOPE_WORDS = {
server: 'Kills of this name on the server a leaderboard is for (the default)',
name: 'Kills of this name on every server',
profile: 'Kills of this profile only, on whichever servers it is pushed to',
}
const TURRET_WORDS = {
default: 'As Rust’s scientists: player turrets shoot it, Outpost and Bandit Camp sentries do not',
ignore: 'No turret shoots it',
always: 'Every turret shoots it, Outpost’s and Bandit Camp’s sentries too',
}
const KIT_WORDS = {
heal: 'Heals with syringes, medkits or bandages in a lull',
grenades: 'Throws grenades at 5 to 20 m',
melee: 'Switches to a melee weapon up close',
rockets: 'Fires rockets at 15 to 80 m',
flamethrower: 'Switches to a flamethrower within 7 m',
}
/** A profile's own exceptions as lines of `faction: relation`, and back. */
const relationsText = (r) => Object.entries(r || {}).map(([k, v]) => `${k}: ${v}`).join('\n')
function relationsFrom(text) {
const out = {}
for (const line of String(text || '').split('\n')) {
const at = line.lastIndexOf(':')
if (at <= 0) continue
const key = line.slice(0, at).trim()
const value = line.slice(at + 1).trim()
if (key && value) out[key] = value
}
return out
}
const list = (text) => String(text || '').split(/[\n,]+/).map((s) => s.trim()).filter(Boolean)
const str = (v) => (v === undefined || v === null ? '' : String(v))
function formFrom(p, defaults) {
const b = { ...defaults, ...(p ? p.body : {}) }
return {
id: p ? p.id : null,
name: p ? p.name : '',
allServers: p ? p.allServers : false,
servers: p ? [...p.servers] : [],
killsScope: p ? p.killsScope : 'server',
names: (b.names || []).join('\n'),
kits: (b.kits || []).join(', '),
prefab: b.prefab,
role: b.role,
moveMode: (b.movement && b.movement.mode) || 'wander',
moveRadius: str(b.movement && b.movement.radius),
health: str(b.health),
damageDealt: str(b.damageDealt),
head: str(b.damageTaken && b.damageTaken.head),
body: str(b.damageTaken && b.damageTaken.body),
legs: str(b.damageTaken && b.damageTaken.legs),
aimCone: str(b.aimCone),
sense: str(b.ranges && b.ranges.sense),
loseTarget: str(b.ranges && b.ranges.loseTarget),
chase: str(b.ranges && b.ranges.chase),
attack: str(b.ranges && b.ranges.attack),
visionCone: str(b.visionCone),
sleepDistance: str(b.sleepDistance),
thresholds: (b.healthThresholds || []).map((t) => Math.round(t * 100)).join(', '),
faction: str(b.faction),
relations: relationsText(b.relations),
alertRadius: str(b.alertRadius),
turrets: b.turrets || 'default',
hurtByPlayers: b.hurtByPlayers !== false,
hurtsPlayers: b.hurtsPlayers !== false,
kitUse: { ...(defaults.kitUse || {}), ...(b.kitUse || {}) },
}
}
/** What the page sends: numbers as typed (the server checks them, as RunicNPC would). */
function bodyFrom(f) {
return {
name: f.name.trim(),
allServers: f.allServers,
servers: f.allServers ? [] : f.servers,
killsScope: f.killsScope,
body: {
names: list(f.names),
kits: list(f.kits),
prefab: f.prefab,
role: f.role,
movement: { mode: f.moveMode.trim(), radius: f.moveRadius },
health: f.health,
damageDealt: f.damageDealt,
damageTaken: { head: f.head, body: f.body, legs: f.legs },
aimCone: f.aimCone,
ranges: { sense: f.sense, loseTarget: f.loseTarget, chase: f.chase, attack: f.attack },
visionCone: f.visionCone,
sleepDistance: f.sleepDistance,
healthThresholds: list(f.thresholds).map((t) => Number(t) / 100),
faction: f.faction.trim() || null,
relations: relationsFrom(f.relations),
alertRadius: f.alertRadius,
turrets: f.turrets,
hurtByPlayers: f.hurtByPlayers,
hurtsPlayers: f.hurtsPlayers,
kitUse: f.kitUse,
},
}
}
/** One line on a server's RunicNPC and the last push to it. */
function serverLine(s) {
if (!s.ready) return s.absence || 'no RunicNPC'
const parts = [`RunicNPC ${s.runicNpc.version || ''} · API ${s.runicNpc.api}`.replace(' ', ' ')]
const sync = s.sync
if (!sync || !sync.adoptedAt) parts.push('not pushed yet: its own profiles are adopted first')
else if (sync.state === 'ok') parts.push(`pushed ${new Date(sync.syncedAt).toLocaleString()}`)
else if (sync.state === 'failed') parts.push(`the last push failed: ${sync.error || 'no reason given'}`)
return parts.join(' · ')
}
export default function NpcProfiles() {
const [reloads, setReloads] = useState(0)
const { data, error: loadError } = useAsync(() => api.adminNpcs.read(), [reloads])
const [form, setForm] = useState(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [notice, setNotice] = useState('')
if (loadError) return <ErrorState error={loadError} />
if (!data) return <Loading />
const servers = data.servers || []
const nameOf = new Map(servers.map((s) => [s.id, s.name || s.id]))
const inUse = (data.profiles || []).filter((p) => !p.replaced)
const replaced = (data.profiles || []).filter((p) => p.replaced)
const act = async (fn, done) => {
setBusy(true)
setError('')
setNotice('')
try {
const out = await fn()
if (done) setNotice(done(out))
setForm(null)
setReloads((n) => n + 1)
} catch (err) {
setError(err.message || 'That did not work.')
} finally {
setBusy(false)
}
}
const save = (e) => {
e.preventDefault()
act(() => (form.id ? api.adminNpcs.update(form.id, bodyFrom(form)) : api.adminNpcs.create(bodyFrom(form))), () => 'Saved. It reaches each server on the next push, within half a minute.')
}
const push = (s) =>
act(
() => api.adminNpcs.push(s.id),
(r) => {
if (r.outcome === 'pushed') {
const refused = Object.entries(r.refused || {})
const adopted = (r.adopted || []).map((a) => `${a.name} (${a.outcome})`)
return `${nameOf.get(s.id)}: pushed ${r.profiles.length} profile(s)${adopted.length ? `; adopted ${adopted.join(', ')}` : ''}${refused.length ? `; RunicNPC refused ${refused.map(([n, why]) => `${n}: ${why}`).join('; ')}` : ''}.`
}
if (r.outcome === 'current') return `${nameOf.get(s.id)} already has the current set.`
return `${nameOf.get(s.id)}: ${r.outcome}${r.reason ? `, ${r.reason}` : ''}${r.error ? `, ${r.error}` : ''}.`
},
)
return (
<div style={{ maxWidth: 960 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
RunicNPC’s NPC profiles: what an NPC wears (its Kits kits), how hard it is and how it moves. Each profile is for
one server, several, or every server, and each server is pushed its set. The first push to a server adopts the
profiles it already had, so nothing on it changes. Where NPCs stand is set on the{' '}
<Link to="/admin/rust/npcs/placements">placements page</Link>, in game with <code>/rnpc place</code>, or by an
event’s <em>Place NPCs</em> step.
</p>
<section className="panel" style={{ padding: '14px 18px', marginBottom: 18 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: '0 0 8px', color: 'var(--head)' }}>Servers</h2>
{servers.length === 0 && <p className="sans dim" style={{ fontSize: '0.82rem', margin: 0 }}>No servers are configured yet.</p>}
{servers.map((s) => {
const refused = Object.entries((s.sync && s.sync.refused) || {})
return (
<div key={s.id} className="sans" style={{ fontSize: '0.8rem', padding: '5px 0', borderTop: '1px solid var(--line-soft)' }}>
<div style={{ display: 'flex', gap: 10, alignItems: 'baseline', flexWrap: 'wrap' }}>
<strong style={{ color: 'var(--head)' }}>{s.name || s.id}</strong>
<span className="dim">{serverLine(s)}</span>
{s.ready && (
<button type="button" className="btn" style={{ marginLeft: 'auto' }} disabled={busy} onClick={() => push(s)}>
Push now
</button>
)}
</div>
{refused.length > 0 && (
<div style={{ color: 'var(--danger, #d98b84)', marginTop: 2 }}>
RunicNPC refused: {refused.map(([n, why]) => `${n} (${why})`).join('; ')}
</div>
)}
</div>
)
})}
</section>
{notice && <p className="sans" style={{ fontSize: '0.84rem', color: 'var(--head)' }}>{notice}</p>}
{error && !form && <p className="sans" style={{ color: 'var(--danger, #d98b84)', fontSize: '0.84rem' }}>{error}</p>}
<section className="panel" style={{ padding: '14px 18px', marginBottom: 18 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: 0, color: 'var(--head)' }}>Profiles</h2>
<button type="button" className="btn" style={{ marginLeft: 'auto' }} onClick={() => { setError(''); setForm(formFrom(null, data.defaults)) }}>
New profile
</button>
</div>
{inUse.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: '8px 0 0' }}>None yet. A server’s own profiles appear here after its first push.</p>
)}
{inUse.map((p) => (
<div key={p.id} className="sans" style={{ borderTop: '1px solid var(--line-soft)', padding: '8px 0', fontSize: '0.84rem' }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
<strong style={{ color: 'var(--head)' }}>{p.label}</strong>
<code className="dim">{p.name}</code>
<span className="dim" style={{ fontSize: '0.76rem' }}>
{p.allServers ? 'every server' : p.servers.map((id) => nameOf.get(id) || id).join(', ')}
{p.adoptedFrom ? ` · adopted from ${nameOf.get(p.adoptedFrom) || p.adoptedFrom}` : ''}
</span>
<button type="button" className="btn" style={{ marginLeft: 'auto' }} onClick={() => { setError(''); setForm(formFrom(p, data.defaults)) }}>
Edit
</button>
</div>
<span className="dim" style={{ fontSize: '0.76rem' }}>
{p.body.role} · {p.body.health} health · kits {(p.body.kits || []).join(', ')} · {p.body.role === 'sentry' ? 'stands still' : p.body.movement && p.body.movement.mode}
{' · '}kills counted: {p.killsScope === 'server' ? 'per server' : p.killsScope === 'name' ? 'every server with this name' : 'this profile only'}
</span>
</div>
))}
</section>
<FactionTable data={data} busy={busy} act={act} />
{replaced.length > 0 && (
<section className="panel" style={{ padding: '14px 18px', marginBottom: 18 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: '0 0 6px', color: 'var(--head)' }}>Replaced</h2>
<p className="sans dim" style={{ fontSize: '0.8rem', margin: '0 0 6px' }}>
A server’s own profiles whose name a site profile already had there when the site first pushed to it. The site’s
is in use; these are kept in case you want them back.
</p>
{replaced.map((p) => (
<div key={p.id} className="sans" style={{ display: 'flex', gap: 10, alignItems: 'baseline', borderTop: '1px solid var(--line-soft)', padding: '6px 0', fontSize: '0.84rem' }}>
<code>{p.name}</code>
<span className="dim">from {nameOf.get(p.adoptedFrom) || p.adoptedFrom}</span>
<button type="button" className="btn" style={{ marginLeft: 'auto' }} disabled={busy} onClick={() => act(() => api.adminNpcs.restore(p.id), () => `${p.name} is back in use on ${nameOf.get(p.adoptedFrom) || p.adoptedFrom}.`)}>
Restore
</button>
<button type="button" className="btn" disabled={busy} onClick={() => act(() => api.adminNpcs.remove(p.id), () => `${p.name} deleted.`)}>
Delete
</button>
</div>
))}
</section>
)}
{form && (
<ProfileForm
form={form}
setForm={setForm}
data={data}
busy={busy}
error={error}
onSave={save}
onCancel={() => setForm(null)}
onDelete={form.id ? () => act(() => api.adminNpcs.remove(form.id), () => `${form.name} deleted. Its placements wait until a profile of that name returns.`) : null}
/>
)}
</div>
)
}
function Field({ label, hint, children }) {
return (
<label className="sans" style={{ display: 'grid', gap: 4, fontSize: '0.84rem' }}>
<span style={{ color: 'var(--head)' }}>{label}</span>
{children}
{hint && <span className="dim" style={{ fontSize: '0.74rem' }}>{hint}</span>}
</label>
)
}
function Num({ value, onChange, width = 110 }) {
return <input value={value} onChange={(e) => onChange(e.target.value)} inputMode="decimal" style={{ ...inputStyle, maxWidth: width }} />
}
function ProfileForm({ form, setForm, data, busy, error, onSave, onCancel, onDelete }) {
const servers = data.servers || []
const set = (key) => (value) => setForm((f) => ({ ...f, [key]: value }))
const toggleServer = (id) => setForm((f) => ({ ...f, servers: f.servers.includes(id) ? f.servers.filter((x) => x !== id) : [...f.servers, id] }))
const fieldset = { border: '1px solid var(--line-soft)', borderRadius: 8, padding: '10px 14px', display: 'grid', gap: 10 }
const legend = { color: 'var(--head)', fontSize: '0.86rem', padding: '0 6px' }
const row = { display: 'flex', gap: 14, flexWrap: 'wrap' }
return (
<form onSubmit={onSave} className="panel" style={{ padding: '16px 18px', display: 'grid', gap: 14 }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>{form.id ? `Edit ${form.name}` : 'A new profile'}</h2>
<Field label="Name" hint="RunicNPC’s name for it: 1 to 40 of a-z, 0-9, _ and -. It is what /rnpc place and an event step name.">
<input value={form.name} onChange={(e) => set('name')(e.target.value)} required maxLength={40} pattern="[a-z0-9_\-]{1,40}" style={{ ...inputStyle, maxWidth: 320 }} />
</Field>
<fieldset style={fieldset}>
<legend className="sans" style={legend}>For</legend>
<label className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.allServers} onChange={(e) => set('allServers')(e.target.checked)} />
Every server, including servers added later
</label>
{!form.allServers &&
servers.map((s) => (
<label key={s.id} className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.servers.includes(s.id)} onChange={() => toggleServer(s.id)} />
{s.name || s.id}
{!s.ready && <span className="dim">({s.absence})</span>}
</label>
))}
</fieldset>
<fieldset style={fieldset}>
<legend className="sans" style={legend}>Looks</legend>
<Field label="NPC names" hint="One per line. Each NPC is given one of these; the first is the profile’s name on the leaderboard.">
<textarea value={form.names} onChange={(e) => set('names')(e.target.value)} rows={3} style={{ ...inputStyle, maxWidth: 360 }} />
</Field>
<Field label="Kits" hint="Kits kits, separated by commas. One is picked for each NPC. Every server the profile is for must have each one.">
<input value={form.kits} onChange={(e) => set('kits')(e.target.value)} style={{ ...inputStyle, maxWidth: 480 }} />
</Field>
<div style={row}>
<Field label="Prefab">
<select value={form.prefab} onChange={(e) => set('prefab')(e.target.value)} style={inputStyle}>
{[...new Set([form.prefab, ...(data.prefabs || [])])].map((p) => <option key={p} value={p}>{p}</option>)}
</select>
</Field>
<Field label="Role">
<select value={form.role} onChange={(e) => set('role')(e.target.value)} style={inputStyle}>
<option value="roamer">Roamer: moves, chases and fights</option>
<option value="sentry">Sentry: stands still and shoots</option>
<option value="guard">Guard: holds its spot, chases within its leash, walks back</option>
</select>
</Field>
</div>
</fieldset>
{form.role !== 'sentry' && (
<fieldset style={fieldset}>
<legend className="sans" style={legend}>Moving</legend>
<div style={row}>
{form.role === 'roamer' && (
<>
<Field label="How it moves" hint="wander, monument (Rust’s own paths there), or route:<name> for a route recorded in game. A placement may change it.">
<input value={form.moveMode} onChange={(e) => set('moveMode')(e.target.value)} list="rnpc-modes" style={{ ...inputStyle, maxWidth: 220 }} />
<datalist id="rnpc-modes"><option value="wander" /><option value="monument" /></datalist>
</Field>
<Field label="Wander radius (m)"><Num value={form.moveRadius} onChange={set('moveRadius')} /></Field>
</>
)}
<Field label="Sleeps with nobody within (m)" hint="0: never sleeps."><Num value={form.sleepDistance} onChange={set('sleepDistance')} /></Field>
</div>
</fieldset>
)}
<fieldset style={fieldset}>
<legend className="sans" style={legend}>Fighting</legend>
<div style={row}>
<Field label="Health"><Num value={form.health} onChange={set('health')} /></Field>
<Field label="Damage dealt ×" hint="1 is the weapon’s own."><Num value={form.damageDealt} onChange={set('damageDealt')} /></Field>
<Field label="Aim spread" hint="Rust’s scientists: 2."><Num value={form.aimCone} onChange={set('aimCone')} /></Field>
<Field label="Vision cone" hint="−1 to 1."><Num value={form.visionCone} onChange={set('visionCone')} /></Field>
</div>
<div style={row}>
<Field label="Damage taken × head"><Num value={form.head} onChange={set('head')} /></Field>
<Field label="× body"><Num value={form.body} onChange={set('body')} /></Field>
<Field label="× legs"><Num value={form.legs} onChange={set('legs')} /></Field>
</div>
<div style={row}>
<Field label="Notices players at (m)"><Num value={form.sense} onChange={set('sense')} /></Field>
<Field label="Forgets them at (m)"><Num value={form.loseTarget} onChange={set('loseTarget')} /></Field>
<Field label="Chases up to (m from home)" hint="0: no limit."><Num value={form.chase} onChange={set('chase')} /></Field>
<Field label="Shoots from (m)"><Num value={form.attack} onChange={set('attack')} /></Field>
</div>
<Field label="Health thresholds (%)" hint="An event phase can wait for these: 50 raises “below 50%” once. Separated by commas.">
<input value={form.thresholds} onChange={(e) => set('thresholds')(e.target.value)} style={{ ...inputStyle, maxWidth: 220 }} />
</Field>
</fieldset>
<fieldset style={fieldset}>
<legend className="sans" style={legend}>Sides</legend>
<p className="sans dim" style={{ fontSize: '0.76rem', margin: 0 }}>
With none of this set, it fights players only. Fighting Rust’s scientists, animals or other profiles is opted
into here or in the faction table, and costs about what fighting players does. It never walks into a monument
to look for scientists: it fights only what comes within its chase range of its spot.
</p>
<div style={row}>
<Field label="Faction" hint="Profiles of one faction are allies. Empty: its allies are its own profile’s NPCs.">
<input value={form.faction} onChange={(e) => set('faction')(e.target.value)} list="rnpc-factions" maxLength={40} style={{ ...inputStyle, maxWidth: 220 }} />
<datalist id="rnpc-factions">{(data.factionNames || []).map((n) => <option key={n} value={n} />)}</datalist>
</Field>
<Field label="Alert radius (m)" hint="Allies this close join a fight one of them is in, seen or not. 0: off.">
<Num value={form.alertRadius} onChange={set('alertRadius')} />
</Field>
</div>
<Field label="Its own exceptions" hint="One per line, winning over the faction table: scientists: hostile, animals: hostile, bandits: allied, profile:warden: hostile.">
<textarea value={form.relations} onChange={(e) => set('relations')(e.target.value)} rows={3} style={{ ...inputStyle, maxWidth: 420 }} />
</Field>
<Field label="Turrets">
<select value={form.turrets} onChange={(e) => set('turrets')(e.target.value)} style={{ ...inputStyle, maxWidth: 560 }}>
{(data.turrets || ['default', 'ignore', 'always']).map((t) => <option key={t} value={t}>{TURRET_WORDS[t] || t}</option>)}
</select>
</Field>
<label className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.hurtByPlayers} onChange={(e) => set('hurtByPlayers')(e.target.checked)} />
Players can hurt it <span className="dim">(off: it cannot be killed by players, on any server)</span>
</label>
<label className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.hurtsPlayers} onChange={(e) => set('hurtsPlayers')(e.target.checked)} />
It can hurt players <span className="dim">(off: it still fights NPCs and turrets)</span>
</label>
</fieldset>
<fieldset style={fieldset}>
<legend className="sans" style={legend}>The kit’s extras</legend>
<p className="sans dim" style={{ fontSize: '0.76rem', margin: 0 }}>
The kit’s main weapon is always used, and never runs out. Each extra is used only if ticked, and comes out of
the NPC’s inventory, so its loot is what is left.
</p>
{(data.kitUses || Object.keys(KIT_WORDS)).map((k) => (
<label key={k} className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={Boolean(form.kitUse[k])} onChange={(e) => setForm((f) => ({ ...f, kitUse: { ...f.kitUse, [k]: e.target.checked } }))} />
{KIT_WORDS[k] || k}
</label>
))}
</fieldset>
<Field label="Kills count" hint="How the leaderboard and chat titles count this profile’s kills.">
<select value={form.killsScope} onChange={(e) => set('killsScope')(e.target.value)} style={{ ...inputStyle, maxWidth: 520 }}>
{(data.killsScopes || ['server', 'name', 'profile']).map((s) => <option key={s} value={s}>{SCOPE_WORDS[s] || s}</option>)}
</select>
</Field>
{error && <p className="sans" style={{ color: 'var(--danger, #d98b84)', fontSize: '0.84rem', margin: 0 }}>{error}</p>}
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button type="submit" className="btn" disabled={busy}>{busy ? 'Saving…' : 'Save'}</button>
<button type="button" className="btn" onClick={onCancel} disabled={busy}>Cancel</button>
{onDelete && (
<button type="button" className="btn" style={{ marginLeft: 'auto' }} onClick={onDelete} disabled={busy}>Delete profile</button>
)}
</div>
</form>
)
}
/**
* The site's faction table (stage 5, D254): one row per pair, both ways (D268).
* A pair not listed is neutral; Rust's scientists and animals are the two
* built-in factions. Pushed to every server with its profiles.
*/
function FactionTable({ data, busy, act }) {
const [rows, setRows] = useState(null)
const shown = rows || (data.factions || []).map((f) => ({ ...f }))
const names = [...new Set([...(data.factionNames || []), ...(data.builtInFactions || ['scientists', 'animals'])])]
const change = (i, key, value) => setRows(shown.map((r, j) => (j === i ? { ...r, [key]: value } : r)))
const save = () =>
act(
() => api.adminNpcs.setFactions(shown.filter((r) => r.a && r.b)),
(out) => {
setRows(null)
return `Faction table saved: ${out.factions.length} pair(s). It reaches each server on the next push.`
},
)
return (
<section className="panel" style={{ padding: '14px 18px', marginBottom: 18 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: '0 0 6px', color: 'var(--head)' }}>Faction table</h2>
<p className="sans dim" style={{ fontSize: '0.8rem', margin: '0 0 8px' }}>
How factions treat each other. One row is both ways: <em>bandits ↔ guards: hostile</em> makes each hunt the other.
A pair that is not here is neutral, and a faction is always allied to itself. <em>scientists</em> and{' '}
<em>animals</em> are Rust’s own; a profile hostile to scientists fights them, and they only take cover.
</p>
<datalist id="rnpc-table-factions">{names.map((n) => <option key={n} value={n} />)}</datalist>
{shown.length === 0 && <p className="sans dim" style={{ fontSize: '0.8rem', margin: '0 0 8px' }}>Empty: every pair is neutral.</p>}
{shown.map((r, i) => (
<div key={i} className="sans" style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '4px 0', fontSize: '0.84rem' }}>
<input value={r.a} onChange={(e) => change(i, 'a', e.target.value)} list="rnpc-table-factions" maxLength={40} style={{ ...inputStyle, maxWidth: 180 }} />
<span className="dim">↔</span>
<input value={r.b} onChange={(e) => change(i, 'b', e.target.value)} list="rnpc-table-factions" maxLength={40} style={{ ...inputStyle, maxWidth: 180 }} />
<select value={r.relation} onChange={(e) => change(i, 'relation', e.target.value)} style={inputStyle}>
<option value="hostile">hostile</option>
<option value="neutral">neutral</option>
<option value="allied">allied</option>
</select>
<button type="button" className="btn" onClick={() => setRows(shown.filter((_, j) => j !== i))} disabled={busy}>Remove</button>
</div>
))}
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<button type="button" className="btn" onClick={() => setRows([...shown, { a: '', b: '', relation: 'hostile' }])} disabled={busy}>Add a pair</button>
<button type="button" className="btn" onClick={save} disabled={busy || rows === null}>Save the table</button>
{rows !== null && <button type="button" className="btn" onClick={() => setRows(null)} disabled={busy}>Discard changes</button>}
</div>
</section>
)
}

View File

@@ -0,0 +1,796 @@
// ── Admin · Rust · Permissions ────────────────────────────────────────────
//
// The permission manager (PLAN_REDESIGNS §1). The site owns every permission and
// group on every server (D160), and this screen follows uMod PermissionsManager's
// flow (D162): a server, then players ⇄ groups, then a subject, then one plugin's
// permissions with Granted / Revoked, Grant all and Revoke all.
//
// Three rules shape it:
//
// • **Every toggle says what is true on THIS server** (U-1): granted,
// waiting for a sync, through a group, waiting for a first connection, not
// registered here, or did not land. A state in a server-level sentence is a
// state nobody reads.
// • **Plugins are who REGISTERED a permission, never its prefix.**
// `zonemanager.ignoreflag.nokits` is ZoneManager's.
// • **Anything that reaches further than this server says so and asks.** A
// fleet-wide grant is revoked everywhere or only here; a shared group is
// changed everywhere or split for this server (D190's two answers, offered
// to a person).
//
// Every subject is named by linked account and in-game name, or by Steam id
// when there is neither (D163). The screen never writes to a game: every button
// writes to the site, and the sync loop settles it within seconds — except
// *Sync now*.
import { useCallback, useEffect, useMemo, useState } from 'react'
import { ErrorState, Loading, useAsync } from '../../core.js'
import { ago } from '../../lib/format.js'
import api from '../../api.js'
import Tabs from '../../components/Tabs.jsx'
import ChatStyleSection from './ChatStyle.jsx'
const POLICY_TEXT = {
'auto-adopt': 'A change made in the game becomes the site’s own, for that server.',
adopt: 'A change made in the game waits here for a person to adopt or undo it.',
revoke: 'A change made in the game is undone at the next sync.',
}
// ── Furniture ────────────────────────────────────────────────────────────
function Card({ title, subtitle, children, actions }) {
return (
<section className="panel" style={{ padding: '16px 18px', marginBottom: 18 }}>
<header style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>{title}</h2>
{subtitle && <span className="sans dim" style={{ fontSize: '0.76rem' }}>{subtitle}</span>}
<span style={{ flex: 1 }} />
{actions}
</header>
{children}
</section>
)
}
function Row({ children, onClick, selected = false }) {
return (
<div
className="sans"
onClick={onClick}
role={onClick ? 'button' : undefined}
tabIndex={onClick ? 0 : undefined}
onKeyDown={onClick ? (e) => (e.key === 'Enter' ? onClick() : null) : undefined}
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
padding: '7px 8px',
borderTop: '1px solid var(--line-soft)',
fontSize: '0.85rem',
color: 'var(--head)',
cursor: onClick ? 'pointer' : undefined,
background: selected ? 'var(--blue)' : undefined,
borderRadius: selected ? 6 : undefined,
}}
>
{children}
</div>
)
}
const TONES = {
good: { color: '#5bb85b', border: '#3d7a3d' },
warn: { color: '#d08a2a', border: '#8a5c1c' },
bad: { color: '#e05a5a', border: '#8a3434' },
info: { color: 'var(--muted)', border: 'var(--line)' },
}
function Chip({ tone = 'info', children, title }) {
const t = TONES[tone]
return (
<span
title={title}
className="sans"
style={{ fontSize: '0.7rem', padding: '1px 8px', borderRadius: 999, border: `1px solid ${t.border}`, color: t.color, whiteSpace: 'nowrap' }}
>
{children}
</span>
)
}
function Warn({ children }) {
return <p className="sans" style={{ color: '#d08a2a', fontSize: '0.78rem', margin: '6px 0 0' }}>{children}</p>
}
/** Granted / Revoked, as two buttons. */
function Toggle({ on, disabled, onChange }) {
const style = (active) => ({
padding: '2px 10px',
fontSize: '0.74rem',
cursor: disabled ? 'default' : 'pointer',
border: `1px solid ${active ? 'var(--accent)' : 'var(--line)'}`,
background: active ? 'var(--blue)' : 'transparent',
color: active ? 'var(--accent-bright)' : 'var(--muted)',
})
return (
<span style={{ display: 'inline-flex' }}>
<button type="button" disabled={disabled} onClick={() => !on && onChange(true)} style={{ ...style(on), borderRadius: '999px 0 0 999px' }}>Granted</button>
<button type="button" disabled={disabled} onClick={() => on && onChange(false)} style={{ ...style(!on), borderRadius: '0 999px 999px 0' }}>Revoked</button>
</span>
)
}
/** A subject's name, as D163 has it: account and in-game name, or the Steam id. */
function SubjectName({ player }) {
const primary = player.name || player.steamId
return (
<span style={{ display: 'inline-flex', flexDirection: 'column' }}>
<span>{primary}</span>
<span className="dim" style={{ fontSize: '0.72rem' }}>
{player.account ? `site account ${player.account.username}` : 'not linked'}
{player.name ? ` · ${player.steamId}` : ''}
</span>
</span>
)
}
/** The plugin buttons: who registered each permission (§0.1). */
function PluginPicker({ plugins, active, onSelect, countFor }) {
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, margin: '6px 0 12px' }}>
{plugins.map((p) => {
const n = countFor ? countFor(p) : 0
const selected = p.key === active
return (
<button
key={p.key}
type="button"
onClick={() => onSelect(p.key)}
className="sans"
title={p.registered ? `Registered by ${p.label}` : `Not registered by a plugin — grouped by the prefix “${p.label}”`}
style={{
padding: '4px 10px',
fontSize: '0.78rem',
borderRadius: 999,
cursor: 'pointer',
border: `1px solid ${selected ? 'var(--accent)' : 'var(--line)'}`,
background: selected ? 'var(--blue)' : 'transparent',
color: selected ? 'var(--accent-bright)' : p.registered ? 'var(--head)' : 'var(--muted)',
}}
>
{p.label}{p.registered ? '' : ' *'}{n ? ` · ${n}` : ''}
</button>
)
})}
</div>
)
}
// ── The facts behind every toggle (U-1) ──────────────────────────────────
function useFacts(view) {
return useMemo(() => {
const landed = new Set(view.landed || [])
const report = view.report || { unresolved: [], pending: [], notLanded: [] }
const unresolved = new Set(report.unresolved.map((p) => String(p).toLowerCase()))
const pending = new Set(report.pending)
const notLanded = new Set(report.notLanded.map((p) => String(p).toLowerCase()))
const groupsByName = new Map(view.groups.map((g) => [g.name, g]))
const registered = new Set(view.plugins.flatMap((p) => p.permissions))
return { landed, unresolved, pending, notLanded, groupsByName, registered }
}, [view])
}
/** One player's state for one permission on this server. */
function playerState(facts, view, player, permission) {
const direct = player.grants.find((g) => g.permission === permission)
const viaGroups = player.groups.filter((name) => (facts.groupsByName.get(name) || { permissions: [] }).permissions.includes(permission))
const excepted = (view.excepted || []).find((e) => e.steamId === player.steamId && e.permission === permission)
if (direct) {
const wider = direct.sources.some((s) => (s.type === 'userGrant' || s.type === 'steamGrant') && s.scope !== view.server.id)
const fromEvent = direct.sources.every((s) => s.type === 'runGrant')
let chip
if (!facts.registered.has(permission)) chip = <Chip tone="bad" title="No loaded plugin registers it here">not registered here</Chip>
else if (facts.notLanded.has(`${player.steamId}:${permission}`)) chip = <Chip tone="bad">did not land</Chip>
else if (facts.landed.has(`grant ${player.steamId} ${permission}`)) chip = <Chip tone="good">granted</Chip>
else chip = <Chip tone="warn">waiting for a sync</Chip>
return { on: true, chip, wider, fromEvent, excepted: null, viaGroups }
}
if (viaGroups.length) {
return { on: true, readOnly: true, chip: <Chip tone="info">through {viaGroups.join(', ')}</Chip>, viaGroups }
}
if (excepted) {
return { on: false, excepted, chip: <Chip tone="warn" title="Granted on every other server">revoked here only</Chip> }
}
return { on: false, chip: null }
}
// ── A player (D162: a subject, its plugins, its groups) ──────────────────
function PlayerPanel({ view, player, act, busy }) {
const facts = useFacts(view)
const [tab, setTab] = useState('permissions')
const [plugin, setPlugin] = useState(view.plugins[0] ? view.plugins[0].key : null)
const [everywhere, setEverywhere] = useState(false)
const [asking, setAsking] = useState(null)
const [addGroup, setAddGroup] = useState('')
const serverId = view.server.id
const subject = { steamId: player.steamId }
const chosen = view.plugins.find((p) => p.key === plugin)
const held = (p) => p.permissions.filter((perm) => playerState(facts, view, player, perm).on).length
const toggle = (permission, on) => {
const state = playerState(facts, view, player, permission)
if (on) {
if (state.excepted) return act(() => api.adminPermissions.removeException(state.excepted.id))
return act(() => api.adminPermissions.grant(serverId, subject, [permission], everywhere))
}
// A grant that reaches further than this server: ask (D190's two answers).
if (state.wider) return setAsking({ permissions: [permission] })
return act(() => api.adminPermissions.revoke(serverId, subject, [permission]))
}
const bulk = (on) => {
if (!chosen) return
const perms = chosen.permissions.filter((perm) => {
const s = playerState(facts, view, player, perm)
return on ? !s.on : s.on && !s.readOnly
})
if (!perms.length) return
if (on) return act(() => api.adminPermissions.grant(serverId, subject, perms, everywhere))
if (perms.some((perm) => playerState(facts, view, player, perm).wider)) return setAsking({ permissions: perms })
return act(() => api.adminPermissions.revoke(serverId, subject, perms))
}
const groupIds = new Map(view.groups.map((g) => [g.name, g.id]))
return (
<Card
title={<SubjectName player={player} />}
subtitle={`${player.grants.length} direct · ${player.groups.length} group${player.groups.length === 1 ? '' : 's'}`}
>
<Tabs
tabs={[{ id: 'permissions', label: 'Permissions' }, { id: 'groups', label: 'Groups' }]}
active={tab}
onSelect={setTab}
label="Player"
/>
{tab === 'permissions' && (
<>
<label className="sans dim" style={{ fontSize: '0.78rem', display: 'flex', gap: 6, alignItems: 'center' }}>
<input type="checkbox" checked={everywhere} onChange={(e) => setEverywhere(e.target.checked)} />
Grant on every server, not just {view.server.name}
</label>
<PluginPicker plugins={view.plugins} active={plugin} onSelect={setPlugin} countFor={held} />
{asking && (
<div className="panel sans" style={{ padding: '10px 12px', marginBottom: 10, fontSize: '0.82rem' }}>
{asking.permissions.length === 1 ? <code>{asking.permissions[0]}</code> : `${asking.permissions.length} of these`} reach
{' '}further than {view.server.name}. Revoke:
<span style={{ display: 'inline-flex', gap: 6, marginLeft: 8 }}>
<button type="button" className="btn" disabled={busy} onClick={() => { const p = asking.permissions; setAsking(null); act(() => api.adminPermissions.revoke(serverId, subject, p, true)) }}>Everywhere</button>
<button type="button" className="btn" disabled={busy} onClick={() => { const p = asking.permissions; setAsking(null); act(() => api.adminPermissions.revoke(serverId, subject, p, false)) }}>Only on {view.server.name}</button>
<button type="button" className="btn btn-ghost" onClick={() => setAsking(null)}>Cancel</button>
</span>
</div>
)}
{chosen && (
<>
<div style={{ display: 'flex', gap: 8, marginBottom: 6 }}>
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => bulk(true)}>Grant all</button>
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => bulk(false)}>Revoke all</button>
</div>
{chosen.permissions.map((perm) => {
const s = playerState(facts, view, player, perm)
return (
<Row key={perm}>
<code style={{ flex: 1, fontSize: '0.8rem' }}>{perm}</code>
{s.fromEvent && <Chip tone="info" title="An event gave it; the event’s revert takes it back">from an event</Chip>}
{s.chip}
<Toggle on={s.on} disabled={busy || s.readOnly || s.fromEvent} onChange={(on) => toggle(perm, on)} />
</Row>
)
})}
</>
)}
{!view.plugins.length && <p className="sans dim">This server has not reported its plugins yet. Sync it once.</p>}
</>
)}
{tab === 'groups' && (
<>
{player.groups.length === 0 && <p className="sans dim" style={{ fontSize: '0.82rem' }}>In no group on {view.server.name} (every player is in <code>default</code>).</p>}
{player.groups.map((name) => {
const waiting = facts.pending.has(`${player.steamId}:${name}`)
const landed = facts.landed.has(`member ${player.steamId} ${name}`)
return (
<Row key={name}>
<span style={{ flex: 1 }}>{name}</span>
{waiting ? <Chip tone="warn" title="The server has never seen this player">waiting for their first connection</Chip>
: landed ? <Chip tone="good">in the group</Chip> : <Chip tone="warn">waiting for a sync</Chip>}
<button type="button" className="btn btn-ghost" disabled={busy || !groupIds.has(name)} onClick={() => act(() => api.adminPermissions.removeMember(groupIds.get(name), subject))}>Remove</button>
</Row>
)
})}
<div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
<select className="input" value={addGroup} onChange={(e) => setAddGroup(e.target.value)}>
<option value="">Add to a group…</option>
{view.groups.filter((g) => g.name !== 'default' && !player.groups.includes(g.name)).map((g) => (
<option key={g.id} value={g.id}>{g.name}{g.title && g.title !== g.name ? ` — ${g.title}` : ''}</option>
))}
</select>
<button type="button" className="btn" disabled={busy || !addGroup} onClick={() => { const id = addGroup; setAddGroup(''); act(() => api.adminPermissions.addMember(Number(id), subject)) }}>Add</button>
{player.groups.length > 0 && (
<button
type="button"
className="btn btn-ghost"
disabled={busy}
onClick={() => act(async () => {
for (const name of player.groups) {
if (groupIds.has(name)) await api.adminPermissions.removeMember(groupIds.get(name), subject)
}
})}
>
Remove from all
</button>
)}
</div>
</>
)}
</Card>
)
}
// ── A group (D189, D190) ─────────────────────────────────────────────────
function GroupPanel({ view, group, act, busy, chatFields }) {
const facts = useFacts(view)
const [tab, setTab] = useState('permissions')
const [plugin, setPlugin] = useState(view.plugins[0] ? view.plugins[0].key : null)
const [scope, setScope] = useState('everywhere')
const [attrs, setAttrs] = useState({ title: group.title, rank: group.rank, parent: group.parent })
const [member, setMember] = useState('')
const [share, setShare] = useState({ allServers: group.allServers, servers: group.servers })
const [conflict, setConflict] = useState(null)
useEffect(() => {
setAttrs({ title: group.title, rank: group.rank, parent: group.parent })
setShare({ allServers: group.allServers, servers: group.servers })
setConflict(null)
}, [group])
const serverId = view.server.id
const here = group.shared && scope === 'here' ? { onlyHere: true, serverId } : null
const chosen = view.plugins.find((p) => p.key === plugin)
const carried = new Set(group.permissions)
const setPermissions = (next) => act(() => api.adminPermissions.setGroupPermissions(group.id, [...next].sort(), here))
const toggle = (perm, on) => {
const next = new Set(carried)
if (on) next.add(perm)
else next.delete(perm)
return setPermissions(next)
}
const bulk = (on) => {
if (!chosen) return
const next = new Set(carried)
for (const perm of chosen.permissions) on ? next.add(perm) : next.delete(perm)
return setPermissions(next)
}
const saveShare = async (replace = []) => {
const body = share.allServers ? { allServers: true, replace } : { allServers: false, servers: share.servers, replace }
try {
await act(() => api.adminPermissions.setGroupServers(group.id, body), { rethrow: true })
setConflict(null)
} catch (err) {
if (err && err.status === 409 && err.body && err.body.conflicts) setConflict(err.body)
}
}
const permState = (perm) => {
if (!facts.registered.has(perm)) return <Chip tone="bad">not registered here</Chip>
if (!carried.has(perm)) return null
if (facts.landed.has(`group-permission ${group.name} ${perm}`)) return <Chip tone="good">carried</Chip>
return <Chip tone="warn">waiting for a sync</Chip>
}
const members = [
...group.members.map((m) => ({ key: `u${m.userId}`, label: m.username, detail: m.steamIds.length ? m.steamIds.join(', ') : 'no Steam account linked — reaches nobody yet', subject: { userId: m.userId } })),
...group.steamMembers.map((steamId) => {
const p = view.players.find((x) => x.steamId === steamId)
return { key: `s${steamId}`, label: (p && p.name) || steamId, detail: p && p.account ? `site account ${p.account.username}` : steamId, subject: { steamId } }
}),
]
return (
<Card
title={group.title || group.name}
subtitle={<>{group.name}{group.builtin ? ' · built in' : ''} · {group.allServers ? 'every server' : group.servers.join(', ')}{group.source && group.source !== 'admin' ? ` · ${group.source}` : ''}</>}
actions={!group.builtin && (
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.deleteGroup(group.id))}>Delete</button>
)}
>
{group.shared && (
<div className="sans" style={{ fontSize: '0.8rem', marginBottom: 10, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<Chip tone="warn">shared</Chip>
<span className="dim">A change here applies</span>
<label><input type="radio" checked={scope === 'everywhere'} onChange={() => setScope('everywhere')} /> everywhere it is</label>
<label><input type="radio" checked={scope === 'here'} onChange={() => setScope('here')} /> only on {view.server.name} (gives it its own copy)</label>
</div>
)}
<Tabs
tabs={[
{ id: 'permissions', label: 'Permissions' },
{ id: 'members', label: `Players (${members.length})` },
{ id: 'settings', label: 'Settings' },
{ id: 'servers', label: 'Servers' },
]}
active={tab}
onSelect={setTab}
label="Group"
/>
{tab === 'permissions' && (
<>
<PluginPicker plugins={view.plugins} active={plugin} onSelect={setPlugin} countFor={(p) => p.permissions.filter((x) => carried.has(x)).length} />
{chosen && (
<>
<div style={{ display: 'flex', gap: 8, marginBottom: 6 }}>
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => bulk(true)}>Grant all</button>
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => bulk(false)}>Revoke all</button>
</div>
{chosen.permissions.map((perm) => (
<Row key={perm}>
<code style={{ flex: 1, fontSize: '0.8rem' }}>{perm}</code>
{permState(perm)}
<Toggle on={carried.has(perm)} disabled={busy} onChange={(on) => toggle(perm, on)} />
</Row>
))}
</>
)}
{group.permissions.filter((p) => !facts.registered.has(p)).length > 0 && (
<Warn>
It also carries {group.permissions.filter((p) => !facts.registered.has(p)).join(', ')}, which no plugin on this server registers now.
They land when that plugin loads.
</Warn>
)}
</>
)}
{tab === 'members' && (
<>
{group.name === 'default' && <p className="sans dim" style={{ fontSize: '0.82rem' }}>Every player who connects is in <code>default</code>; it is not listed.</p>}
{members.map((m) => (
<Row key={m.key}>
<span style={{ flex: 1, display: 'inline-flex', flexDirection: 'column' }}>
<span>{m.label}</span>
<span className="dim" style={{ fontSize: '0.72rem' }}>{m.detail}</span>
</span>
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.removeMember(group.id, m.subject, here))}>Remove</button>
</Row>
))}
<div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
<input className="input" placeholder="Steam id or site account name" value={member} onChange={(e) => setMember(e.target.value)} />
<button
type="button"
className="btn"
disabled={busy || !member.trim()}
onClick={() => {
const v = member.trim()
setMember('')
act(() => api.adminPermissions.addMember(group.id, /^\d{5,20}$/.test(v) ? { steamId: v } : { username: v }, here))
}}
>
Add
</button>
{members.length > 0 && (
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.clearMembers(group.id, here))}>Remove all</button>
)}
</div>
</>
)}
{tab === 'settings' && (
<>
<form
className="sans"
onSubmit={(e) => { e.preventDefault(); act(() => api.adminPermissions.updateGroup(group.id, attrs, here)) }}
style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 8, fontSize: '0.82rem' }}
>
<label>Title<input className="input" value={attrs.title} onChange={(e) => setAttrs({ ...attrs, title: e.target.value })} /></label>
<label>Rank<input className="input" type="number" value={attrs.rank} onChange={(e) => setAttrs({ ...attrs, rank: Number(e.target.value) })} /></label>
<label>
Parent
<select className="input" value={attrs.parent} onChange={(e) => setAttrs({ ...attrs, parent: e.target.value })}>
<option value="">None</option>
{view.groups.filter((g) => g.name !== group.name).map((g) => <option key={g.id} value={g.name}>{g.name}</option>)}
</select>
</label>
<span style={{ alignSelf: 'end' }}><button type="submit" className="btn" disabled={busy}>Save</button></span>
</form>
<ChatStyleSection
group={group}
fields={chatFields}
servers={view.sync ? [{ serverId: view.server.id, report: view.sync.report }] : []}
busy={busy}
onSave={async (chat) => {
try {
await act(() => api.adminPermissions.updateGroup(group.id, { chat }, here), { rethrow: true })
return true
} catch {
return false
}
}}
/>
</>
)}
{tab === 'servers' && (
<div className="sans" style={{ fontSize: '0.82rem' }}>
<p className="dim" style={{ margin: '0 0 8px' }}>
A group belongs to one server unless it is shared (D189). A shared group carries the same permissions and players on every server
it is on; a change made in one game gives that server its own copy.
</p>
<label style={{ display: 'block', marginBottom: 6 }}>
<input type="checkbox" checked={share.allServers} onChange={(e) => setShare({ ...share, allServers: e.target.checked })} /> On every server, including servers added later
</label>
{!share.allServers && view.servers.map((s) => (
<label key={s.id} style={{ display: 'block' }}>
<input
type="checkbox"
checked={share.servers.includes(s.id)}
onChange={(e) => setShare({ ...share, servers: e.target.checked ? [...share.servers, s.id] : share.servers.filter((x) => x !== s.id) })}
/> {s.name}
</label>
))}
<button type="button" className="btn" style={{ marginTop: 8 }} disabled={busy} onClick={() => saveShare()}>Save</button>
{conflict && (
<div className="panel" style={{ padding: '10px 12px', marginTop: 10 }}>
<p style={{ margin: '0 0 6px' }}>{conflict.message}</p>
<p className="dim" style={{ margin: '0 0 6px' }}>This group carries: {(conflict.group.permissions || []).join(', ') || 'nothing'}</p>
{conflict.conflicts.map((c) => (
<p key={c.id} style={{ margin: '0 0 4px' }}>
The group on {c.servers.join(', ')} carries: {c.permissions.join(', ') || 'nothing'}
</p>
))}
<button type="button" className="btn" disabled={busy} onClick={() => saveShare(conflict.conflicts.map((c) => c.id))}>
Replace them with this group
</button>{' '}
<button type="button" className="btn btn-ghost" onClick={() => setConflict(null)}>Cancel</button>
</div>
)}
</div>
)}
</Card>
)
}
// ── What waits for a person (D161) ───────────────────────────────────────
const DIRECTION_TEXT = {
added: 'added in the game',
removed: 'removed in the game',
changed: 'changed in the game',
split: 'split off',
}
function DriftList({ rows, act, busy }) {
if (!rows.length) return null
return (
<Card title="Waiting for a person" subtitle={`${rows.length}`}>
{rows.map((d) => {
const who = d.username ? `${d.playerName || d.subject} (${d.username})` : d.playerName || d.subject
const what = d.kind === 'grant' ? <>{who} holds <code>{d.object}</code></>
: d.kind === 'member' ? <>{who} is in <code>{d.object}</code></>
: d.kind === 'group-permission' ? <>group <code>{d.subject}</code> carries <code>{d.object}</code></>
: d.kind === 'chat-field' ? <>group <code>{d.subject}</code>’s {d.object} is <code>{d.detail}</code></>
: <>group <code>{d.subject}</code></>
return (
<Row key={d.id}>
<span style={{ flex: 1 }}>
{what} — <span className="dim">{DIRECTION_TEXT[d.direction] || d.direction}{d.detail === 'event' ? ' (an event gave it, so it was put back)' : ''}</span>
{d.direction === 'split' && d.detail && <span className="dim" style={{ display: 'block', fontSize: '0.74rem' }}>{d.detail}</span>}
</span>
{(d.direction === 'added' || d.direction === 'changed' || d.kind === 'chat-field') && d.detail !== 'event' && (
<button type="button" className="btn" disabled={busy} onClick={() => act(() => api.adminPermissions.adoptDrift(d.id))}>Adopt</button>
)}
{(d.direction === 'added' || d.kind === 'chat-field') && (
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.revokeDrift(d.id))}>Undo</button>
)}
{d.direction === 'removed' && d.detail !== 'event' && (
<button type="button" className="btn" disabled={busy} onClick={() => act(() => api.adminPermissions.acceptDrift(d.id))}>Accept</button>
)}
{(d.direction === 'removed' || d.direction === 'changed') && d.kind !== 'chat-field' && d.detail !== 'event' && (
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.restoreDrift(d.id))}>Put back</button>
)}
{(d.direction === 'split' || d.detail === 'event') && (
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.dismissDrift(d.id))}>Dismiss</button>
)}
</Row>
)
})}
</Card>
)
}
// ── One server ───────────────────────────────────────────────────────────
function ServerPanel({ serverId, chatFields, reloads, act, busy }) {
const { data: view, error } = useAsync(() => api.adminPermissions.server(serverId), [serverId, reloads])
const [tab, setTab] = useState('players')
const [selected, setSelected] = useState(null)
const [filter, setFilter] = useState('')
const [found, setFound] = useState([])
const [newGroup, setNewGroup] = useState('')
useEffect(() => { setSelected(null); setFilter(''); setFound([]) }, [serverId])
if (error) return <ErrorState error={error} />
if (!view) return <Loading />
const f = filter.trim().toLowerCase()
const players = view.players.filter((p) => !f || [p.name, p.steamId, p.account && p.account.username].some((v) => v && String(v).toLowerCase().includes(f)))
// A player found by search who holds nothing yet: shown with empty holdings.
const player = selected && selected.type === 'player'
? view.players.find((p) => p.steamId === selected.steamId) || { ...selected.found, grants: [], groups: [] }
: null
const group = selected && selected.type === 'group' ? view.groups.find((g) => g.id === selected.id) : null
return (
<>
<Tabs tabs={[{ id: 'players', label: `Players (${view.players.length})` }, { id: 'groups', label: `Groups (${view.groups.length})` }]} active={tab} onSelect={(t) => { setTab(t); setSelected(null) }} label="Permissions" />
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(220px, 300px) 1fr', gap: 18, alignItems: 'start' }}>
<div className="panel" style={{ padding: '10px 10px' }}>
{tab === 'players' && (
<>
<input
className="input"
placeholder="Find a player…"
value={filter}
onChange={(e) => setFilter(e.target.value)}
onKeyDown={async (e) => {
if (e.key !== 'Enter' || !filter.trim()) return
const res = await api.adminPermissions.players(serverId, filter.trim())
setFound(res.players || [])
}}
style={{ width: '100%', marginBottom: 6 }}
/>
<p className="sans dim" style={{ fontSize: '0.7rem', margin: '0 0 6px' }}>Enter searches every player this server has seen.</p>
{players.map((p) => (
<Row key={p.steamId} selected={player && player.steamId === p.steamId} onClick={() => setSelected({ type: 'player', steamId: p.steamId })}>
<SubjectName player={p} />
</Row>
))}
{found.filter((p) => !view.players.some((x) => x.steamId === p.steamId)).map((p) => (
<Row key={`f${p.steamId}`} onClick={() => setSelected({ type: 'player', steamId: p.steamId, found: p })}>
<SubjectName player={p} /> <Chip>holds nothing</Chip>
</Row>
))}
{!players.length && !found.length && <p className="sans dim" style={{ fontSize: '0.8rem' }}>Nobody holds anything here yet.</p>}
</>
)}
{tab === 'groups' && (
<>
{view.groups.map((g) => (
<Row key={g.id} selected={group && group.id === g.id} onClick={() => setSelected({ type: 'group', id: g.id })}>
<span style={{ flex: 1 }}>{g.name}</span>
{g.shared && <Chip tone="warn">shared</Chip>}
<span className="dim" style={{ fontSize: '0.72rem' }}>{g.permissions.length}</span>
</Row>
))}
<form
onSubmit={(e) => { e.preventDefault(); const name = newGroup.trim(); if (!name) return; setNewGroup(''); act(() => api.adminPermissions.createGroup(serverId, { name, title: name })) }}
style={{ display: 'flex', gap: 6, marginTop: 10 }}
>
<input className="input" placeholder="New group name" value={newGroup} onChange={(e) => setNewGroup(e.target.value)} style={{ flex: 1 }} />
<button type="submit" className="btn" disabled={busy || !newGroup.trim()}>Create</button>
</form>
</>
)}
</div>
<div>
{player && <PlayerPanel view={view} player={player} act={act} busy={busy} />}
{group && <GroupPanel view={view} group={group} act={act} busy={busy} chatFields={chatFields} />}
{!player && !group && (
<p className="sans dim" style={{ fontSize: '0.84rem' }}>
Choose a {tab === 'players' ? 'player' : 'group'} on the left.
</p>
)}
<DriftList rows={view.drift} act={act} busy={busy} />
</div>
</div>
</>
)
}
// ── The page ─────────────────────────────────────────────────────────────
export default function Permissions() {
const [reloads, setReloads] = useState(0)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [serverId, setServerId] = useState(null)
const { data, error: loadError } = useAsync(() => api.adminPermissions.overview(), [reloads])
const reload = useCallback(() => setReloads((n) => n + 1), [])
const act = async (fn, { rethrow = false } = {}) => {
setBusy(true)
setError('')
try {
await fn()
reload()
} catch (err) {
if (!(rethrow && err && err.status === 409)) setError(err.message || 'That did not work.')
if (rethrow) throw err
} finally {
setBusy(false)
}
}
useEffect(() => {
if (!serverId && data && data.servers.length) setServerId(data.servers[0].id)
}, [data, serverId])
if (loadError) return <ErrorState error={loadError} />
if (!data) return <Loading />
const server = data.servers.find((s) => s.id === serverId)
const sync = server && server.sync
return (
<div style={{ maxWidth: 1100 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
This site holds every permission and group on each server — what was there before it, what is made here, and
what is changed in the game. It reads each server’s store and pushes the site’s set back, so a wipe loses nothing.
</p>
{error && <p className="sans" style={{ color: '#e05a5a', fontSize: '0.84rem' }}>{error}</p>}
<div className="sans" style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', marginBottom: 14 }}>
<label style={{ fontSize: '0.84rem' }}>
Server{' '}
<select className="input" value={serverId || ''} onChange={(e) => setServerId(e.target.value)}>
{data.servers.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</label>
{server && (
<>
<label style={{ fontSize: '0.84rem' }}>
In-game changes{' '}
<select className="input" value={server.policy} disabled={busy} onChange={(e) => act(() => api.adminPermissions.setPolicy(server.id, e.target.value))}>
{data.policies.map((p) => <option key={p} value={p}>{p}</option>)}
</select>
</label>
{sync && (
sync.inSync ? <Chip tone="good">in sync{sync.lastOkAt ? ` · ${ago(sync.lastOkAt)}` : ''}</Chip>
: sync.state === 'failed' ? <Chip tone="bad" title={sync.error || ''}>last sync failed</Chip>
: <Chip tone="warn">waiting for a sync</Chip>
)}
{sync && !sync.importedAt && <Chip tone="warn" title="The first sync imports everything on the server (D198)">not imported yet</Chip>}
<button type="button" className="btn btn-ghost" disabled={busy} onClick={() => act(() => api.adminPermissions.sync(server.id))}>Sync now</button>
</>
)}
</div>
{server && <p className="sans dim" style={{ fontSize: '0.78rem', margin: '-6px 0 14px' }}>{POLICY_TEXT[server.policy]}</p>}
{sync && sync.state === 'failed' && sync.error && <Warn>{sync.error}</Warn>}
{serverId && <ServerPanel serverId={serverId} chatFields={data.chatFields} reloads={reloads} act={act} busy={busy} />}
{!data.servers.length && <p className="sans dim">No Rust servers are configured yet.</p>}
</div>
)
}

View File

@@ -0,0 +1,418 @@
// ── Admin · Rust · Servers (phase 16, D133) ───────────────────────────────
//
// The page the module did not have. Until phase 16 a server row was written only
// through `PUT /admin/rust/servers/:id` — D106 recorded it, and the README said
// "in Admin → Rust, add a server" about a page that did not exist. D130's wipe
// schedule needed somewhere to be typed, and the org lead chose to build the
// missing page rather than hang the schedule on the visibility page (D133).
//
// One form for adding and editing, because they are one `PUT`. Three rules it
// keeps from the API:
//
// 1. **The token is write-only.** The field is blank on every edit, a blank
// save leaves the stored one alone, and the row says whether one is stored.
// 2. **The protocol a row was configured against is kept.** The `PUT` defaults
// an omitted protocol to this build's, so an edit sends the stored value back
// rather than silently re-stamping the row.
// 3. **The wipe schedule is the operator's words, not the forecast.** The form
// shows what was stored; the row shows what it computes to, from the same
// answer the public pages read.
//
// Test and Delete act at once rather than on Save — they are questions put to a
// sidecar and a removal, not settings.
//
// Phase 17 added a server's chat titles and the announcement voice, in
// `ChatTitles.jsx`, each saved on its own.
import { useState } from 'react'
import { ErrorState, Loading, useAsync } from '../../core.js'
import api from '../../api.js'
import { ago, nextWipe } from '../../lib/format.js'
import { CategoryTitles, TitlesForm, VoiceCard, integrationsLine, titlesSummary } from './ChatTitles.jsx'
const RULES = [
{ id: 'none', label: 'No schedule', hint: 'Nothing is forecast, not even the monthly forced wipe.' },
{ id: 'forced', label: 'Forced wipe only', hint: 'The first Thursday of each month, 19:00 UK time — Facepunch forces it on every server.' },
{ id: 'weekly', label: 'Weekly', hint: 'Every week on the day and time below, and the forced wipe.' },
{ id: 'biweekly', label: 'Every other week', hint: 'Every second week, on the weeks the date below falls in, and the forced wipe.' },
]
const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
const SOURCE = { forced: 'the forced wipe', rule: 'its own schedule', once: 'the one-off date' }
/** The browser's own zone — the likeliest answer for an operator typing a time. */
const localZone = () => {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
} catch {
return 'UTC'
}
}
/** Every zone the browser knows, for the datalist; an older browser gets none and a free field. */
const ZONES = (() => {
try {
return typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : []
} catch {
return []
}
})()
/** An ISO instant as the value a `datetime-local` input takes, in the browser's clock. */
/**
* What the missing ZoneManager helper costs this server (PLAN_FIXES F12, D182), or
* null when there is nothing to say — the helper patched, or a plugin that
* reported no ZoneManager state at all. Scoring is never what is lost: the bridge
* falls back to the zone's shape. ZoneManager's own flags are.
*/
export function zoneHelperNote(helper) {
if (!helper || helper.state === 'patched' || helper.state === 'no-zonemanager') return null
const cost =
'Event zones still score everybody inside, but ZoneManager’s own flags and messages miss a player who was already standing in a zone when it opened or came back after a restart.'
if (helper.state === 'missing') {
return `The ZoneManager helper (RunicGatewayZones.cs) is not installed. ${cost} Reinstall or update the plugin to put it back.`
}
return `The ZoneManager helper could not patch this ZoneManager${helper.reason ? ` (${helper.reason})` : ''}. ${cost}`
}
function toLocalInput(iso) {
if (!iso) return ''
const d = new Date(iso)
if (Number.isNaN(d.getTime())) return ''
const pad = (n) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
}
function blankForm() {
return {
isNew: true,
id: '',
name: '',
sidecarBaseUrl: '',
sidecarToken: '',
enabled: true,
sortOrder: 0,
protocol: undefined,
wipeRule: 'none',
wipeDay: 4,
wipeTime: '19:00',
wipeTz: localZone(),
wipeAnchor: '',
wipeOnce: '',
}
}
function formFrom(server) {
const s = server.schedule || { rule: 'none' }
return {
isNew: false,
id: server.id,
name: server.name,
sidecarBaseUrl: server.sidecarBaseUrl,
sidecarToken: '',
enabled: server.enabled,
sortOrder: server.sortOrder,
protocol: server.protocol,
wipeRule: s.rule || 'none',
wipeDay: s.day == null ? 4 : s.day,
wipeTime: s.time || '19:00',
wipeTz: s.tz || localZone(),
wipeAnchor: s.anchor || '',
wipeOnce: toLocalInput(s.onceAt),
storedOnceAt: s.onceAt || null,
}
}
/** The PUT body. The token only when one was typed; the schedule always. */
function bodyFrom(form) {
const weekly = form.wipeRule === 'weekly' || form.wipeRule === 'biweekly'
const onceUnchanged = form.storedOnceAt && form.wipeOnce === toLocalInput(form.storedOnceAt)
const body = {
name: form.name.trim(),
sidecarBaseUrl: form.sidecarBaseUrl.trim(),
enabled: form.enabled,
sortOrder: Number(form.sortOrder) || 0,
wipeRule: form.wipeRule,
wipeDay: weekly ? Number(form.wipeDay) : null,
wipeTime: weekly ? form.wipeTime : null,
wipeTz: weekly ? form.wipeTz.trim() : null,
wipeAnchor: form.wipeRule === 'biweekly' ? form.wipeAnchor : null,
// A past one-off date that was not touched is dropped rather than sent back:
// the server refuses a past date on save (it says nothing about the next
// wipe), and an operator editing the name must not be stopped by it.
wipeOnceAt: !form.wipeOnce || (onceUnchanged && Date.parse(form.storedOnceAt) <= Date.now())
? null
: new Date(form.wipeOnce).toISOString(),
}
if (form.sidecarToken) body.sidecarToken = form.sidecarToken
if (form.protocol !== undefined) body.protocol = form.protocol
return body
}
export default function ServerSettings() {
const [reloads, setReloads] = useState(0)
const { data, error: loadError } = useAsync(() => api.admin.listServers(), [reloads])
const [form, setForm] = useState(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [notes, setNotes] = useState({})
const [confirming, setConfirming] = useState(null)
const [titling, setTitling] = useState(null)
if (loadError) return <ErrorState error={loadError} />
if (!data) return <Loading />
const servers = data.servers || []
const categories = data.titleCategories || []
const set = (key) => (e) => {
const value = e && e.target ? (e.target.type === 'checkbox' ? e.target.checked : e.target.value) : e
setForm((f) => ({ ...f, [key]: value }))
}
const save = async (e) => {
e.preventDefault()
setBusy(true)
setError('')
try {
await api.admin.saveServer(form.id.trim(), bodyFrom(form))
setForm(null)
setReloads((n) => n + 1)
} catch (err) {
setError(err.message || 'That did not save.')
} finally {
setBusy(false)
}
}
const test = async (server) => {
setNotes((n) => ({ ...n, [server.id]: 'Asking the sidecar…' }))
try {
const r = await api.admin.testServer(server.id)
const sidecar = r.sidecar || {}
const text = r.ok
? `The sidecar answered${sidecar.protocol ? ` (protocol ${sidecar.protocol})` : ''}${sidecar.plugin_connected === false ? ', but the game’s plugin is not connected to it' : ''}.`
: `The sidecar did not answer: ${r.status}.`
setNotes((n) => ({ ...n, [server.id]: text }))
} catch (err) {
setNotes((n) => ({ ...n, [server.id]: err.message || 'The test did not run.' }))
}
}
const mods = async (server) => {
setNotes((n) => ({ ...n, [server.id]: 'Asking the game…' }))
try {
const line = integrationsLine(await api.admin.integrations(server.id))
setNotes((n) => ({ ...n, [server.id]: line }))
} catch (err) {
setNotes((n) => ({ ...n, [server.id]: err.message || 'The game could not be asked.' }))
}
}
const remove = async (server) => {
setConfirming(null)
try {
await api.admin.deleteServer(server.id)
setReloads((n) => n + 1)
} catch (err) {
setNotes((n) => ({ ...n, [server.id]: err.message || 'That did not delete.' }))
}
}
return (
<div style={{ maxWidth: 900 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
Each Rust server this site follows, the sidecar it answers through, and when it wipes. A server’s sidecar is
installed on its own game host; this page tells the site where to find it.
</p>
<section className="panel" style={{ padding: '16px 18px', marginBottom: 18 }}>
{servers.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: 0 }}>No servers are configured yet.</p>
)}
{servers.map((s) => (
<div key={s.id} className="sans" style={{ borderTop: '1px solid var(--line-soft)', padding: '10px 0', fontSize: '0.84rem' }}>
<div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'baseline', gap: 10 }}>
<strong style={{ color: 'var(--head)' }}>{s.name}</strong>
<code className="dim" style={{ fontSize: '0.74rem' }}>{s.id}</code>
{!s.enabled && <span className="dim" style={{ fontSize: '0.74rem' }}>disabled</span>}
<span style={{ marginLeft: 'auto', color: s.online ? 'var(--mode-live, #5fb98a)' : 'var(--dim)' }}>
{s.online ? `online · ${s.players}${s.maxPlayers ? `/${s.maxPlayers}` : ''}` : s.reachable ? 'sidecar up, game offline' : 'unreachable'}
</span>
</div>
<div className="dim" style={{ fontSize: '0.76rem', marginTop: 4 }}>
{s.sidecarBaseUrl} · {s.hasToken ? 'token stored' : 'no token'} · protocol {s.protocol}
{s.sidecarProtocol != null && s.sidecarProtocol !== s.protocol ? ` (sidecar speaks ${s.sidecarProtocol})` : ''}
{s.lastSeenAt ? ` · last seen ${ago(s.lastSeenAt)}` : ''}
</div>
<div className="dim" style={{ fontSize: '0.76rem', marginTop: 2 }}>
{s.nextWipe
? `Next wipe ${nextWipe(s.nextWipe)}, from ${SOURCE[s.nextWipe.source] || s.nextWipe.source}.`
: 'No wipe schedule set.'}
</div>
<div className="dim" style={{ fontSize: '0.76rem', marginTop: 2 }}>{titlesSummary(s.titles, s.titlePush, categories)}</div>
{zoneHelperNote(s.zoneHelper) && (
<div style={{ fontSize: '0.76rem', marginTop: 2, color: 'var(--warn, #d9c184)' }}>{zoneHelperNote(s.zoneHelper)}</div>
)}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
<button type="button" className="btn" onClick={() => { setError(''); setTitling(null); setForm(formFrom(s)) }}>Edit</button>
<button type="button" className="btn" onClick={() => test(s)}>Test the sidecar</button>
<button type="button" className="btn" onClick={() => { setForm(null); setTitling(s) }}>Chat titles</button>
<button type="button" className="btn" onClick={() => mods(s)}>Optional mods</button>
{confirming === s.id ? (
<>
<button type="button" className="btn" onClick={() => remove(s)}>Delete {s.name} and everything recorded about it</button>
<button type="button" className="btn" onClick={() => setConfirming(null)}>Keep it</button>
</>
) : (
<button type="button" className="btn" onClick={() => setConfirming(s.id)}>Delete</button>
)}
</div>
{notes[s.id] && <p className="dim" style={{ fontSize: '0.76rem', margin: '6px 0 0' }}>{notes[s.id]}</p>}
</div>
))}
{!form && (
<div style={{ marginTop: 12 }}>
<button type="button" className="btn" onClick={() => { setError(''); setForm(blankForm()) }}>Add a server</button>
</div>
)}
</section>
{form && (
<ServerForm form={form} set={set} busy={busy} error={error} onSave={save} onCancel={() => setForm(null)} />
)}
{titling && (
<TitlesForm
key={titling.id}
server={titling}
categories={categories}
onSaved={() => { setTitling(null); setReloads((n) => n + 1) }}
onCancel={() => setTitling(null)}
/>
)}
<CategoryTitles categories={categories} onSaved={() => setReloads((n) => n + 1)} />
<VoiceCard />
</div>
)
}
function Field({ label, hint, children }) {
return (
<label className="sans" style={{ display: 'grid', gap: 4, fontSize: '0.84rem' }}>
<span style={{ color: 'var(--head)' }}>{label}</span>
{children}
{hint && <span className="dim" style={{ fontSize: '0.74rem' }}>{hint}</span>}
</label>
)
}
function ServerForm({ form, set, busy, error, onSave, onCancel }) {
const weekly = form.wipeRule === 'weekly' || form.wipeRule === 'biweekly'
const rule = RULES.find((r) => r.id === form.wipeRule) || RULES[0]
const oncePast = form.storedOnceAt && form.wipeOnce === toLocalInput(form.storedOnceAt) && Date.parse(form.storedOnceAt) <= Date.now()
return (
<form onSubmit={onSave} className="panel" style={{ padding: '16px 18px', display: 'grid', gap: 14 }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>
{form.isNew ? 'Add a server' : `Edit ${form.name}`}
</h2>
{form.isNew && (
<Field label="Id" hint="Lowercase letters, digits and hyphens. It is in every link to this server and cannot be changed later.">
<input value={form.id} onChange={set('id')} required pattern="[a-z0-9][a-z0-9-]{0,63}" style={inputStyle} />
</Field>
)}
<Field label="Name">
<input value={form.name} onChange={set('name')} required maxLength={120} style={inputStyle} />
</Field>
<Field label="Sidecar address" hint="The base URL of the sidecar on the game host, e.g. http://10.0.0.5:8090.">
<input value={form.sidecarBaseUrl} onChange={set('sidecarBaseUrl')} required style={inputStyle} />
</Field>
<Field
label="Sidecar token"
hint={form.isNew ? 'From the sidecar’s own config. Needed to add a server.' : 'Leave blank to keep the stored token. It is never shown again once saved.'}
>
<input
type="password"
autoComplete="new-password"
value={form.sidecarToken}
onChange={set('sidecarToken')}
required={form.isNew}
maxLength={512}
style={inputStyle}
/>
</Field>
<div style={{ display: 'flex', gap: 18, flexWrap: 'wrap' }}>
<label className="sans" style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.enabled} onChange={set('enabled')} /> Enabled
</label>
<Field label="Order">
<input type="number" value={form.sortOrder} onChange={set('sortOrder')} min={-1000} max={1000} style={{ ...inputStyle, width: 90 }} />
</Field>
</div>
<fieldset style={{ border: '1px solid var(--line-soft)', borderRadius: 8, padding: '12px 14px', display: 'grid', gap: 12 }}>
<legend className="sans" style={{ color: 'var(--head)', fontSize: '0.86rem', padding: '0 6px' }}>Wipe schedule</legend>
<Field label="Rule" hint={rule.hint}>
<select value={form.wipeRule} onChange={set('wipeRule')} style={inputStyle}>
{RULES.map((r) => <option key={r.id} value={r.id}>{r.label}</option>)}
</select>
</Field>
{weekly && (
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
<Field label="Day">
<select value={form.wipeDay} onChange={set('wipeDay')} style={inputStyle}>
{DAYS.map((d, i) => <option key={d} value={i}>{d}</option>)}
</select>
</Field>
<Field label="Time">
<input type="time" value={form.wipeTime} onChange={set('wipeTime')} required style={inputStyle} />
</Field>
<Field label="Time zone" hint="The zone the time is in. It follows that zone’s summer time.">
<input value={form.wipeTz} onChange={set('wipeTz')} list="rust-zones" required style={inputStyle} />
</Field>
</div>
)}
{form.wipeRule === 'biweekly' && (
<Field label="One wipe on this schedule" hint={`A ${DAYS[form.wipeDay]} the server wiped or will wipe on. It says which weeks are wipe weeks.`}>
<input type="date" value={form.wipeAnchor} onChange={set('wipeAnchor')} required style={inputStyle} />
</Field>
)}
<Field
label="One-off wipe (optional)"
hint="A delayed or extra wipe, in your own clock. While it is in the future it is the next wipe, and anything scheduled before it is skipped."
>
<span style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<input type="datetime-local" value={form.wipeOnce} onChange={set('wipeOnce')} style={inputStyle} />
{form.wipeOnce && <button type="button" className="btn" onClick={() => set('wipeOnce')('')}>Clear</button>}
</span>
</Field>
{oncePast && (
<p className="sans dim" style={{ fontSize: '0.76rem', margin: 0 }}>
That date has passed, so it no longer changes anything. Saving will clear it.
</p>
)}
</fieldset>
<datalist id="rust-zones">{ZONES.map((z) => <option key={z} value={z} />)}</datalist>
<div className="sans" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<button type="submit" className="btn" disabled={busy}>{busy ? 'Saving…' : 'Save'}</button>
<button type="button" className="btn" onClick={onCancel} disabled={busy}>Cancel</button>
{error && <span style={{ color: '#d08a2a', fontSize: '0.8rem' }}>{error}</span>}
</div>
</form>
)
}
const inputStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input, 6px)',
padding: '5px 8px',
fontSize: '0.84rem',
}

View File

@@ -0,0 +1,284 @@
// ── This module's fill for `admin.users.detail` ───────────────────────────
//
// R13's first slot, and the phase criterion as an operator meets it: the Steam
// id inside core's own user page, under core's own security panel.
//
// **The slot hands over `userId` and nothing else** — not a client. So this file
// builds its own bindings for the routes the server half registered
// (`api.adminUserLinks`), which is §3.5's rule applied to a slot: the two ends of
// a call belong to the same module even when the URL between them is core's.
//
// **Most users have no Rust account, so most of the time this renders nothing.**
// A panel that announced "no linked Steam accounts" on every user page in a
// community that also runs a UO shard would be noise on the overwhelming
// majority of them. Silence is the honest answer to "what does the Rust module
// know about this person" when it is nothing.
import { useCallback, useState } from 'react'
import { ago, count, duration } from '../../lib/format.js'
import { useAsync } from '../../core.js'
import api from '../../api.js'
/** Six lines of furniture the §3.4 kit does not carry, so it is vendored. */
function SectionTitle({ children }) {
return (
<div className="field-label" style={{ marginBottom: 12, marginTop: 4 }}>
{children}
</div>
)
}
/** One server's all-time totals for this player. */
function ServerRow({ server }) {
return (
<li
className="sans"
style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: '0.86rem', color: 'var(--ink)' }}
>
<span style={{ minWidth: 0, color: 'var(--head)' }}>{server.serverName}</span>
<span className="dim" style={{ flex: 'none', fontSize: '0.8rem' }}>
{count(server.kills)} kills · {count(server.deaths)} deaths · {duration(server.playtimeSec)}
{server.wipes > 1 ? ` · ${server.wipes} wipes` : ''}
</span>
</li>
)
}
/** One linked Steam account: who it is, when it was linked, and the way out. */
function LinkPanel({ userId, link, onRemoved }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
async function unlink() {
setBusy(true)
setError('')
try {
await api.adminUserLinks.remove(userId, link.steamId)
await onRemoved()
} catch (err) {
setError(err.message || 'Could not unlink that account.')
setBusy(false)
}
}
return (
<div className="panel" style={{ padding: '14px 16px' }}>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
<div style={{ minWidth: 0, flex: 1 }}>
<div className="display" style={{ fontSize: '1rem', color: 'var(--head)' }}>
{link.name || link.steamId}
</div>
<div className="sans dim" style={{ fontSize: '0.76rem', marginTop: 2 }}>
{link.steamId} · linked {ago(link.linkedAt)}
{link.serverId ? ` on ${link.serverId}` : ''}
{link.lastSeen ? ` · last played ${ago(link.lastSeen)}` : ' · never played'}
</div>
{/* Worth showing only when they differ: the name on the link is what
they were called when they linked, the other is what the game last
saw. A rename is the ordinary reason, and an operator reading a
support ticket wants both names. */}
{link.linkedName && link.name && link.linkedName !== link.name && (
<div className="sans dim" style={{ fontSize: '0.72rem', marginTop: 2 }}>
Linked as “{link.linkedName}”.
</div>
)}
</div>
<button type="button" className="btn btn-ghost" onClick={unlink} disabled={busy} style={{ flex: 'none' }}>
{busy ? 'Unlinking…' : 'Unlink'}
</button>
</div>
{error && (
<p className="sans" style={{ color: '#e05a5a', fontSize: '0.8rem', margin: '8px 0 0' }}>{error}</p>
)}
{link.servers.length > 0 && (
<ul
style={{
listStyle: 'none',
margin: '12px 0 0',
padding: '12px 0 0',
borderTop: '1px solid var(--line-soft)',
display: 'flex',
flexDirection: 'column',
gap: 6,
}}
>
{link.servers.map((server) => (
<ServerRow key={server.serverId} server={server} />
))}
</ul>
)}
</div>
)
}
/**
* Phase 7's half of the panel: what this person may do in game.
*
* It renders whenever they hold anything, INCLUDING when they have linked no
* Steam account — which is the one case worth going out of the way for. A grant
* against an unlinked person is authored, stored, pushed nowhere, and identical
* to a working one everywhere except here.
*/
function PermissionsPanel({ userId, data, onChanged }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [permission, setPermission] = useState('')
const act = async (fn) => {
setBusy(true)
setError('')
try {
await fn()
await onChanged()
} catch (err) {
setError(err.message || 'That did not work.')
} finally {
setBusy(false)
}
}
if (!data) return null
const nothing = data.groups.length === 0 && data.grants.length === 0
return (
<div className="panel" style={{ padding: '14px 16px' }}>
<div className="field-label" style={{ marginBottom: 8 }}>
Permissions
</div>
{nothing && (
<p className="sans dim" style={{ fontSize: '0.8rem', margin: '0 0 8px' }}>
Nothing granted.
</p>
)}
{data.groups.map((group) => (
<div key={group.name} className="sans" style={{ fontSize: '0.84rem', padding: '4px 0' }}>
<span style={{ color: 'var(--head)' }}>{group.title || group.name}</span>{' '}
<span className="dim" style={{ fontSize: '0.76rem' }}>
group · {group.scope === '*' ? 'every server' : group.scope}
{group.permissions.length ? ` · ${group.permissions.join(', ')}` : ' · carries nothing'}
</span>
</div>
))}
{data.grants.map((row) => (
<div
key={row.id}
className="sans"
style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: '0.84rem', padding: '4px 0' }}
>
<span style={{ flex: 1, color: 'var(--head)' }}>
{row.permission}{' '}
<span className="dim" style={{ fontSize: '0.76rem' }}>
{row.scope === '*' ? 'every server' : row.scope}
{row.source !== 'admin' ? ` · ${row.source}` : ''}
</span>
</span>
<button
type="button"
className="btn btn-ghost"
disabled={busy}
onClick={() => act(() => api.adminUserPermissions.revoke(userId, row.id))}
style={{ flex: 'none' }}
>
Remove
</button>
</div>
))}
{!nothing && data.reaches.length === 0 && (
<p className="sans" style={{ color: '#d08a2a', fontSize: '0.78rem', margin: '8px 0 0' }}>
This account has linked no Steam id, so none of it reaches a game yet. It will apply by
itself when they link.
</p>
)}
<form
style={{ display: 'flex', gap: 8, marginTop: 10 }}
onSubmit={(event) => {
event.preventDefault()
if (!permission.trim()) return
act(() =>
api.adminUserPermissions.grant(userId, { permission: permission.trim().toLowerCase() }),
)
setPermission('')
}}
>
<input
className="input"
placeholder="kits.vip"
value={permission}
onChange={(event) => setPermission(event.target.value)}
style={{ flex: 1 }}
/>
<button type="submit" className="btn" disabled={busy}>
Grant
</button>
</form>
{error && (
<p className="sans" style={{ color: '#e05a5a', fontSize: '0.8rem', margin: '8px 0 0' }}>
{error}
</p>
)}
</div>
)
}
export default function UserRustSections({ userId }) {
// Core's `useAsync` has no refresh, so a counter in the deps is how this
// re-reads after its own write (the same shape the player page uses).
const [reloads, setReloads] = useState(0)
const { data } = useAsync(() => api.adminUserLinks.list(userId), [userId, reloads])
const { data: permissions } = useAsync(
() => api.adminUserPermissions.list(userId),
[userId, reloads],
)
const reload = useCallback(() => setReloads((n) => n + 1), [])
// No `Loading` and no `ErrorState`, deliberately. This is a section inside
// somebody else's page: a spinner on every user page for a module most users
// have nothing to do with is worse than a section that appears when it has
// something, and a failure here must not replace core's own user detail with an
// error card.
// **Both reads decide whether this section exists**, and the second one is the
// reason. A browser walk found it: a person can hold permissions and have
// linked no Steam account — which is exactly the state an operator most needs
// to see, because it is the one that reaches nobody — and a section gated on
// links alone hides it completely.
const holdsSomething =
permissions && (permissions.groups.length > 0 || permissions.grants.length > 0)
if (!data || (data.links.length === 0 && !holdsSomething)) return null
return (
<section style={{ borderTop: '1px solid var(--line-soft)', marginTop: 30, paddingTop: 22 }}>
<SectionTitle>Rust</SectionTitle>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{data.links.map((link) => (
<LinkPanel key={link.steamId} userId={userId} link={link} onRemoved={reload} />
))}
{data.links.length > 0 && (
<p className="sans dim" style={{ fontSize: '0.74rem', margin: 0 }}>
A link is fleet-wide and totals are all-time, summed across every wipe. Unlinking here is
recorded in the activity log — it is the way back for a player who linked the wrong
account and cannot reach it in game.
</p>
)}
{/* Inside the same section rather than beside it: "who is this in game"
and "what may they do there" are one question asked twice, and an
operator reading a support ticket has both in front of them. The note
above belongs to the links, so it sits with them rather than under
the panel it would otherwise appear to describe. */}
<PermissionsPanel userId={userId} data={permissions} onChanged={reload} />
</div>
</section>
)
}

View File

@@ -0,0 +1,669 @@
// ── Admin · Rust · Visibility ─────────────────────────────────────────────
//
// Who may see who is online. The org lead's rule (2026-09-22): nothing names who
// is online by default — the narrowest audience, staff, unless an operator
// deliberately widens it here. A count of players is public at every setting.
//
// One fleet default and an optional override per server, because a creative or
// PvE server may reasonably publish a roll call a PvP server must not — and a
// server that has not chosen follows the fleet, so narrowing the fleet narrows
// every server that never said otherwise.
//
// The page says what "who is online" covers, because it is wider than the tab
// of the same name: the killfeed, chat and joins in the feed, and the
// leaderboard's "last seen" all name a player who was on at a given moment.
//
// Phase 9 adds a second setting beside it: who may see a CLAN ROSTER (D48). It
// defaults to the clan's own members and staff, and widening it widens online
// status too, because a roster row carries it — the page says so. The same card
// lists each server's clan board: a server whose clans cannot be read, one at
// the game's 100-clan ceiling (D55), and one running the uMod Clans plugin,
// whose clans are a separate system and never Teams (D47).
//
// Phase 13b adds a third (D104, D106): whether a published news post is also
// said in each server's in-game chat. Off by default, because core sends every
// post to every registered leg — without a switch, the day this module updated,
// every post would start appearing in every server's chat. It lives here because
// this is the one page that lists every server with a setting of its own.
//
// Phase 14 adds the live map's switches (D114): four layers, each with a fleet
// audience and an optional per-server override, and the own-and-mates switch
// (D118). Beside each server is what its map picture is, and the two buttons
// that act at once rather than on Save: Fetch again, and Render now — shown only
// where there is no picture, with how long it will stall that server (D109).
//
// PLAN_REDESIGNS §4 adds which monuments the map draws (D196): a switch per
// monument label, because that is what staff read and it groups the variants
// (31 substations of four prefabs are one "Substation"). The minor labels start
// hidden and every other label drawn, so a monument Facepunch adds appears. One
// fleet list, and each server's own labels with an override each.
import { useCallback, useEffect, useState } from 'react'
import { ErrorState, Loading, useAsync } from '../../core.js'
import api from '../../api.js'
import { fleetLabels, fleetShows, markerDiff, serverShows, setFleet as setFleetMarker, setServer as setServerMarker } from '../../lib/mapMarkers.js'
const INHERIT = ''
const LABEL = {
staff: 'Staff only',
signed_in: 'Signed-in members',
public: 'Everyone',
}
const CLAN_LABEL = {
members: 'The clan’s members and staff',
signed_in: 'Signed-in members',
public: 'Everyone',
}
const CLAN_DESCRIBE = {
members: 'Players whose linked Rust account is in the clan, plus admins and moderators. The default.',
signed_in: 'Anybody with an account on this site.',
public: 'Anybody at all, signed in or not.',
}
const DESCRIBE = {
staff: 'Admins and moderators. The default.',
signed_in: 'Anybody with an account on this site.',
public: 'Anybody at all, signed in or not.',
}
function Card({ title, subtitle, children }) {
return (
<section className="panel" style={{ padding: '16px 18px', marginBottom: 18 }}>
<header style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 12 }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>
{title}
</h2>
{subtitle && (
<span className="sans dim" style={{ fontSize: '0.76rem' }}>
{subtitle}
</span>
)}
</header>
{children}
</section>
)
}
function AudienceSelect({ value, onChange, audiences, inherit = null, label }) {
return (
<select value={value} onChange={(e) => onChange(e.target.value)} style={selectStyle} aria-label={label}>
{inherit && <option value={INHERIT}>{inherit}</option>}
{audiences.map((a) => (
<option key={a} value={a}>{LABEL[a] || a}</option>
))}
</select>
)
}
export default function Visibility() {
const [reloads, setReloads] = useState(0)
const { data, error: loadError } = useAsync(() => api.adminVisibility.read(), [reloads])
const [fleet, setFleet] = useState('staff')
const [clanRoster, setClanRoster] = useState('members')
const [servers, setServers] = useState({})
const [news, setNews] = useState({})
const [delivery, setDelivery] = useState({})
const [mapFleet, setMapFleet] = useState({})
const [mapServers, setMapServers] = useState({})
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [saved, setSaved] = useState(false)
// The form starts from what the server said and is reset from it after every
// save — the answer to a PUT is the new state, so what is on screen is always
// the site's word rather than what this page sent.
const load = useCallback((state) => {
setFleet(state.presence.fleet)
setClanRoster((state.clans && state.clans.roster) || 'members')
setServers(Object.fromEntries(state.presence.servers.map((s) => [s.id, s.override || INHERIT])))
setNews(Object.fromEntries(((state.news && state.news.servers) || []).map((s) => [s.id, Boolean(s.on)])))
setDelivery(Object.fromEntries(((state.news && state.news.servers) || []).map((s) => [s.id, s.delivery || 'chat'])))
if (state.map) {
setMapFleet({ ...state.map.fleet, markers: { ...(state.map.fleet.markers || {}) } })
setMapServers(Object.fromEntries(state.map.servers.map((s) => [s.id, mapOverridesToForm(s.overrides)])))
}
}, [])
useEffect(() => {
if (data) load(data)
}, [data, load])
if (loadError) return <ErrorState error={loadError} />
if (!data) return <Loading />
const audiences = data.audiences
const rows = data.presence.servers
const dirtyFleet = fleet !== data.presence.fleet
const dirtyServers = rows.filter((s) => (servers[s.id] ?? INHERIT) !== (s.override || INHERIT))
const clans = data.clans || { audiences: [], roster: 'members', servers: [] }
const dirtyClans = clanRoster !== clans.roster
const newsRows = (data.news && data.news.servers) || []
const dirtyNews = newsRows.filter((s) => Boolean(news[s.id]) !== Boolean(s.on))
const dirtyDelivery = newsRows.filter((s) => (delivery[s.id] || 'chat') !== (s.delivery || 'chat'))
const mapCard = data.map || null
const mapChanges = mapCard ? mapDiff(mapCard, mapFleet, mapServers) : null
const dirtyMap = Boolean(mapChanges)
const dirty = dirtyFleet || dirtyServers.length > 0 || dirtyClans || dirtyNews.length > 0 || dirtyDelivery.length > 0 || dirtyMap
const effective = (id) => servers[id] || fleet
const widened = fleet !== 'staff' || rows.some((s) => effective(s.id) !== 'staff')
const save = async (e) => {
e.preventDefault()
setBusy(true)
setError('')
setSaved(false)
try {
const body = {}
if (dirtyFleet) body.fleet = fleet
if (dirtyClans) body.clanRoster = clanRoster
if (dirtyServers.length) {
body.servers = Object.fromEntries(dirtyServers.map((s) => [s.id, servers[s.id] || null]))
}
if (dirtyNews.length) body.news = Object.fromEntries(dirtyNews.map((s) => [s.id, Boolean(news[s.id])]))
if (dirtyDelivery.length) body.newsDelivery = Object.fromEntries(dirtyDelivery.map((s) => [s.id, delivery[s.id] || 'chat']))
if (dirtyMap) body.map = mapChanges
load(await api.adminVisibility.save(body))
setSaved(true)
setReloads((n) => n + 1)
} catch (err) {
setError(err.message || 'That did not save.')
} finally {
setBusy(false)
}
}
return (
<form onSubmit={save} style={{ maxWidth: 900 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
Nothing on this site names who is online unless you choose to show it. That covers more than
the Online tab: the joins, deaths and chat in each server’s feed, and the leaderboard’s “last
seen”, all say that a named player was on at a given moment. How many players are online is
always shown.
</p>
<Card title="Who is online" subtitle="the default for every server">
<div className="sans" style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: '0.86rem' }}>
<AudienceSelect value={fleet} onChange={setFleet} audiences={audiences} label="Fleet default" />
<span className="dim" style={{ fontSize: '0.78rem' }}>{DESCRIBE[fleet]}</span>
</div>
</Card>
<Card title="Per server" subtitle="an override, or the default above">
{rows.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: 0 }}>No servers are configured yet.</p>
)}
{rows.map((s) => (
<div
key={s.id}
className="sans"
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
padding: '8px 0',
borderTop: '1px solid var(--line-soft)',
fontSize: '0.86rem',
}}
>
<span style={{ minWidth: 180, color: 'var(--head)' }}>
{s.name}
{!s.enabled && <span className="dim" style={{ fontSize: '0.74rem' }}> · disabled</span>}
</span>
<AudienceSelect
value={servers[s.id] ?? INHERIT}
onChange={(v) => setServers((prev) => ({ ...prev, [s.id]: v }))}
audiences={audiences}
inherit={`Default (${LABEL[fleet] || fleet})`}
label={`Who is online on ${s.name}`}
/>
<span className="dim" style={{ fontSize: '0.78rem' }}>
{servers[s.id] ? 'its own setting' : 'follows the default'}
</span>
</div>
))}
</Card>
{widened && (
<p className="sans" style={{ color: '#d08a2a', fontSize: '0.8rem' }}>
Wider than staff: on a PvP server, knowing who is on tells a raiding party whose base is
undefended.
</p>
)}
<Card title="Clan rosters" subtitle="who is in each clan, on every server">
<div className="sans" style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: '0.86rem' }}>
<select
value={clanRoster}
onChange={(e) => setClanRoster(e.target.value)}
style={selectStyle}
aria-label="Who may see a clan roster"
>
{clans.audiences.map((a) => (
<option key={a} value={a}>{CLAN_LABEL[a] || a}</option>
))}
</select>
<span className="dim" style={{ fontSize: '0.78rem' }}>{CLAN_DESCRIBE[clanRoster]}</span>
</div>
<p className="sans dim" style={{ fontSize: '0.78rem', margin: '10px 0 0' }}>
Each clan’s name, colour, score and member count are always public.
</p>
{clanRoster !== 'members' && (
<p className="sans" style={{ color: '#d08a2a', fontSize: '0.8rem', margin: '8px 0 0' }}>
A roster also shows which members are online right now, so this shows who is on to{' '}
{clanRoster === 'public' ? 'everyone' : 'every signed-in member'} as well.
</p>
)}
<ClanBoards servers={clans.servers || []} />
</Card>
<Card title="News in game chat" subtitle="a published news post, said in each server’s chat">
<p className="sans dim" style={{ fontSize: '0.8rem', margin: '0 0 8px' }}>
When a news post is published, its title is said in the chat of every server switched on
here. A server that is down when a post is published is skipped rather than told late. A popup
needs PopupNotifications on that server; one without it refuses the post and says why.
</p>
{newsRows.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: 0 }}>No servers are configured yet.</p>
)}
{newsRows.map((s) => (
<label
key={s.id}
className="sans"
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
padding: '8px 0',
borderTop: '1px solid var(--line-soft)',
fontSize: '0.86rem',
cursor: 'pointer',
}}
>
<input
type="checkbox"
checked={Boolean(news[s.id])}
onChange={(e) => setNews((prev) => ({ ...prev, [s.id]: e.target.checked }))}
aria-label={`Say news in ${s.name}’s chat`}
/>
<span style={{ minWidth: 180, color: 'var(--head)' }}>
{s.name}
{!s.enabled && <span className="dim" style={{ fontSize: '0.74rem' }}> · disabled</span>}
</span>
<span className="dim" style={{ fontSize: '0.78rem' }}>{news[s.id] ? 'says news' : 'off'}</span>
{/* D142: where the post goes on this server when it is switched on. */}
<select
value={delivery[s.id] || 'chat'}
onChange={(e) => setDelivery((prev) => ({ ...prev, [s.id]: e.target.value }))}
disabled={!news[s.id]}
aria-label={`Where news goes on ${s.name}`}
style={{ marginLeft: 'auto', background: 'var(--panel-flat, transparent)', color: 'var(--text)', border: '1px solid var(--line)', borderRadius: 'var(--radius-input, 6px)', padding: '3px 6px', fontSize: '0.8rem' }}
>
<option value="chat">in chat</option>
<option value="popup">as a popup</option>
</select>
</label>
))}
</Card>
{mapCard && (
<MapCard
card={mapCard}
audiences={audiences}
presenceOf={(id) => effective(id)}
fleet={mapFleet}
setFleet={setMapFleet}
servers={mapServers}
setServers={setMapServers}
onActed={() => setReloads((n) => n + 1)}
/>
)}
<div className="sans" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<button type="submit" className="btn" disabled={busy || !dirty}>
{busy ? 'Saving…' : 'Save'}
</button>
{saved && !dirty && <span className="dim" style={{ fontSize: '0.8rem' }}>Saved.</span>}
{error && <span style={{ color: '#d08a2a', fontSize: '0.8rem' }}>{error}</span>}
</div>
</form>
)
}
/**
* What each server's clan board says about itself. Only the servers with
* something to report are listed: a board that is current, complete and read
* normally is the case that needs no sentence.
*/
function ClanBoards({ servers }) {
const notes = []
for (const s of servers) {
if (s.umodClans) {
notes.push([s, 'is running the uMod Clans plugin. Its clans are a separate system from the game’s own, and only the game’s clans appear on this site.'])
}
if (!s.supported) {
notes.push([s, s.reason ? `cannot report its clans: ${s.reason}.` : 'has not reported its clans yet.'])
} else if (s.truncated) {
notes.push([s, 'is at the game’s limit of 100 listed clans, so clans beyond the top 100 by score are not shown, and a disbanded clan is not removed until it drops below.'])
} else if (!s.fresh) {
notes.push([s, 'has not reported its clans recently, so they are shown as last reported.'])
}
}
if (!notes.length) return null
return (
<ul className="sans" style={{ margin: '12px 0 0', paddingLeft: 18, fontSize: '0.8rem' }}>
{notes.map(([s, text], i) => (
// eslint-disable-next-line react/no-array-index-key
<li key={`${s.id}-${i}`} style={{ margin: '4px 0' }}>
<strong style={{ color: 'var(--head)' }}>{s.name}</strong> {text}
</li>
))}
</ul>
)
}
const selectStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 'var(--radius-input, 6px)',
padding: '4px 8px',
fontSize: '0.84rem',
}
// ── The live map (phase 14) ───────────────────────────────────────────────
const MAP_LAYERS = [
{ id: 'world', label: 'Monuments & world events', hint: 'Cargo, helicopters, Bradley, supply drops, locked crates.' },
{ id: 'events', label: 'Site events', hint: 'The zones, crates and NPCs this site’s events placed, while they run.' },
{ id: 'players', label: 'Players', hint: 'Where everybody is, with names, and the sleepers.' },
{ id: 'bases', label: 'Bases', hint: 'Tool cupboards and vending machines, as positions only.' },
]
const RANK = { public: 0, signed_in: 1, staff: 2 }
/** A server's overrides as form values: '' follows the fleet, mates is 'on' / 'off'. */
function mapOverridesToForm(overrides) {
const form = {}
for (const l of MAP_LAYERS) form[l.id] = overrides[l.id] || INHERIT
form.mates = overrides.mates === null || overrides.mates === undefined ? INHERIT : overrides.mates ? 'on' : 'off'
form.markers = { ...(overrides.markers || {}) }
return form
}
/** What the form changed, in the shape the PUT takes, or null when nothing did. */
function mapDiff(card, fleet, servers) {
const out = {}
const fleetChanges = {}
for (const key of [...MAP_LAYERS.map((l) => l.id), 'mates']) {
if (key in fleet && fleet[key] !== card.fleet[key]) fleetChanges[key] = fleet[key]
}
const fleetMarkers = markerDiff(card.fleet.markers, fleet.markers)
if (fleetMarkers) fleetChanges.markers = fleetMarkers
if (Object.keys(fleetChanges).length) out.fleet = fleetChanges
const serverChanges = {}
for (const s of card.servers) {
const before = mapOverridesToForm(s.overrides)
const now = servers[s.id] || before
const changed = {}
const markers = markerDiff(before.markers, now.markers)
if (markers) changed.markers = markers
for (const key of Object.keys(before)) {
if (key === 'markers' || now[key] === before[key]) continue
if (key === 'mates') changed.mates = now.mates === INHERIT ? null : now.mates === 'on'
else changed[key] = now[key] === INHERIT ? null : now[key]
}
if (Object.keys(changed).length) serverChanges[s.id] = changed
}
if (Object.keys(serverChanges).length) out.servers = serverChanges
return Object.keys(out).length ? out : null
}
function MapCard({ card, audiences, presenceOf, fleet, setFleet, servers, setServers, onActed }) {
const [acting, setActing] = useState(null)
const [notes, setNotes] = useState({})
// Fetch again and Render now act at once rather than on Save: they are
// questions put to a game server, not settings.
const act = async (server, kind) => {
setActing(`${server.id}:${kind}`)
setNotes((n) => ({ ...n, [server.id]: '' }))
try {
if (kind === 'fetch') {
const r = await api.admin.fetchMap(server.id)
setNotes((n) => ({ ...n, [server.id]: r.message || `Fetched: ${r.outcome}.` }))
} else {
const r = await api.admin.renderMap(server.id)
setNotes((n) => ({
...n,
[server.id]: `The server is drawing its map now — about ${r.stallSeconds} seconds of stall. The picture appears here when it is done.`,
}))
}
onActed()
} catch (err) {
setNotes((n) => ({ ...n, [server.id]: err.message || 'That did not work.' }))
} finally {
setActing(null)
}
}
return (
<Card title="The live map" subtitle="what each server’s map shows, and to whom">
<p className="sans dim" style={{ fontSize: '0.8rem', margin: '0 0 10px' }}>
The picture of the map is always public: it is drawn from the map seed and says nothing about who plays.
Everything that moves on it is a layer, and each layer has its own audience. The players layer can never
show more than who is online does, whatever it is set to here.
</p>
<div
className="sans"
style={{ display: 'grid', gridTemplateColumns: 'minmax(180px, 1fr) auto', gap: '6px 12px', alignItems: 'center', fontSize: '0.86rem' }}
>
{MAP_LAYERS.map((l) => (
<FleetRow key={l.id} label={l.label} hint={l.hint}>
<AudienceSelect
value={fleet[l.id] || 'staff'}
onChange={(v) => setFleet((f) => ({ ...f, [l.id]: v }))}
audiences={audiences}
label={`${l.label}: fleet default`}
/>
</FleetRow>
))}
<FleetRow label="You and your clan" hint="A linked player sees themselves and their online clan mates, whatever the players layer says.">
<select
value={fleet.mates ? 'on' : 'off'}
onChange={(e) => setFleet((f) => ({ ...f, mates: e.target.value === 'on' }))}
style={selectStyle}
aria-label="You and your clan: fleet default"
>
<option value="on">On</option>
<option value="off">Off</option>
</select>
</FleetRow>
</div>
<FleetMarkers card={card} fleet={fleet} setFleet={setFleet} />
{card.servers.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: '12px 0 0' }}>No servers are configured yet.</p>
)}
{card.servers.map((s) => {
const form = servers[s.id] || mapOverridesToForm(s.overrides)
const set = (key, value) => setServers((prev) => ({ ...prev, [s.id]: { ...form, [key]: value } }))
const players = form.players || fleet.players
const presence = presenceOf(s.id)
const capped = RANK[players] < RANK[presence]
const noPicture = !s.picture || !s.picture.hasPicture
return (
<div key={s.id} className="sans" style={{ borderTop: '1px solid var(--line-soft)', padding: '10px 0', fontSize: '0.84rem' }}>
<div style={{ color: 'var(--head)', marginBottom: 6 }}>
{s.name}
{!s.enabled && <span className="dim" style={{ fontSize: '0.74rem' }}> · disabled</span>}
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
{MAP_LAYERS.map((l) => (
<label key={l.id} className="dim" style={{ display: 'inline-flex', flexDirection: 'column', gap: 2, fontSize: '0.74rem' }}>
{l.label}
<AudienceSelect
value={form[l.id]}
onChange={(v) => set(l.id, v)}
audiences={audiences}
inherit={`Default (${LABEL[fleet[l.id]] || fleet[l.id]})`}
label={`${l.label} on ${s.name}`}
/>
</label>
))}
<label className="dim" style={{ display: 'inline-flex', flexDirection: 'column', gap: 2, fontSize: '0.74rem' }}>
You and your clan
<select value={form.mates} onChange={(e) => set('mates', e.target.value)} style={selectStyle} aria-label={`You and your clan on ${s.name}`}>
<option value={INHERIT}>{`Default (${fleet.mates ? 'On' : 'Off'})`}</option>
<option value="on">On</option>
<option value="off">Off</option>
</select>
</label>
</div>
<ServerMarkers
server={s}
minorLabels={card.minorLabels || []}
fleetMarkers={fleet.markers}
markers={form.markers}
onChange={(next) => set('markers', next)}
/>
{capped && (
<p className="dim" style={{ fontSize: '0.76rem', margin: '6px 0 0' }}>
Players will be shown to {(LABEL[presence] || presence).toLowerCase()} on this server, because that is who may see who is online.
</p>
)}
<div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 10, marginTop: 8, fontSize: '0.78rem' }}>
<span className="dim">{describePicture(s.picture)}</span>
<button type="button" className="btn" disabled={Boolean(acting) || s.fetching} onClick={() => act(s, 'fetch')}>
{acting === `${s.id}:fetch` || s.fetching ? 'Fetching…' : 'Fetch again'}
</button>
{noPicture && (
<button type="button" className="btn" disabled={Boolean(acting) || s.rendering} onClick={() => act(s, 'render')}>
{s.rendering ? 'Drawing…' : 'Render now'}
</button>
)}
</div>
{noPicture && (
<p style={{ color: '#d08a2a', fontSize: '0.76rem', margin: '6px 0 0' }}>
Render now makes the game draw its own map, which stops that server for about {s.renderStallSeconds} seconds —
nobody on it can move while it draws. A server with Rust+ switched on (<code>app.port</code>) never needs it.
</p>
)}
{(notes[s.id] || s.lastError) && (
<p className="dim" style={{ fontSize: '0.76rem', margin: '6px 0 0' }}>{notes[s.id] || s.lastError}</p>
)}
</div>
)
})}
</Card>
)
}
/**
* The fleet's monument labels (D196): every label on any server's current map,
* and the minor list, each a checkbox. Ticked is drawn.
*/
function FleetMarkers({ card, fleet, setFleet }) {
const minor = card.minorLabels || []
const labels = fleetLabels(minor, card.servers)
const hidden = labels.filter((l) => !fleetShows(minor, fleet.markers, l.key)).length
return (
<details className="sans" style={{ marginTop: 12, fontSize: '0.84rem' }}>
<summary style={{ cursor: 'pointer', color: 'var(--head)' }}>
Monuments on the map <span className="dim" style={{ fontSize: '0.76rem' }}>· {labels.length} labels, {hidden} hidden by default</span>
</summary>
<p className="dim" style={{ fontSize: '0.76rem', margin: '6px 0 8px' }}>
Ticked labels are drawn on every server that has not chosen for itself. The minor ones — substations, caves, train
tunnels, wells and the like — start hidden. Any label not listed here, such as a monument a game update adds, is drawn.
</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))', gap: '4px 12px' }}>
{labels.map((l) => (
<label key={l.key} style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
<input
type="checkbox"
checked={fleetShows(minor, fleet.markers, l.key)}
onChange={(e) => setFleet((f) => ({ ...f, markers: setFleetMarker(minor, f.markers, l.key, e.target.checked) }))}
aria-label={`Draw ${l.label} by default`}
/>
<span>{l.label}</span>
{l.count > 0 && <span className="dim" style={{ fontSize: '0.72rem' }}>{l.count}</span>}
</label>
))}
</div>
</details>
)
}
/**
* One server's monument labels (D196): the labels on its current map, each
* following the fleet or drawn or hidden on this server alone.
*/
function ServerMarkers({ server, minorLabels, fleetMarkers, markers, onChange }) {
const labels = server.markerLabels || []
if (!labels.length) return null
const hidden = labels.filter((l) => !serverShows(minorLabels, fleetMarkers, markers, l.key)).length
const own = Object.keys(markers || {}).length
return (
<details style={{ marginTop: 8, fontSize: '0.8rem' }}>
<summary style={{ cursor: 'pointer' }} className="dim">
Monuments: {labels.length} labels on this map, {hidden} hidden{own ? `, ${own} set for this server` : ''}
</summary>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: '4px 12px', marginTop: 6 }}>
{labels.map((l) => {
const mine = markers && Object.prototype.hasOwnProperty.call(markers, l.key) ? (markers[l.key] ? 'on' : 'off') : INHERIT
const fleetOn = fleetShows(minorLabels, fleetMarkers, l.key)
return (
<label key={l.key} style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'space-between' }}>
<span>
{l.label} <span className="dim" style={{ fontSize: '0.72rem' }}>{l.count}</span>
</span>
<select
value={mine}
onChange={(e) => onChange(setServerMarker(markers, l.key, e.target.value === INHERIT ? null : e.target.value === 'on'))}
style={{ ...selectStyle, fontSize: '0.78rem', padding: '2px 6px' }}
aria-label={`${l.label} on ${server.name}`}
>
<option value={INHERIT}>{`Default (${fleetOn ? 'drawn' : 'hidden'})`}</option>
<option value="on">Drawn</option>
<option value="off">Hidden</option>
</select>
</label>
)
})}
</div>
</details>
)
}
function FleetRow({ label, hint, children }) {
return (
<>
<span>
<span style={{ color: 'var(--head)' }}>{label}</span>
<span className="dim" style={{ display: 'block', fontSize: '0.74rem' }}>{hint}</span>
</span>
{children}
</>
)
}
function describePicture(pic) {
if (!pic) return 'The server has not described its map yet.'
if (!pic.hasPicture) return `Map ${pic.mapKey}: the game has no picture of it.`
const from = pic.source === 'companion' ? 'from Rust+' : 'drawn on request'
const kb = Math.round((pic.bytes || 0) / 1024)
return `Map ${pic.mapKey}: picture ${from}, ${pic.width} × ${pic.height}, ${kb} KB${pic.fetchedAt ? `, fetched ${new Date(pic.fetchedAt).toLocaleString()}` : ''}.`
}

View File

@@ -0,0 +1,294 @@
// ── Admin · Rust · Zone presets (PLAN_REDESIGNS §3.1, D195, D210) ──────────
//
// Where a zone's ZoneManager flags and settings are chosen. Core's step editor
// has single-value fields only, so the org lead put the checkboxes here (D210):
// an admin saves a named set for one server, several, or every server, and a
// zone step's Options field offers the presets. Picking one COPIES its line into
// the step, so editing a preset here changes no published event.
//
// The flags are whatever each server's ZoneManager declared in its last hello
// (D211), grouped by `server/model/zones/zoneOptions.js`. A flag that file does
// not know is under Other, never hidden. A flag not on every server a preset
// covers is refused on save, with the server named.
import { useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { ErrorState, Loading, useAsync } from '../../core.js'
import api from '../../api.js'
const inputStyle = {
background: 'var(--panel-flat, transparent)',
color: 'var(--text)',
border: '1px solid var(--line)',
borderRadius: 6,
padding: '6px 8px',
font: 'inherit',
}
function blankForm() {
return { id: null, name: '', flags: [], settings: {}, allServers: false, servers: [] }
}
function formFrom(p) {
const settings = {}
for (const [k, v] of Object.entries(p.settings || {})) settings[k] = String(v)
return { id: p.id, name: p.name, flags: [...p.flags], settings, allServers: p.allServers, servers: [...p.servers] }
}
/** What the page sends: blank settings left out, the rest as typed (the server checks them). */
function bodyFrom(form) {
const settings = {}
for (const [k, v] of Object.entries(form.settings)) {
if (v !== '' && v !== undefined && v !== null) settings[k] = v
}
return { name: form.name.trim(), flags: form.flags, settings, allServers: form.allServers, servers: form.allServers ? [] : form.servers }
}
/** One line on what a server said about its zone mods. */
export function zoneModsLine(s) {
const zm = s.zoneManager
const zd = s.zoneDomes
const parts = [zm ? `ZoneManager ${zm.version || ''} · ${zm.flagCount} flags`.replace(' ', ' ') : 'no ZoneManager reported']
if (!zd || !zd.loaded) parts.push('no ZoneDomes, so no domes')
else if (!zd.helper || zd.helper.state === 'missing') parts.push('ZoneDomes without RunicGatewayDomes.cs, so no domes')
else if (zd.helper.state !== 'patched') parts.push(`the domes helper could not patch ZoneDomes${zd.helper.reason ? ` (${zd.helper.reason})` : ''}`)
else parts.push('domes available')
return parts.join(' · ')
}
export default function ZonePresets() {
const [reloads, setReloads] = useState(0)
const { data, error: loadError } = useAsync(() => api.adminZones.read(), [reloads])
const [form, setForm] = useState(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
if (loadError) return <ErrorState error={loadError} />
if (!data) return <Loading />
const servers = data.servers || []
const nameOf = new Map(servers.map((s) => [s.id, s.name || s.id]))
const save = async (e) => {
e.preventDefault()
setBusy(true)
setError('')
try {
if (form.id) await api.adminZones.update(form.id, bodyFrom(form))
else await api.adminZones.create(bodyFrom(form))
setForm(null)
setReloads((n) => n + 1)
} catch (err) {
setError(err.message || 'That did not save.')
} finally {
setBusy(false)
}
}
const remove = async (preset) => {
setBusy(true)
setError('')
try {
await api.adminZones.remove(preset.id)
setForm(null)
setReloads((n) => n + 1)
} catch (err) {
setError(err.message || 'That did not delete.')
} finally {
setBusy(false)
}
}
return (
<div style={{ maxWidth: 900 }}>
<p className="sans dim" style={{ fontSize: '0.82rem', marginTop: 0 }}>
Named sets of ZoneManager flags and settings. An event’s <em>Open a zone</em> step offers these in its Options
field; picking one copies it into the step, so changing a preset later does not change an event already
published. Who is exempt from a flag is a <code>zonemanager.ignoreflag.*</code> permission, set on the{' '}
<Link to="/admin/rust">permissions page</Link>.
</p>
<section className="panel" style={{ padding: '14px 18px', marginBottom: 18 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: '0 0 8px', color: 'var(--head)' }}>Servers</h2>
{servers.length === 0 && <p className="sans dim" style={{ fontSize: '0.82rem', margin: 0 }}>No servers are configured yet.</p>}
{servers.map((s) => (
<div key={s.id} className="sans" style={{ fontSize: '0.8rem', padding: '4px 0' }}>
<strong style={{ color: 'var(--head)' }}>{s.name || s.id}</strong>{' '}
<span className="dim">{zoneModsLine(s)}</span>
</div>
))}
</section>
<section className="panel" style={{ padding: '14px 18px', marginBottom: 18 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
<h2 className="display" style={{ fontSize: '1rem', margin: 0, color: 'var(--head)' }}>Presets</h2>
<button type="button" className="btn" style={{ marginLeft: 'auto' }} onClick={() => { setError(''); setForm(blankForm()) }}>
New preset
</button>
</div>
{(data.presets || []).length === 0 && (
<p className="sans dim" style={{ fontSize: '0.82rem', margin: '8px 0 0' }}>
None yet. None ship with the module: what an arena is differs by server.
</p>
)}
{(data.presets || []).map((p) => (
<div key={p.id} className="sans" style={{ borderTop: '1px solid var(--line-soft)', padding: '8px 0', fontSize: '0.84rem' }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
<strong style={{ color: 'var(--head)' }}>{p.name}</strong>
<span className="dim" style={{ fontSize: '0.76rem' }}>
{p.allServers ? 'every server' : p.servers.map((id) => nameOf.get(id) || id).join(', ')}
</span>
<button type="button" className="btn" style={{ marginLeft: 'auto' }} onClick={() => { setError(''); setForm(formFrom(p)) }}>
Edit
</button>
</div>
<code className="dim" style={{ fontSize: '0.74rem', wordBreak: 'break-word' }}>{p.line || 'no flags or settings'}</code>
</div>
))}
</section>
{form && (
<PresetForm
form={form}
setForm={setForm}
data={data}
busy={busy}
error={error}
onSave={save}
onCancel={() => setForm(null)}
onDelete={form.id ? () => remove(form) : null}
/>
)}
</div>
)
}
function PresetForm({ form, setForm, data, busy, error, onSave, onCancel, onDelete }) {
const servers = data.servers || []
// The flags on EVERY covered server that reported a list: a flag missing from
// one of them is shown but marked, and the save refuses it with the server named.
const covered = form.allServers ? servers : servers.filter((s) => form.servers.includes(s.id))
const missingOn = useMemo(() => {
const out = new Map()
for (const s of covered) {
const flags = s.zoneManager && s.zoneManager.flags
if (!flags || flags.length === 0) continue
const have = new Set(flags.map((f) => f.toLowerCase()))
for (const g of data.groups || []) {
for (const f of g.flags) {
if (!have.has(f.name.toLowerCase())) out.set(f.name, [...(out.get(f.name) || []), s.name || s.id])
}
}
}
return out
}, [covered, data.groups])
const toggleFlag = (name) =>
setForm((f) => ({ ...f, flags: f.flags.includes(name) ? f.flags.filter((x) => x !== name) : [...f.flags, name] }))
const toggleServer = (id) =>
setForm((f) => ({ ...f, servers: f.servers.includes(id) ? f.servers.filter((x) => x !== id) : [...f.servers, id] }))
const setSetting = (key, value) => setForm((f) => ({ ...f, settings: { ...f.settings, [key]: value } }))
return (
<form onSubmit={onSave} className="panel" style={{ padding: '16px 18px', display: 'grid', gap: 14 }}>
<h2 className="display" style={{ fontSize: '1.05rem', margin: 0, color: 'var(--head)' }}>
{form.id ? `Edit ${form.name}` : 'A new preset'}
</h2>
<label className="sans" style={{ display: 'grid', gap: 4, fontSize: '0.84rem' }}>
<span style={{ color: 'var(--head)' }}>Name</span>
<input value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} required maxLength={64} style={inputStyle} />
</label>
<fieldset style={{ border: '1px solid var(--line-soft)', borderRadius: 8, padding: '10px 14px', display: 'grid', gap: 6 }}>
<legend className="sans" style={{ color: 'var(--head)', fontSize: '0.86rem', padding: '0 6px' }}>For</legend>
<label className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.allServers} onChange={(e) => setForm((f) => ({ ...f, allServers: e.target.checked }))} />
Every server, including servers added later
</label>
{!form.allServers &&
servers.map((s) => (
<label key={s.id} className="sans" style={{ display: 'flex', gap: 8, fontSize: '0.84rem' }}>
<input type="checkbox" checked={form.servers.includes(s.id)} onChange={() => toggleServer(s.id)} />
{s.name || s.id}
</label>
))}
</fieldset>
<fieldset style={{ border: '1px solid var(--line-soft)', borderRadius: 8, padding: '10px 14px', display: 'grid', gap: 12 }}>
<legend className="sans" style={{ color: 'var(--head)', fontSize: '0.86rem', padding: '0 6px' }}>Flags</legend>
{(data.groups || []).length === 0 && (
<p className="sans dim" style={{ fontSize: '0.8rem', margin: 0 }}>
No server has reported its ZoneManager flags yet. They arrive when a server with ZoneManager connects.
</p>
)}
{(data.groups || []).map((g) => (
<div key={g.group}>
<div className="sans" style={{ fontSize: '0.8rem', color: 'var(--head)', marginBottom: 4 }}>{g.group}</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: '4px 12px' }}>
{g.flags.map((f) => {
const missing = missingOn.get(f.name)
return (
<label
key={f.name}
className="sans"
title={[f.note, missing ? `Not on ${missing.join(', ')}` : null].filter(Boolean).join(' ')}
style={{ display: 'flex', gap: 6, fontSize: '0.8rem', opacity: missing ? 0.55 : 1 }}
>
<input type="checkbox" checked={form.flags.includes(f.name)} onChange={() => toggleFlag(f.name)} />
{f.name}
{missing && <span className="dim">*</span>}
</label>
)
})}
</div>
</div>
))}
{missingOn.size > 0 && (
<p className="sans dim" style={{ fontSize: '0.74rem', margin: 0 }}>
* not on every server this preset is for. Hover for which.
</p>
)}
</fieldset>
<fieldset style={{ border: '1px solid var(--line-soft)', borderRadius: 8, padding: '10px 14px', display: 'grid', gap: 10 }}>
<legend className="sans" style={{ color: 'var(--head)', fontSize: '0.86rem', padding: '0 6px' }}>Settings</legend>
{(data.settings || []).map((s) => (
<label key={s.key} className="sans" style={{ display: 'grid', gap: 4, fontSize: '0.84rem' }}>
<span style={{ color: 'var(--head)' }}>{s.label}</span>
{s.type === 'boolean' ? (
<select value={form.settings[s.key] ?? ''} onChange={(e) => setSetting(s.key, e.target.value)} style={inputStyle}>
<option value="">Not set</option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
) : (
<input
value={form.settings[s.key] ?? ''}
onChange={(e) => setSetting(s.key, e.target.value)}
inputMode={s.type === 'float' ? 'decimal' : undefined}
placeholder={s.type === 'float' ? `${s.min} to ${s.max}` : ''}
style={{ ...inputStyle, maxWidth: 260 }}
/>
)}
<span className="dim" style={{ fontSize: '0.74rem' }}>{s.description}</span>
</label>
))}
</fieldset>
{error && <p className="sans" style={{ color: 'var(--danger, #d98b84)', fontSize: '0.84rem', margin: 0 }}>{error}</p>}
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button type="submit" className="btn" disabled={busy}>{busy ? 'Saving…' : 'Save'}</button>
<button type="button" className="btn" onClick={onCancel} disabled={busy}>Cancel</button>
{onDelete && (
<button type="button" className="btn" style={{ marginLeft: 'auto' }} onClick={onDelete} disabled={busy}>
Delete preset
</button>
)}
</div>
</form>
)
}

View File

@@ -0,0 +1,365 @@
// ── The player's own Rust identity ────────────────────────────────────────
//
// `/player/rust` — where a signed-in player links the Steam account they play
// on. It is the one page in this module a player is asked to *do* something on,
// and the thing they are doing matters more than it looks: from phase 7 the link
// is what in-game permissions are granted against, and from phase 13 it is what
// rewards are handed to.
//
// **A player route renders no layout of its own.** Core wraps `/player/*` in its
// own portal chrome, so this page starts at a heading — unlike the public pages
// in this module, which render `PublicLayout` themselves.
//
// The three-step instruction at the top is not decoration. Nothing else on the
// site tells a player that the code comes from the game, and a code field with no
// explanation is a code field nobody can use.
import { useCallback, useState } from 'react'
import { ErrorState, Loading, useAsync } from '../../core.js'
import { ago, shortId } from '../../lib/format.js'
import api from '../../api.js'
/** The code field, and the four answers it can produce. */
function LinkForm({ onLinked }) {
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState('')
const [error, setError] = useState('')
async function submit(event) {
event.preventDefault()
if (!code.trim() || busy) return
setBusy(true)
setMessage('')
setError('')
try {
const result = await api.playerLinks.confirm(code.trim())
setMessage(
result.already
? 'That account was already linked to you.'
: `Linked ${result.link.name || shortId(result.link.steamId)}.`,
)
setCode('')
await onLinked()
} catch (err) {
// Every refusal the server sends is already a sentence aimed at a player —
// "run /link again", "run /unlink in game", "try again in a minute" — so
// this renders it rather than replacing it with one of its own. The three
// are not interchangeable, and a page that flattened them into "could not
// link that code" would send a player back to the server that is down.
setError(err.message || 'Could not link that code.')
} finally {
setBusy(false)
}
}
return (
<form onSubmit={submit} style={{ marginTop: 18 }}>
<div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', flexWrap: 'wrap' }}>
<label style={{ display: 'block' }}>
<span className="field-label" style={{ display: 'block', marginBottom: 6 }}>Link code</span>
<input
value={code}
onChange={(e) => setCode(e.target.value.toUpperCase())}
placeholder="K7M2PQ"
// The plugin's alphabet has no O, 0, I or 1, so a player reading a
// code off their screen cannot produce one — but they can type a
// lowercase one, and the code is matched case-insensitively at the
// other end. Upper-casing here makes what they typed look like what
// they were shown.
maxLength={12}
autoComplete="off"
spellCheck={false}
className="input"
style={{ textTransform: 'uppercase', letterSpacing: '0.18em', width: 160 }}
/>
</label>
<button type="submit" className="btn" disabled={busy || !code.trim()}>
{busy ? 'Checking…' : 'Link account'}
</button>
</div>
{message && (
<p className="sans" style={{ color: '#7fd0a4', fontSize: '0.86rem', margin: '10px 0 0' }}>{message}</p>
)}
{error && (
<p className="sans" style={{ color: '#e05a5a', fontSize: '0.86rem', margin: '10px 0 0' }}>{error}</p>
)}
</form>
)
}
/** One linked account, and the control that releases it. */
function LinkRow({ link, onRemoved }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
async function remove() {
setBusy(true)
setError('')
try {
await api.playerLinks.remove(link.steamId)
await onRemoved()
} catch (err) {
setError(err.message || 'Could not unlink that account.')
setBusy(false)
}
}
return (
<li className="panel" style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14 }}>
<div style={{ minWidth: 0, flex: 1 }}>
<div className="display" style={{ fontSize: '1rem', color: 'var(--head)' }}>
{link.name || shortId(link.steamId)}
</div>
<div className="sans dim" style={{ fontSize: '0.76rem', marginTop: 2 }}>
{link.steamId} · linked {ago(link.linkedAt)}
{link.serverId ? ` on ${link.serverId}` : ''}
</div>
{error && (
<p className="sans" style={{ color: '#e05a5a', fontSize: '0.8rem', margin: '6px 0 0' }}>{error}</p>
)}
</div>
<button type="button" className="btn btn-ghost" onClick={remove} disabled={busy} style={{ flex: 'none' }}>
{busy ? 'Unlinking…' : 'Unlink'}
</button>
</li>
)
}
/**
* Where an entitlement has actually landed.
*
* The server resolves the scope and marks each server, so this renders an answer
* rather than working one out — `*` means nothing to a player, and a second
* implementation of the scope arithmetic on the client is a second thing to keep
* true (see `forPlayer` in the permission model).
*/
function Reach({ reach }) {
if (!reach.length) {
return (
<span className="sans dim" style={{ fontSize: '0.76rem' }}>
No servers are configured yet
</span>
)
}
return (
<div className="sans" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, fontSize: '0.76rem' }}>
{reach.map((server) => (
<span
key={server.id}
style={{
border: '1px solid var(--line, rgba(255,255,255,0.14))',
borderRadius: 999,
padding: '2px 10px',
color: server.live ? 'var(--head)' : undefined,
opacity: server.live ? 1 : 0.65,
}}
>
{/* The word, not only the dot. A filled circle beside a hollow one is
the whole difference between "you have this in game" and "you do
not yet", which is more than a shape should have to carry — and a
reader who cannot tell the two apart gets no answer at all. */}
{server.live ? '● ' : '○ '}
{server.name} · {server.live ? 'has it' : 'waiting'}
</span>
))}
</div>
)
}
/** One group or one direct grant, drawn the same way because they read the same. */
function HeldRow({ title, subtitle, permissions, reach }) {
return (
<li className="panel" style={{ padding: '14px 16px' }}>
<div className="display" style={{ fontSize: '1rem', color: 'var(--head)' }}>{title}</div>
{subtitle && (
<div className="sans dim" style={{ fontSize: '0.76rem', marginTop: 2 }}>{subtitle}</div>
)}
{permissions && permissions.length > 0 && (
<div className="sans dim" style={{ fontSize: '0.78rem', marginTop: 8 }}>
{permissions.join(' · ')}
</div>
)}
<div style={{ marginTop: 10 }}>
<Reach reach={reach} />
</div>
</li>
)
}
/**
* What the site has given this player in game.
*
* Its own read, not part of the links read: an entitlement exists whether or not
* a Steam account is linked, and a player who has just been given something and
* has not linked yet is exactly the person who needs to see both halves at once.
*/
function Held({ accounts }) {
const { data, loading, error } = useAsync(() => api.playerPermissions.list(), [])
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
const groups = data.groups || []
const grants = data.grants || []
if (!groups.length && !grants.length) {
return (
<p className="sans dim" style={{ fontSize: '0.8rem', margin: 0, maxWidth: '60ch' }}>
Nothing yet. Ranks and rewards this site hands out show up here, and reach you in game on
the servers they cover.
</p>
)
}
const waiting = [...groups, ...grants].some((entry) => entry.reach.some((server) => !server.live))
return (
<>
<ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{groups.map((group) => (
<HeldRow
key={`group:${group.name}`}
title={group.title}
subtitle={`Rank · joined ${ago(group.since)}`}
permissions={group.permissions}
reach={group.reach}
/>
))}
{grants.map((grant) => (
<HeldRow
key={`grant:${grant.permission}:${grant.scope}`}
title={grant.permission}
subtitle={grant.note || `Granted ${ago(grant.since)}`}
reach={grant.reach}
/>
))}
</ul>
{accounts === 0 && (
<p className="sans dim" style={{ fontSize: '0.76rem', marginTop: 12, maxWidth: '60ch' }}>
None of this reaches the game yet — link a Steam account above and the site pushes it
across on its next sync.
</p>
)}
{accounts > 0 && waiting && (
<p className="sans dim" style={{ fontSize: '0.76rem', marginTop: 12, maxWidth: '60ch' }}>
A server marked <em>waiting</em> has not confirmed it yet. One that is offline catches up
when it comes back.
</p>
)}
</>
)
}
/**
* RunicNPC (runicnpc stage 4, D252): your kills of each NPC profile, this wipe,
* by server, across every Steam account you have linked. Nothing without a link.
*/
function NpcKills() {
const { data, loading, error } = useAsync(() => api.playerNpcKills.list(), [])
if (loading) return <Loading />
if (error) return <ErrorState error={error} />
const rows = (data && data.kills) || []
if (rows.length === 0) {
return <p className="sans dim" style={{ fontSize: '0.8rem', margin: 0 }}>None this wipe.</p>
}
const byServer = new Map()
for (const r of rows) byServer.set(r.server || r.serverId, [...(byServer.get(r.server || r.serverId) || []), r])
return (
<ul className="sans" style={{ listStyle: 'none', margin: 0, padding: 0, fontSize: '0.86rem', display: 'grid', gap: 6 }}>
{[...byServer.entries()].map(([serverId, list]) => (
<li key={serverId}>
<span className="dim">{serverId}: </span>
{list.map((k, i) => (
<span key={k.profile}>
{i > 0 && <span className="dim"> · </span>}
{k.label} <strong>{k.kills}</strong>
</span>
))}
</li>
))}
</ul>
)
}
export default function Account() {
// `useAsync` rather than this module's `usePolled`: nothing here changes unless
// the person looking at it changes it, and a page that re-asked every twenty
// seconds would be asking a question nobody is waiting on.
//
// **Core's `useAsync` has no `refresh`** — it re-runs when its deps change and
// that is the whole of its interface — so a counter in the deps is how a page
// re-reads after its own write. It blanks while it re-reads, which is right
// here and is exactly what made it wrong for a poll (see `hooks/usePolled.js`).
const [reloads, setReloads] = useState(0)
const { data, loading, error } = useAsync(() => api.playerLinks.list(), [reloads])
const links = data ? data.links : []
const reload = useCallback(() => setReloads((n) => n + 1), [])
return (
<div>
<div className="field-label" style={{ marginBottom: 12 }}>Steam accounts</div>
<p className="sans dim" style={{ margin: 0, fontSize: '0.86rem', maxWidth: '60ch' }}>
Linking tells this site which Steam account is yours, so your play on our servers appears
under your name here — and so rewards and permissions the site hands out can reach you in
game.
</p>
<ol className="sans dim" style={{ fontSize: '0.86rem', marginTop: 14, paddingLeft: 20, maxWidth: '60ch' }}>
<li>Join any of our Rust servers and type <code>/link</code> in chat.</li>
<li>The server replies with a six-character code, only you can see it, and it lasts five minutes.</li>
<li>Type it below. It works once.</li>
</ol>
<LinkForm onLinked={reload} />
{loading && <Loading />}
{error && <ErrorState error={error} />}
{data && links.length > 0 && (
<ul style={{ listStyle: 'none', margin: '22px 0 0', padding: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{links.map((link) => (
<LinkRow key={link.steamId} link={link} onRemoved={reload} />
))}
</ul>
)}
{data && links.length > 0 && (
<p className="sans dim" style={{ fontSize: '0.76rem', marginTop: 14, maxWidth: '60ch' }}>
A link covers every server this community runs — a Steam account is one person wherever
they play, while stats are kept per server and per wipe. You can also type
{' '}<code>/unlink</code> in game to release one.
</p>
)}
{data && links.length === 0 && (
<p className="sans dim" style={{ fontSize: '0.8rem', marginTop: 18 }}>
No Steam account is linked to this profile yet.
</p>
)}
{/* Phase 8. Rendered whether or not anything is linked: an entitlement is
authored against the website account, so it exists before a Steam id
does — and hiding it until one appears is the mistake the admin user
page shipped in phase 7 (PLAN.md §20.5). */}
<div className="field-label" style={{ margin: '30px 0 12px' }}>What you can do in game</div>
{data && <Held accounts={links.length} />}
<div className="field-label" style={{ margin: '30px 0 12px' }}>NPCs you have killed</div>
{data && links.length > 0 ? <NpcKills /> : <p className="sans dim" style={{ fontSize: '0.8rem', margin: 0 }}>Link a Steam account to see them.</p>}
</div>
)
}

View File

@@ -0,0 +1,161 @@
// ── One clan ──────────────────────────────────────────────────────────────
//
// A first-party Rust clan is a Team (R5), and this is its page. Core owns the
// Team — the reconciler, the access rules, the activity feed, the forum — but
// not the word "clan", so it publishes no Team page of its own (MODULE_API.md
// §3.7a). The page is this module's, and the three parts only core can render
// are contributed into places this page names:
//
// rust.clan.header ← core's `team.notify` (above the roster: an action ON the page)
// rust.clan.detail ← core's `team.activity` (the members-only feed, D49)
// rust.clan.forum ← core's `team.forum`
//
// One slot per PLACE, as module-uo does, so core never decides the layout of a
// page it does not own. **Every slot may be empty** — a core without Teams, a
// deployment with the forum switched off, a clan whose Team core has not created
// yet — and the page has to read correctly anyway. That is the phase criterion,
// and it is why nothing here says "see below" about something core may not put
// below.
//
// The roster comes from this module's own board, through the same function core
// asks when it projects a roster (D48), so the two cannot disagree about who may
// look. Below the audience the clan is still described — its name, score and
// count are public (D58) — and the roster says who may see it instead.
import { useParams, Link } from 'react-router-dom'
import { ErrorState, Loading, PageHeader, PublicLayout, Slot, useAsync } from '../../core.js'
import Empty from '../../components/Empty.jsx'
import { Swatch } from '../../components/Clans.jsx'
import { count, day } from '../../lib/format.js'
import api from '../../api.js'
const ID = 'rust'
export default function Clan() {
const { externalId } = useParams()
const { data, loading, error } = useAsync(() => api.clans.get(externalId), [externalId])
if (loading) {
return (
<PublicLayout shell="mid">
<Loading />
</PublicLayout>
)
}
// A mistyped or out-of-date address is not an outage, and must not read as
// one — the same rule the server page learned in phase 4.
if (error || !data || !data.clan) {
const missing = !error || error.status === 404
return (
<PublicLayout shell="mid">
<PageHeader
title={missing ? 'No such clan' : 'That clan could not be loaded'}
lead={
missing
? 'This address does not name a clan this site knows about.'
: 'The site could not read this clan just now. It is worth trying again.'
}
/>
{!missing && <ErrorState error={error} />}
<p className="sans" style={{ marginTop: 20 }}>
<Link to="/rust">Back to the server list</Link>
</p>
</PublicLayout>
)
}
const { clan, roster } = data
const serverLink = `/rust/servers/${encodeURIComponent(clan.serverId)}?tab=clans`
return (
<PublicLayout shell="mid">
<p className="sans" style={{ margin: '0 0 12px' }}>
<Link to={serverLink}>← Clans on {clan.serverName || clan.serverId}</Link>
</p>
<PageHeader eyebrow="Rust clan" title={clan.name} lead={describe(clan)} />
{clan.gone && (
<p className="sans" style={{ color: 'var(--dim)', marginTop: 0 }}>
This clan has been disbanded, or has left its server’s clan list. What is shown is the last the site heard.
</p>
)}
<Slot name="rust.clan.header" externalId={clan.externalId} moduleId={ID} />
<h2 className="sans" style={{ fontSize: '1rem', margin: '24px 0 8px' }}>Members</h2>
<Roster roster={roster} memberCount={clan.memberCount} gone={clan.gone} />
<Slot name="rust.clan.detail" externalId={clan.externalId} moduleId={ID} />
<Slot name="rust.clan.forum" externalId={clan.externalId} moduleId={ID} />
</PublicLayout>
)
}
function describe(clan) {
const parts = [
<Swatch key="c" color={clan.color} />,
` ${count(clan.memberCount)} ${clan.memberCount === 1 ? 'member' : 'members'}`,
clan.maxMembers ? ` of ${count(clan.maxMembers)}` : '',
` · ${count(clan.score)} points`,
clan.founded ? ` · founded ${day(clan.founded)}` : '',
]
return <span>{parts}</span>
}
function Roster({ roster, memberCount, gone }) {
if (!roster || !roster.visible) {
return <Empty title={`${count(memberCount)} ${memberCount === 1 ? 'member' : 'members'}`} message={withheld(roster && roster.audience)} />
}
if (roster.members.length === 0) {
return gone
? <Empty title="No roster" message="A clan that has left its server’s list has no members to show." />
: <Empty title="No roster yet" message="The server has not sent this clan’s members yet." />
}
return (
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{roster.members.map((m, i) => (
<li
// The roster carries no identifier on purpose (a Steam id and a site
// account are withheld from every public roster), so the row's place is
// its key. The list is re-rendered whole, never reordered in place.
// eslint-disable-next-line react/no-array-index-key
key={i}
style={{
display: 'flex',
alignItems: 'baseline',
gap: 12,
padding: '8px 0',
borderBottom: '1px solid var(--line-soft, var(--line))',
}}
>
<strong style={{ color: 'var(--ink)', flex: 1, minWidth: 0 }}>
{m.name || 'Unknown player'}
{m.leader && (
<span className="sans" style={{ color: 'var(--accent)', marginLeft: 8, fontSize: '0.72rem' }}>Leader</span>
)}
</strong>
{m.role && !m.leader && (
<span className="sans" style={{ color: 'var(--dim)', fontSize: '0.8rem' }}>{m.role}</span>
)}
{/* Inside the roster audience by construction (D48): a viewer who may
not see the roster sees no row to hang this on. */}
<span className="sans" style={{ color: m.online ? 'var(--mode-live, #5fb98a)' : 'var(--dim)', fontSize: '0.78rem', whiteSpace: 'nowrap' }}>
{m.online ? 'online' : ''}
</span>
</li>
))}
</ul>
)
}
/** Why the roster was withheld, in words a visitor can act on. */
function withheld(audience) {
if (audience === 'signed_in') return 'Sign in to see who is in this clan.'
if (audience === 'public') return 'This site is not showing clan rosters right now.'
return 'Only this clan’s own members, with a linked Rust account, and this site’s staff can see who is in it.'
}

View File

@@ -0,0 +1,195 @@
// ── One server ────────────────────────────────────────────────────────────
//
// R8's page beneath the landing page, and the phase-4 criterion lives here: it
// renders the last thing this server said while every server is off. Nothing on
// it is a live call to a game host — every panel reads this module's own tables,
// filled by the ingest cursor — so a shard that has been down for a week renders
// a week-old killfeed and a leaderboard that is still correct, rather than an
// error page.
//
// ── Everything selectable is in the URL ───────────────────────────────────
//
// Tab, feed filter, wipe and leaderboard sort all live in search parameters.
// That costs a little ceremony here and buys the thing a community site is for:
// "look at last wipe's leaderboard on Main" is a LINK. State held in `useState`
// would make every one of those sentences unlinkable, lose the reader's place on
// a refresh, and make the browser's back button leave the page instead of
// undoing what they just clicked.
//
// `useSearchParams` comes from CORE's router (the shim in `src/shim/`), so it is
// the same live navigation context core's own pages use. A module with its own
// copy of react-router would get a `useParams` that returns nothing on a page
// that otherwise renders perfectly — see `core.js`'s identity check.
import { useSearchParams, useParams, Link } from 'react-router-dom'
import { ErrorState, Loading, PageHeader, PublicLayout, useAsync } from '../../core.js'
import Clans from '../../components/Clans.jsx'
import Feed from '../../components/Feed.jsx'
import Leaderboard from '../../components/Leaderboard.jsx'
import MapView from '../../components/MapView.jsx'
import Online from '../../components/Online.jsx'
import Tabs from '../../components/Tabs.jsx'
import WipeSelect, { ALL_TIME } from '../../components/WipeSelect.jsx'
import Wipes from '../../components/Wipes.jsx'
import { ago, count, day, nextWipe } from '../../lib/format.js'
import api from '../../api.js'
const TABS = [
{ id: 'feed', label: 'Feed' },
{ id: 'leaderboard', label: 'Leaderboard' },
{ id: 'online', label: 'Online' },
// Phase 14. The picture is public; what moves on it has an audience per layer.
{ id: 'map', label: 'Map' },
{ id: 'wipes', label: 'Wipes' },
// Phase 9. The list is public (D58); each clan's roster is on its own page.
{ id: 'clans', label: 'Clans' },
]
export default function ServerDetail() {
const { id } = useParams()
const [params, setParams] = useSearchParams()
const { data, loading, error } = useAsync(() => api.servers.get(id), [id])
const server = data ? data.server : null
const tab = TABS.some((t) => t.id === params.get('tab')) ? params.get('tab') : 'feed'
const filter = params.get('show') || 'all'
const sort = params.get('sort') || 'kills'
// `wipe` absent means all time; `wipe=current` means whatever wipe the server
// is on now, which is a moving target and therefore a word rather than an id —
// a link somebody shares stays about "now" rather than about the map that was
// current when they sent it.
const wipeParam = params.get('wipe')
const wipeId = !wipeParam || wipeParam === ALL_TIME ? null : wipeParam === 'current' ? (server && server.wipeId) || null : wipeParam
const set = (key, value) => {
const next = new URLSearchParams(params)
if (!value || value === 'all' || (key === 'tab' && value === 'feed')) next.delete(key)
else next.set(key, value)
// `replace` so that flipping between tabs does not fill the reader's history
// with one entry per click — back should leave the page they arrived on.
setParams(next, { replace: true })
}
if (loading) {
return (
<PublicLayout shell="mid">
<Loading />
</PublicLayout>
)
}
// A 404 from the detail route is the one answer the other four cannot give:
// an unknown id has no events, no leaderboard and nobody online, and each of
// those empty lists is a perfectly good answer to its own question. So this is
// where "there is no such server" is said.
//
// **A mistyped address is not a fault, and must not be dressed as one.** The
// first version of this page rendered core's `ErrorState` under the heading and
// the result read "No such server / Something went wrong" — which sends a
// reader who fat-fingered a URL looking for an outage. `ErrorState` is kept for
// the case it is for: a request that failed for a reason nobody can see.
if (error || !server) {
const missing = !error || error.status === 404
return (
<PublicLayout shell="mid">
<PageHeader
title={missing ? 'No such server' : 'That server could not be loaded'}
lead={
missing
? 'This address does not name a server this site follows.'
: 'The site could not read this server just now. It is worth trying again.'
}
/>
{!missing && <ErrorState error={error} />}
<p className="sans" style={{ marginTop: 20 }}>
<Link to="/rust">Back to the server list</Link>
</p>
</PublicLayout>
)
}
return (
<PublicLayout shell="mid">
<PageHeader
eyebrow="Rust"
title={server.name}
lead={describeWorld(server)}
/>
<div
className="sans"
style={{ display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'baseline', marginBottom: 24 }}
>
<span style={{ color: server.online ? 'var(--mode-live, #5fb98a)' : 'var(--dim)' }}>
{server.online
? `${count(server.players)}${server.maxPlayers ? ` / ${count(server.maxPlayers)}` : ''} online`
: 'Offline'}
</span>
{/* `lastSeenAt` is when a frame arrived; `updatedAt` is when this site
last wrote the row, which a FAILED poll does too. Reading the second
as the first is what made an offline server claim it had reported just
now, every thirty seconds, for as long as it stayed down. */}
<span style={{ color: 'var(--dim)', fontSize: '0.8rem' }}>
{server.lastSeenAt ? `last reported ${ago(server.lastSeenAt)}` : 'has never reported'}
{server.stale && server.lastSeenAt ? ' — out of date, so it is shown as offline' : ''}
</span>
<span style={{ marginLeft: 'auto' }}>
<WipeSelect
serverId={server.id}
value={wipeParam}
currentWipeId={server.wipeId}
onChange={(value) => set('wipe', value === ALL_TIME ? null : value)}
/>
</span>
</div>
<Tabs tabs={TABS} active={tab} onSelect={(next) => set('tab', next)} label={`${server.name} sections`} />
{tab === 'feed' && (
<Feed serverId={server.id} wipeId={wipeId} filter={filter} onFilter={(value) => set('show', value)} />
)}
{tab === 'leaderboard' && (
<Leaderboard serverId={server.id} wipeId={wipeId} sort={sort} onSort={(value) => set('sort', value)} />
)}
{tab === 'online' && <Online serverId={server.id} online={server.online} />}
{tab === 'map' && <MapView serverId={server.id} online={server.online} />}
{tab === 'clans' && <Clans serverId={server.id} />}
{tab === 'wipes' && (
<Wipes
serverId={server.id}
currentWipeId={server.wipeId}
selected={wipeId}
// Picking a wipe here is a navigation as much as a filter: it is the
// question "what happened during that map", and the answer is the feed.
onSelect={(value) => {
const next = new URLSearchParams(params)
next.set('wipe', value)
next.delete('tab')
setParams(next, { replace: true })
}}
/>
)}
</PublicLayout>
)
}
/** The world line under the heading — the things a Rust player asks first. */
function describeWorld(server) {
const parts = [
server.level || null,
server.worldSize ? `size ${count(server.worldSize)}` : null,
server.seed ? `seed ${server.seed}` : null,
server.wipedAt ? `wiped ${day(server.wipedAt)}` : null,
nextWipe(server.nextWipe) ? `next wipe ${nextWipe(server.nextWipe)}` : null,
].filter(Boolean)
return parts.length > 0 ? parts.join(' · ') : 'This server has not described itself yet.'
}

View File

@@ -1,43 +1,46 @@
// ── The server list ───────────────────────────────────────────────────────
// ── The server list, and the module's landing page ────────────────────────
//
// R8: the list is what `/rust` renders, and `/rust/servers/:id` hangs beneath
// it. The route is registered with an empty path in `entry.jsx` — core turns
// that into the module's own namespace root — so this page's address is the one
// an operator links to when they mean "our Rust servers".
//
// An ordinary React component. Nothing about being inside a module changes how
// you write one — the only differences are where React comes from (core, via the
// you write one; the only differences are where React comes from (core, via the
// aliases in `vite.config.js`, so the import below looks completely normal and is
// not) and where the chrome comes from (`../../core.js`, the shared UI kit).
//
// **Render `PublicLayout` yourself.** Core wraps public routes in its maintenance
// gate and nothing else, so a page that omits the layout renders bare — no
// header, no footer, no site chrome — which looks like a bug and is the contract
// (§3.3). Admin and player routes are the other way round: core wraps those.
// **Render `PublicLayout` yourself, and pass a `shell`.** Core wraps public
// routes in its maintenance gate and nothing else, so a page that omits the
// layout renders bare; without a `shell` it renders full-bleed with the footer
// riding up underneath it. Name a width, never a class — the classes are core's
// (MODULE_API.md §3.3).
//
// **And pass a `shell`.** The layout is the chrome; `shell` is the body — the
// centred column, the vertical padding, and the thing that holds the footer at
// the bottom of the viewport. Widths are 'narrow', 'mid' and 'wide'; name a
// width, never a class, because the classes belong to core's stylesheet.
//
// This is the phase-1 version of the landing page R8 calls for. It lists servers
// and links nowhere yet — `/rust/servers/:id` is the next phase's work — so it is
// deliberately a table and not a design.
// **This page never calls a game server.** Every field it renders comes from
// this module's own tables, written by the ingest cursor, which is what lets it
// render "offline, last seen an hour ago" instead of an error page when a shard
// is down. The site's availability does not depend on the game's.
import { EmptyState, ErrorState, Loading, PageHeader, PublicLayout, useAsync } from '../../core.js'
import { Link } from 'react-router-dom'
import { ErrorState, Loading, PageHeader, PublicLayout, useAsync } from '../../core.js'
import Empty from '../../components/Empty.jsx'
import { ago, count, day, nextWipe } from '../../lib/format.js'
import api from '../../api.js'
// A relative time that does not need a date library. `Intl.RelativeTimeFormat`
// is in every browser core supports, and one fewer dependency in the chunk is
// one fewer thing an operator ships.
const RELATIVE = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' })
function ago(iso) {
if (!iso) return 'never'
const seconds = Math.round((new Date(iso).getTime() - Date.now()) / 1000)
const [unit, size] = Math.abs(seconds) < 3600 ? ['minute', 60] : ['hour', 3600]
return RELATIVE.format(Math.round(seconds / size), unit)
/** The "last reported" line, which has three cases and not one. */
function reported(server) {
if (!server.lastSeenAt) return 'This server has never reported.'
if (server.stale) return `Last reported ${ago(server.lastSeenAt)} — out of date, so it is shown as offline.`
return `Last reported ${ago(server.lastSeenAt)}.`
}
export default function Servers() {
// `useAsync` is core's fetch/loading/error hook, and the components below are
// its states. Using them rather than rolling your own is what makes a module
// page indistinguishable from a core one while it loads and while it fails.
//
// It loads once, deliberately. The DETAIL page polls, because that is where
// somebody watching a server sits; a list is a place people pass through.
const { data, loading, error } = useAsync(() => api.servers.list(), [])
const servers = data ? data.servers : []
@@ -59,44 +62,64 @@ export default function Servers() {
empty game — it is an install that is not finished. Saying so beats a
blank page that looks like a failure. */}
{data && servers.length === 0 && (
<EmptyState
<Empty
title="No servers yet"
message="An administrator adds a Rust server, and its sidecar, from the admin panel."
/>
)}
{servers.length > 0 && (
<div style={{ display: 'grid', gap: '0.75rem' }}>
<div style={{ display: 'grid', gap: 12 }}>
{servers.map((server) => (
<div
// The whole row is the link. A server's name being the only clickable
// part is the thing people miss on a list of cards, and `a.card`
// already carries core's own hover treatment.
<Link
key={server.id}
to={`/rust/servers/${encodeURIComponent(server.id)}`}
className="card"
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'baseline',
gap: '1rem',
padding: '0.75rem 0',
borderBottom: '1px solid rgba(128,128,128,0.25)',
padding: '16px 20px',
}}
>
<div>
<strong>{server.name}</strong>
{server.level ? <span style={{ opacity: 0.7 }}> · {server.level}</span> : null}
<div style={{ opacity: 0.7, fontSize: '0.9em' }}>
{/* `stale` is a first-class part of the answer rather than
something the page infers from a timestamp. The server
decides what counts as stale, because the server is what
knows how often a sidecar is supposed to check in. */}
Last reported {ago(server.updatedAt)}
{server.stale ? ' — out of date, so it is shown as offline.' : '.'}
</div>
</div>
<div style={{ whiteSpace: 'nowrap' }}>
<span>
<strong style={{ color: 'var(--ink)' }}>{server.name}</strong>
<span className="sans" style={{ display: 'block', color: 'var(--dim)', fontSize: '0.78rem', marginTop: 4 }}>
{[
server.level || null,
server.worldSize ? `size ${count(server.worldSize)}` : null,
server.wipedAt ? `wiped ${day(server.wipedAt)}` : null,
// Phase 16 (D131): absent from an older module, and null for a
// server with no schedule — either way the part is left out.
nextWipe(server.nextWipe) ? `next wipe ${nextWipe(server.nextWipe)}` : null,
]
.filter(Boolean)
.join(' · ')}
</span>
<span className="sans" style={{ display: 'block', color: 'var(--dim)', fontSize: '0.74rem', marginTop: 2 }}>
{/* `lastSeenAt`, never `updatedAt`. The second is when THIS
site last wrote the row — which a failed poll does too — so
a page reading it told a reader that a server down for three
days had reported just now. And `stale` is a first-class
part of the answer rather than something inferred from a
timestamp: the server decides what counts as stale, because
the server knows how often a sidecar is supposed to check in. */}
{reported(server)}
</span>
</span>
<span
className="sans"
style={{ whiteSpace: 'nowrap', color: server.online ? 'var(--mode-live, #5fb98a)' : 'var(--dim)' }}
>
{server.online
? `${server.players}${server.maxPlayers ? ` / ${server.maxPlayers}` : ''} online`
? `${count(server.players)}${server.maxPlayers ? ` / ${count(server.maxPlayers)}` : ''} online`
: 'Offline'}
</div>
</div>
</span>
</Link>
))}
</div>
)}

View File

@@ -19,7 +19,7 @@ import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const CLIENT = path.resolve(HERE, '..')
const { bareImports, problemsWith } = await import('../scripts/checkExternals.js')
const { bareImports, problemsWith, relativeImports } = await import('../scripts/checkExternals.js')
const configModule = await import('../vite.config.js')
const config = configModule.default
const { SHARED, SHARED_PACKAGES: guardedPackages } = configModule
@@ -152,3 +152,38 @@ test('an import inside a string is not an import — the check reads code, not t
// string must not end it early and leave the tail looking like code.
assert.deepStrictEqual(bareImports('const s="he said \\"import\\" loudly";'), [])
})
// ── D120: Leaflet's split chunk ───────────────────────────────────────────
test('a split chunk is found by what entry.js imports, and a string is still not an import', () => {
assert.deepStrictEqual(relativeImports('const m=await import("./leaflet-Ab12.js")'), ['leaflet-Ab12.js'])
assert.deepStrictEqual(relativeImports('import"./other.js";import"react"'), ['other.js'])
assert.deepStrictEqual(relativeImports('const s="import(\\"./fake.js\\")"'), [])
})
test('every chunk entry.js imports is in dist/, and none of them bundles a shared dependency', () => {
const dist = path.join(CLIENT, 'dist')
const entry = path.join(dist, 'entry.js')
if (!fs.existsSync(entry)) return
const split = relativeImports(fs.readFileSync(entry, 'utf8'))
assert.ok(split.length >= 1, 'the Map tab imports Leaflet from a chunk of its own (D120)')
for (const name of split) {
assert.ok(fs.existsSync(path.join(dist, name)), `entry.js imports ./${name}, which the build did not emit`)
assert.deepStrictEqual(problemsWith(fs.readFileSync(path.join(dist, name), 'utf8')), [], name)
}
})
test('Leaflet is not in the entry chunk — every page of the site loads that one', () => {
const entry = path.join(CLIENT, 'dist', 'entry.js')
if (!fs.existsSync(entry)) return
assert.doesNotMatch(fs.readFileSync(entry, 'utf8'), /Leaflet 1\.9/, 'Leaflet was bundled into entry.js')
})
test('the release ships every chunk, not entry.js by name', () => {
// The other half of D120. A release that copied `entry.js` alone would load on
// every page and spin for ever on the Map tab, with every check above green.
const release = fs.readFileSync(path.join(CLIENT, '..', '.gitea', 'workflows', 'release.yml'), 'utf8')
assert.match(release, /cp client\/dist\/\*\.js "\$OUT\/client\/dist\/"/)
assert.doesNotMatch(release, /cp client\/dist\/entry\.js /)
})

142
client/test/feed.test.js Normal file
View File

@@ -0,0 +1,142 @@
// ── The feed's sentences ──────────────────────────────────────────────────
//
// `lib/feed.js` is the one part of the client half with real branching in it, and
// it is pure on purpose so that a DOM-less runner can ask all of it. Everything
// here is a claim about what a reader sees for a given frame — which is exactly
// the kind of thing that rots silently, because a wrong killfeed line is still a
// killfeed line.
//
// The fixtures are the frames the bridge plugin actually emits (its
// `DescribeAttacker`, and PROTOCOL.md §8.4), not invented shapes.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
import { describe, FEED_KINDS, FILTERS, kindsFor } from '../src/lib/feed.js'
const row = (kind, frame = {}) => ({ id: 1, kind, t: Date.now(), wipeId: 'w1', steamId: '7656', frame })
test('a player kill names the killer and the victim, in that order', () => {
const line = describe(row('player.death', {
name: 'Bob',
attackerType: 'player',
attackerName: 'Alice',
weapon: 'rifle.ak',
distance: 42.4,
grid: 'H7',
}))
assert.equal(line.tone, 'kill')
assert.equal(line.actor, 'Alice')
assert.equal(line.verb, 'killed')
assert.equal(line.subject, 'Bob')
assert.match(line.detail, /rifle ak/)
assert.match(line.detail, /42m/)
assert.match(line.detail, /H7/)
})
test('the four attacker types are four different sentences', () => {
// The plugin distinguishes them precisely so a reader does not have to guess
// from an absent field, and collapsing any two loses something: a fall reported
// as a kill by nobody is the failure this prevents.
const victim = { name: 'Bob' }
const npc = describe(row('player.death', { ...victim, attackerType: 'npc', attackerName: 'scientistnpc_full_any' }))
// A family is named, not spelled out as a prefab (PLAN_FIXES F2, D185).
assert.equal(npc.actor, 'Scientist')
assert.equal(npc.subject, 'Bob')
const self = describe(row('player.death', { ...victim, attackerType: 'self' }))
assert.equal(self.actor, 'Bob')
assert.equal(self.subject, null)
assert.match(self.verb, /own hand/)
const environment = describe(row('player.death', { ...victim, attackerType: 'environment' }))
assert.equal(environment.actor, 'Bob')
assert.equal(environment.verb, 'died')
assert.equal(environment.subject, null)
// `HitInfo` is legitimately null on the environment path, so a death frame with
// NO attacker type at all is that case — not a missing field to render around.
const bare = describe(row('player.death', victim))
assert.equal(bare.verb, 'died')
assert.equal(bare.subject, null)
})
test('a sleeping victim is said to have been sleeping', () => {
const line = describe(row('player.death', { name: 'Bob', attackerType: 'player', attackerName: 'Alice', sleeping: true }))
assert.match(line.detail, /while sleeping/)
})
test('a disconnect with no session length says nothing about one', () => {
// The plugin OMITS `sessionSec` for a player who was already on when it loaded:
// an unknown session is not a session of no length. A line reading "after 0s"
// would be a lie this module invented.
const unknown = describe(row('player.disconnected', { name: 'Bob', reason: 'Quit' }))
assert.equal(unknown.detail, 'Quit')
const known = describe(row('player.disconnected', { name: 'Bob', reason: 'Quit', sessionSec: 3720 }))
assert.equal(known.detail, 'Quit · after 1h 2m')
})
test('a chat line carries the message as text, never as markup', () => {
// The message is the one field on this wire whose bytes a player chooses. It
// comes back as a STRING and is rendered as a React child, which escapes it;
// this test is here so that a later "render the message with formatting" idea
// has to delete an explicit assertion rather than quietly change behaviour.
const line = describe(row('player.chat', { name: 'Bob', message: '<img src=x onerror=alert(1)>', channel: 'Global' }))
assert.equal(line.verb, '<img src=x onerror=alert(1)>')
assert.equal(typeof line.verb, 'string')
// Global is the default channel and saying so on every line is noise; Team is
// information.
assert.equal(line.detail, '')
assert.equal(describe(row('player.chat', { name: 'B', message: 'hi', channel: 'Team' })).detail, 'Team')
// A chat row is the one line where the actor is a speaker rather than a
// subject, and "Brannock see you in september" is not a sentence anybody
// writes. The colon is presentation, so it lives here and not inside the text
// the player typed.
assert.equal(line.join, ': ')
assert.equal(describe(row('player.connected', { name: 'B' })).join, undefined)
})
test('an unknown kind renders as itself rather than vanishing', () => {
// A later protocol adds kinds, and a module may be older than the game host it
// is reading. The server's allowlist has already decided the row may be seen;
// dropping it here would make the page quietly say less than the truth.
const line = describe(row('player.teleported', { name: 'Bob' }))
assert.equal(line.verb, 'player.teleported')
assert.equal(line.tone, 'other')
})
test('the feed never asks for the aggregate kind', () => {
// `player.tally` is public and is flushed once a minute per active player
// (§8.6). A feed that included it would be mostly wood counts; it is the
// leaderboard's input, and that is where it shows up.
assert.ok(!FEED_KINDS.includes('player.tally'))
for (const filter of FILTERS) {
for (const kind of filter.kinds) {
assert.ok(FEED_KINDS.includes(kind), `filter "${filter.id}" asks for ${kind}, which the feed does not carry`)
}
}
})
test('every kind the feed asks for is one the public route will serve', () => {
// Held against the module's own allowlist rather than against a copy of it: a
// kind this file asked for and `server/catalogue.js` refuses is a filter that
// silently returns nothing, which reads as a quiet server.
//
// A CommonJS file from the server half, read by an ESM test through
// `createRequire`. Crossing the two halves is fine HERE and nowhere else:
// `test/` is not shipped, and `scripts/checkImports.js` governs what is.
const catalogue = createRequire(import.meta.url)('../../server/catalogue.js')
for (const kind of FEED_KINDS) {
assert.ok(catalogue.PUBLIC_KINDS.includes(kind), `the feed asks for ${kind}, which is not public`)
}
})
test('an unknown filter falls back to everything rather than to nothing', () => {
assert.deepEqual(kindsFor('nonsense'), FEED_KINDS)
assert.deepEqual(kindsFor(undefined), FEED_KINDS)
})

142
client/test/format.test.js Normal file
View File

@@ -0,0 +1,142 @@
// ── Formatting ────────────────────────────────────────────────────────────
//
// Small functions, and the tests are small too — but three of them guard claims
// that would otherwise be made by a page that looks fine: an unknown duration
// rendered as zero, a timestamp in the wrong unit, and "in 0 seconds".
//
// Locale-dependent output is asserted loosely on purpose. `Intl` formats to the
// RUNNER's locale, and a test pinned to "3 minutes ago" would be a test that
// fails on a machine set to French while the page it describes is correct.
import test from 'node:test'
import assert from 'node:assert/strict'
import { ago, attacker, clock, contrastInk, count, day, duration, nextWipe, prefab, shortId } from '../src/lib/format.js'
const NOW = Date.parse('2026-09-16T12:00:00Z')
test('a relative time picks the unit that fits', () => {
assert.match(ago(NOW - 3 * 60_000, NOW), /3/)
assert.match(ago(NOW - 5 * 3600_000, NOW), /5/)
assert.match(ago(NOW - 3 * 86400_000, NOW), /3/)
})
test('"just now" rather than "in 0 seconds"', () => {
// What `numeric: 'auto'` produces under a minute is not what anybody means,
// and a feed row a few seconds old is the commonest row on the page.
assert.equal(ago(NOW, NOW), 'just now')
assert.equal(ago(NOW - 10_000, NOW), 'just now')
})
test('both time shapes this module serves are accepted', () => {
// `updatedAt` is an ISO string the model produced; an event's `t` is the
// millisecond stamp the plugin put on the frame. A helper that took only one
// would be a helper every caller has to remember the type for.
assert.equal(ago('2026-09-16T11:57:00.000Z', NOW), ago(NOW - 3 * 60_000, NOW))
})
test('a missing time is "never", not the epoch', () => {
assert.equal(ago(null), 'never')
assert.equal(ago(undefined), 'never')
assert.equal(ago(''), 'never')
assert.equal(day(null), 'unknown')
})
test('an unknown duration is a dash, and a short one keeps its seconds', () => {
// The distinction the plugin makes and this must not lose: `sessionSec` is
// ABSENT for a player who was already on when it loaded, so zero and unknown
// arrive at the same function and must not render the same way.
assert.equal(duration(null), '—')
assert.equal(duration(0), '—')
assert.equal(duration(40), '40s')
assert.equal(duration(90), '2m')
assert.equal(duration(3720), '1h 2m')
assert.equal(duration(7200), '2h')
})
test('a prefab reads as words, without a lookup table', () => {
assert.equal(prefab('rifle.ak'), 'rifle ak')
assert.equal(prefab('scientistnpc_full_any'), 'scientistnpc full any')
assert.equal(prefab(null), '')
})
test('a steam id is shortened without pretending to be a name', () => {
assert.equal(shortId('76561198000000001'), '…000001')
assert.equal(shortId(''), '')
})
test('a count that is not a number is zero, never NaN on the page', () => {
assert.equal(count(undefined), '0')
assert.equal(count(null), '0')
})
test("a feed row from another day carries its date, not just a time", () => {
// Found by the page walk: with the feed filtered to the previous wipe, three
// events from six weeks ago rendered as `02:03 PM` and read as this afternoon.
// Today's rows stay bare, because a killfeed of today's fights does not want
// the date on every line.
// Asserted against `Intl` rather than against a literal: a 12-hour locale puts
// letters in a bare time ("05:30 AM"), so "has letters in it" is not the test —
// "is exactly the time, and nothing else" is.
const time = (at) => new Date(at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
const todayAt = NOW - 90 * 60_000
assert.equal(clock(todayAt, NOW), time(todayAt))
const olderAt = NOW - 46 * 86400_000
assert.ok(clock(olderAt, NOW).endsWith(time(olderAt)))
assert.ok(clock(olderAt, NOW).length > time(olderAt).length, 'an older row carries no date')
// Yesterday counts as another day even when it is only a few hours back — the
// boundary is the calendar, not a duration, because that is what a reader
// means by "what time was that".
const lateLastNight = Date.parse('2026-09-15T23:50:00')
const earlyToday = Date.parse('2026-09-16T00:20:00')
assert.ok(clock(lateLastNight, earlyToday).length > time(lateLastNight).length)
})
test('the next wipe: the reader’s own clock, how far away, and whether it moved', () => {
const now = Date.parse('2026-09-25T12:00:00Z')
const forced = nextWipe({ at: '2026-10-01T18:00:00.000Z', source: 'forced' }, now)
assert.match(forced, /\(in 6 days\)$/)
assert.ok(!forced.includes('rescheduled'))
assert.match(nextWipe({ at: '2026-09-27T17:00:00.000Z', source: 'once' }, now), /\(in 2 days\) — rescheduled$/)
// No schedule is no line, not "unknown": the page leaves the part out.
assert.equal(nextWipe(null, now), null)
assert.equal(nextWipe({ at: 'soon', source: 'rule' }, now), null)
})
test('a title chip’s ink is whichever of black and white reads on its colour', () => {
assert.equal(contrastInk('#ffff00'), '#000000')
assert.equal(contrastInk('#FFAA55'), '#000000')
assert.equal(contrastInk('#1a1a8c'), '#ffffff')
assert.equal(contrastInk('#ff0000'), '#000000')
assert.equal(contrastInk('red'), '#000000', 'not a hex colour: black, on the caller’s fallback')
})
test('an NPC attacker reads as a name: a family, or the prefab without its variant (F2, D185)', () => {
// The first walk's "killed by wolf2".
assert.equal(attacker('wolf2'), 'Wolf')
assert.equal(attacker('wolf'), 'Wolf')
assert.equal(attacker('boar'), 'Boar')
assert.equal(attacker('polarbear'), 'Polar bear')
assert.equal(attacker('scientistnpc_full_any'), 'Scientist')
assert.equal(attacker('scientistnpc_roam'), 'Scientist')
assert.equal(attacker('scientistnpc_heavy'), 'Heavy scientist')
assert.equal(attacker('npc_bandit_guard'), 'Bandit guard')
assert.equal(attacker('bradleyapc'), 'Bradley APC')
assert.equal(attacker('patrolhelicopter'), 'Patrol helicopter')
assert.equal(attacker('autoturret_deployed'), 'Auto turret')
assert.equal(attacker('sam_site_turret_deployed'), 'SAM site')
// Anything unknown still reads as words, capitalised, with no suffix or variant.
assert.equal(attacker('some_new_beast3'), 'Some new beast')
assert.equal(attacker('spikes.floor.deployed'), 'Spikes floor')
assert.equal(attacker(null), '')
assert.equal(attacker(''), '')
})
test('a weapon keeps the light touch — attacker() is for what did the killing', () => {
assert.equal(prefab('rifle.ak'), 'rifle ak')
})

View File

@@ -0,0 +1,92 @@
// ── How a world position reaches a pixel (PLAN.md §30.3) ─────────────────
//
// The grid cases are the GAME's answers, not this file's: on 2026-09-25 a probe
// on the Oxide rig (a 3000 map, seed 1234) asked `MapHelper.PositionToString`
// for these positions and wrote down what it said. A label the page draws that
// disagrees with the in-game map is a player walking to the wrong square — and
// phase 3's plugin did exactly that for three weeks with a 146.3 m cell (D119).
import test from 'node:test'
import assert from 'node:assert/strict'
import { boundsOf, column, countdown, grid, gridLabel, scaleOf, toLatLng } from '../src/lib/mapGeometry.js'
// The rig's map as `GET /map` describes it.
const RIG = { worldSize: 3000, oceanMargin: 500, width: 2500, height: 2500, gridCells: 20, gridCellSize: 150 }
test('the grid label is the game’s, at every probed position', () => {
const probed = [
['ue_jungle_swamp_a', 764.7, 167.4, 'P8'],
['ue_jungle_swamp_a', 733.7, -556.0, 'O13'],
['harbor_2', 1122.7, 204.6, 'R8'],
['harbor_1', 678.1, 1005.7, 'O3'],
['ferry_terminal_1', 645.4, -1004.1, 'O16'],
['fishing_village_a', -787.8, 224.1, 'E8'],
['fishing_village_c', -203.0, -911.1, 'I16'],
['fishing_village_b', 1142.1, -566.5, 'R13'],
['desert_military_base_c', 94.0, -729.3, 'K14'],
['arctic_research_base_a', -556.9, 840.0, 'G4'],
['powerplant_1', -608.6, -346.4, 'F12'],
['water_treatment_plant_1', 497.8, 84.9, 'N9'],
['nw-corner', -1499, 1499, 'A0'],
['se-corner', 1499, -1499, 'T19'],
['origin', 0, 0, 'K10'],
]
for (const [name, x, z, game] of probed) assert.equal(gridLabel(RIG, x, z), game, name)
})
test('a 146.3 m cell — phase 3’s constant — would have disagreed with the game', () => {
// Kept as a test so the constant cannot come back in a refactor that "fixes"
// the cell size to the number community tools quote.
assert.notEqual(gridLabel({ ...RIG, gridCells: 21, gridCellSize: 146.3 }, 645.4, -1004.1), 'O16')
})
test('columns past Z are spelled the way Rust spells them', () => {
assert.equal(column(0), 'A')
assert.equal(column(25), 'Z')
assert.equal(column(26), 'AA')
assert.equal(column(27), 'AB')
})
test('the ocean margin is in pixels and is not scaled', () => {
assert.equal(scaleOf(RIG), 0.5)
// The world's corners sit exactly one margin inside the picture's.
assert.deepEqual(toLatLng(RIG, -1500, -1500), [500, 500])
assert.deepEqual(toLatLng(RIG, 1500, 1500), [2000, 2000])
assert.deepEqual(toLatLng(RIG, 0, 0), [1250, 1250])
})
test('north is up: a larger z is a larger latitude, and x is longitude', () => {
const [lat1, lng1] = toLatLng(RIG, 100, 100)
const [lat2, lng2] = toLatLng(RIG, 100, 400)
assert.ok(lat2 > lat1)
assert.equal(lng1, lng2)
assert.deepEqual(boundsOf(RIG), [[0, 0], [2500, 2500]])
})
test('something off the edge of the world is still placed, outside the picture', () => {
// The rig's cargo ship, as the probe found it: past the world AND the margin.
const [lat, lng] = toLatLng(RIG, 2691.6, -1453.1)
assert.ok(lng > RIG.width)
assert.ok(lat > 0 && lat < RIG.height)
})
test('the grid has a line per edge and a label per cell, A0 at the north-west corner', () => {
const g = grid(RIG)
assert.equal(g.lines.length, 2 * (RIG.gridCells + 1))
assert.equal(g.labels.length, RIG.gridCells * RIG.gridCells)
const a0 = g.labels.find((l) => l.text === 'A0')
assert.deepEqual([a0.x, a0.z], [-1500, 1500])
assert.deepEqual(grid(null), { lines: [], labels: [] })
})
test('a geometry that cannot place anything places nothing rather than NaN everywhere', () => {
assert.equal(scaleOf({ worldSize: 0, width: 2500 }), 0)
assert.equal(gridLabel({ worldSize: 3000 }, 0, 0), null)
})
test('a hack timer reads as minutes and seconds', () => {
assert.equal(countdown(540), '9:00')
assert.equal(countdown(61.4), '1:01')
assert.equal(countdown(-3), '0:00')
})

View File

@@ -0,0 +1,70 @@
// ── Which monument labels a map draws (PLAN_REDESIGNS §4, D196) ───────────
//
// The admin card must agree with the server about what a switch means, or the
// page says a label is drawn while the map leaves it out. These are the ways it
// could disagree: case, the built-in list, the fleet under a server, and a
// switch set back to its default.
import test from 'node:test'
import assert from 'node:assert/strict'
import { builtIn, fleetLabels, fleetShows, markerDiff, markerKey, serverShows, setFleet, setServer } from '../src/lib/mapMarkers.js'
const MINOR = ['Substation', 'Jungle Swamp', 'Ranch']
test('a label becomes the same key the server stores', () => {
assert.equal(markerKey(' jungle Swamp '), 'jungle swamp')
assert.equal(markerKey(null), '')
})
test('the minor labels start hidden and every other label drawn', () => {
assert.equal(builtIn(MINOR, 'substation'), false)
assert.equal(builtIn(MINOR, 'something facepunch added'), true)
})
test('a server switch wins over the fleet, and the fleet over the built-in list', () => {
assert.equal(fleetShows(MINOR, {}, 'substation'), false)
assert.equal(fleetShows(MINOR, { substation: true }, 'substation'), true)
assert.equal(serverShows(MINOR, { substation: true }, {}, 'substation'), true)
assert.equal(serverShows(MINOR, { substation: true }, { substation: false }, 'substation'), false)
assert.equal(serverShows(MINOR, {}, { 'power plant': false }, 'power plant'), false)
})
test('the fleet list is every server’s labels and the minor list, each once', () => {
const labels = fleetLabels(MINOR, [
{ markerLabels: [{ key: 'substation', label: 'Substation', count: 31 }, { key: 'harbor', label: 'Harbor', count: 2 }] },
{ markerLabels: [{ key: 'substation', label: 'Substation', count: 12 }] },
{},
])
assert.deepEqual(
labels.map((l) => [l.key, l.count]),
[
['harbor', 2],
['jungle swamp', 0],
['ranch', 0],
['substation', 43],
],
)
})
test('the fleet list shows a capitalised spelling where the game only wrote lower case', () => {
const labels = fleetLabels(MINOR, [{ markerLabels: [{ key: 'jungle swamp', label: 'jungle swamp', count: 3 }] }])
assert.deepEqual(labels.find((l) => l.key === 'jungle swamp'), { key: 'jungle swamp', label: 'Jungle Swamp', count: 3 })
})
test('setting the fleet back to the built-in answer clears the row instead of copying it', () => {
assert.deepEqual(setFleet(MINOR, {}, 'substation', true), { substation: true })
assert.deepEqual(setFleet(MINOR, { substation: true }, 'substation', false), {})
assert.deepEqual(setFleet(MINOR, {}, 'harbor', false), { harbor: false })
})
test('a server set to follow the fleet loses its own switch', () => {
assert.deepEqual(setServer({ substation: true }, 'substation', null), {})
assert.deepEqual(setServer({}, 'substation', false), { substation: false })
})
test('the diff sends a changed switch as its value and a removed one as null', () => {
assert.equal(markerDiff({ a: true }, { a: true }), null)
assert.deepEqual(markerDiff({ a: true, b: false }, { a: false, c: true }), { a: false, b: null, c: true })
assert.equal(markerDiff(undefined, {}), null)
})

View File

@@ -66,9 +66,22 @@ function fakeRg() {
),
api: { request: async () => ({}), ApiError: Error, BASE: '/api/v1' },
registry: {
// Core's own prefixing, character for character (client/src/modules/registry.js):
// the leading separators of the module's path are stripped and so are the
// TRAILING ones, which is what lets a module register `path: ''` and own its
// namespace root — `/rust` rather than `/rust/`.
//
// This fake did the obvious `${id}/${path}` until phase 4, and the day a
// module registered an index route it produced `rust/` while a real core
// produced `rust`. The suite then failed the nav check for a link that works
// perfectly in a browser. A fake that is nearly core is worse than one that
// is obviously not: it fails on the truth.
registerRoutes(id, byArea) {
for (const [area, list] of Object.entries(byArea || {})) {
for (const r of list || []) routes[area].push({ ...r, path: `${id}/${r.path}`, moduleId: id })
for (const r of list || []) {
const path = `${id}/${String(r.path || '').replace(/^\/+/, '')}`.replace(/\/+$/, '')
routes[area].push({ ...r, path, moduleId: id })
}
}
},
registerNav(id, { area, items }) {
@@ -120,7 +133,12 @@ it('registers at least one route, namespaced under the module id', () => {
assert.ok(all.length > 0, 'the chunk registered no routes at all')
for (const [area, list] of Object.entries(registered.routes)) {
for (const r of list) {
assert.ok(r.path.startsWith(`${manifest.id}/`), `${area} route "${r.path}" is not under the namespace`)
// Either the namespace root itself (a module's index route, `rust`) or
// something under it (`rust/servers/:id`). `startsWith('rust/')` alone
// would reject the root — and `startsWith('rust')` alone would accept a
// hypothetical `rustling`, which is why this is spelled out.
const under = r.path === manifest.id || r.path.startsWith(`${manifest.id}/`)
assert.ok(under, `${area} route "${r.path}" is not under the namespace`)
assert.ok(r.element, `${area} route "${r.path}" has no element`)
}
}
@@ -176,6 +194,19 @@ it('a nav row that gates on a feature has a provider to resolve it', () => {
assert.ok(registered.providers.size > 0, 'rows carry feature gates but no provider was registered')
})
it('the footer slot core declares is filled, and by a component', () => {
// R13's first slot, and the half that lives in the CHUNK: `site.footer.status`
// is a CLIENT slot, so it cannot be named in `module.json`'s `extensions` —
// that array is validated against the SERVER registry and naming a client slot
// there fails the load outright. Nothing else holds this registration, and an
// extension that stopped being registered is invisible: an unfilled slot
// renders nothing, exactly as an uninstalled module does.
const footer = registered.extensions.get('site.footer.status')
assert.ok(footer, 'nothing fills site.footer.status')
assert.equal(footer.id, manifest.id)
assert.equal(typeof footer.Component, 'function')
})
it('every slot module.json declares is one the chunk fills', () => {
// `module.json` declares SERVER slots, and the loader validates those before
// the chunk is ever served. Client slots cannot be declared there — the server
@@ -226,6 +257,23 @@ it('every declared slot names a core contribution core actually offers', () => {
}
})
it('the clan page gets all three of core’s Team contributions, one per place (phase 9, D56)', () => {
// Core contributes three things to a Team page it does not own. Each has its
// own place on the clan page, so no contribution is decided by another's
// position — and a slot missing here is a clan page with no feed, no forum or
// no notification switch, with nothing logged anywhere.
const byName = Object.fromEntries(registered.declaredSlots.map((s) => [s.name, s.wants]))
assert.deepEqual(byName, {
'rust.clan.header': 'team.notify',
'rust.clan.detail': 'team.activity',
'rust.clan.forum': 'team.forum',
})
// And the page is at the address the Team provider hands core.
const paths = registered.routes.public.map((r) => r.path)
assert.ok(paths.includes('rust/clans/:externalId'), paths.join(', '))
})
it('registers under exactly one module id, matching the manifest', () => {
const owners = new Set([
...Object.values(registered.routes).flat().map((r) => r.moduleId),

View File

@@ -0,0 +1,49 @@
// ── The UI kit's props, as core actually reads them ───────────────────────
//
// React drops an unknown prop without a word, so a UI-kit component called with
// the wrong one renders — just not what was written. Two of these have shipped
// from this org already: `PageHeader subtitle` (Teams phase 11, the kit's
// template) and `EmptyState title/message` (this module, phases 4 to 8 — every
// empty panel was a blank box until the presence fix's browser walk).
//
// A DOM-less runner cannot see a blank box, so this reads the source instead:
// it names the props core's components do NOT take and fails on any use of them.
// It is a claim about core that must be re-read when core's kit changes —
// written down rather than imported, because no core is in this process.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const SRC = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src')
/** Every .jsx/.js under src/. */
function sources(dir = SRC) {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) return sources(full)
return /\.(jsx?|mjs)$/.test(entry.name) ? [full] : []
})
}
// Core's `components/PageState.jsx` and `PageHeader.jsx`, read 2026-09-23 at the
// pinned core (ci/core-ref.json).
const REFUSED = {
// `EmptyState({ children })` — children only.
EmptyState: /<EmptyState\b[^>]*\b(title|message|description|text)\s*=/,
// `PageHeader({ eyebrow, title, lead, center })` — there is no `subtitle`.
PageHeader: /<PageHeader\b[^>]*\bsubtitle\s*=/,
}
test('no UI-kit component is handed a prop core does not read', () => {
const offences = []
for (const file of sources()) {
const text = fs.readFileSync(file, 'utf8')
for (const [component, pattern] of Object.entries(REFUSED)) {
if (pattern.test(text)) offences.push(`${path.relative(SRC, file)}: ${component}`)
}
}
assert.deepEqual(offences, [], 'use components/Empty.jsx for a titled empty state')
})

1492
engagement-triggers.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,7 @@
"id": "rust",
"name": "Rust",
"version": "0.1.0",
"coreApi": "^1.10.0",
"coreApi": "^1.11.0",
"server": "server/index.js",
"client": { "entry": "client/dist/entry.js" },
"schema": "server/db/schema.sql",
@@ -12,5 +12,6 @@
"admin": ["/rust"],
"player": ["/rust"]
},
"capabilities": ["servers"]
"extensions": ["admin.users.detail"],
"capabilities": ["rust", "servers", "killfeed", "leaderboard", "presence", "wipes", "identity", "map"]
}

View File

@@ -1,35 +1,425 @@
{
"$comment": "Generated inventory of the URLs module-rust serves - the module half of the freeze core keeps in server/routes.manifest.json. DERIVED as the difference between a core without this module and the same core with it, both at the pinned ref in ci/core-ref.json. Regenerate with the frozen-manifest job in .gitea/workflows/pr-checks.yml; see server/scripts/frozenManifest.js.",
"routes": [
{
"method": "DELETE",
"path": "/api/v1/admin/rust/npcs/profiles/:pid",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/rust/npcs/servers/:id/placements/:placement",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/rust/permissions/exceptions/:id",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/rust/permissions/groups/:id",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/rust/servers/:id",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/rust/zones/presets/:id",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/users/:id/rust/links/:steamId",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/users/:id/rust/permissions/grants/:grantId",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/player/rust/links/:steamId",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/config/:serverId/file",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/config/:serverId/files",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/config/:serverId/writes",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/config/:serverId/writes/:writeId",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/npcs",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/npcs/servers/:id/placements",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/permissions",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/permissions/catalogue",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/permissions/servers/:serverId",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/permissions/servers/:serverId/players",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/servers",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/servers/:id/integrations",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/title-categories",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/visibility",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/voice",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/rust/zones",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/rust/links",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/rust/permissions",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/rust/links",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/rust/npc-kills",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/rust/permissions",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/rust/servers",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/clans/:externalId",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/clans",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/events",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/leaderboard",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/map",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/map/image",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/map/live",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/npc-leaderboard",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/npc-profiles",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/online",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/players/:steamId/npc-kills",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/rust/servers/:id/wipes",
"tier": "public"
},
{
"method": "PATCH",
"path": "/api/v1/admin/rust/permissions/groups/:id",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/config/:serverId/file",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/npcs/profiles",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/npcs/profiles/:pid/restore",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/npcs/servers/:id/placements",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/npcs/servers/:id/placements/:placement/rename",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/npcs/servers/:id/placements/:placement/respawn",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/npcs/servers/:id/push",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/drift/:id/accept",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/drift/:id/adopt",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/drift/:id/dismiss",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/drift/:id/restore",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/drift/:id/revoke",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/groups/:id/members",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/groups/:id/members/clear",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/groups/:id/members/remove",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/groups/:id/split",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/servers/:serverId/grant",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/servers/:serverId/groups",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/servers/:serverId/revoke",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/permissions/sync",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/servers/:id/map/fetch",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/servers/:id/map/render",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/servers/:id/test",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/rust/zones/presets",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/users/:id/rust/permissions/grants",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/player/rust/link",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/npcs/factions",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/npcs/profiles/:pid",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/npcs/servers/:id/placements/:placement",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/permissions/groups/:id/permissions",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/permissions/groups/:id/servers",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/permissions/servers/:serverId/policy",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/servers/:id",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/servers/:id/titles",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/title-categories/:stat",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/visibility",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/voice",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/rust/zones/presets/:id",
"tier": "public"
}
]
}

View File

@@ -21,25 +21,62 @@
// letting that fail the boot would make installing the module before installing
// the bridge impossible.
//
// ── Polling, in phase 1 ───────────────────────────────────────────────────
// ── Four timers, and they answer four different questions ─────────────────
//
// This is a poll, and the live feed it will become is a later phase's work. The
// poll is not a placeholder for it: a sidecar's store-backed reads are exactly
// what answers while a game server is off, and the module will keep reading them
// on an interval to notice a server that went away without saying anything.
// What the feed adds is latency, not coverage.
// refresh (30s) what is each server, and who is on it — the BOARDS
// ingest (5s) what has happened since we last looked — the CURSOR
// sweep (1m) which login attempts were never let in (PLAN.md §25)
// prune (1h) forgetting the detail we promised not to keep for ever
//
// The boards poll and the ingest are deliberately separate rather than one loop
// reading both. They fail differently and they matter differently: a board that
// is 30 seconds stale shows a player count slightly behind, and an ingest that
// is 30 seconds behind shows a killfeed that feels broken. Splitting them lets
// the cheap one run often and the expensive one run rarely, and it means a
// sidecar that answers one and not the other degrades in exactly one place.
//
// The poll was never a placeholder for a socket: a sidecar's store-backed reads
// are what answer while a game server is off, which is most of what this module
// renders. See `ingest.js` for why the live feed is a cursor and not a
// WebSocket.
const core = require('./core')
const db = require('./model/servers/servers.db')
const engagement = require('./engagement/emit')
const eventsDb = require('./model/events/events.db')
const eventWorld = require('./eventWorld')
const ingest = require('./ingest')
const mapImages = require('./mapImages')
const npcSync = require('./npcSync')
const permSync = require('./permSync')
const permissionsDb = require('./model/permissions/permissions.db')
const titleSync = require('./titleSync')
const servers = require('./model/servers/servers.model')
const sidecar = require('./sidecarClient')
const log = core.logger('boot')
let refreshTimer = null
let ingestTimer = null
let pruneTimer = null
let sweepTimer = null
const REFRESH_MS = 30 * 1000
const INGEST_MS = 5 * 1000
const PRUNE_MS = 60 * 60 * 1000
const SWEEP_MS = 60 * 1000
/**
* How long this module keeps raw events.
*
* Longer than the sidecar's 14 days, because this is the richer store and the
* one a page reads — and because the sidecar lives on somebody's game host while
* this lives on the website's own database. What is NOT bounded by it is the
* record: `rust_player_wipe_stats` and `rust_gather_totals` are permanent, which
* is the whole of R12's "a wipe does not erase a player's history".
*/
const EVENT_RETENTION_DAYS = 30
/**
* Ask every configured sidecar how its server is doing, and store what it said.
@@ -63,7 +100,18 @@ async function refresh() {
async function refreshOne(server) {
try {
const board = await sidecar.serverBoard(server)
// One call for both boards. `/server` would answer the same question about
// the server itself, but presence would then be a second round trip to the
// same process for a fact it already had in hand.
//
// **And one for `/health`, because the boards cannot say whether the game is
// there NOW** (D68, PLAN.md §25.1). The sidecar keeps its last `server.hello`
// after the plugin disconnects — that is what lets a page render a server
// that is off — so a game that hung, or whose bridge was unloaded, while the
// sidecar stayed up read as online here from phase 4 until phase 10. Only
// `/health`'s `plugin_connected` answers the question, and the two are asked
// together so they describe the same moment.
const [board, health] = await Promise.all([sidecar.boards(server), sidecar.health(server)])
// Three outcomes, and collapsing any two of them loses something an operator
// needs:
@@ -76,25 +124,53 @@ async function refreshOne(server) {
// whose plugin is not loaded yet, and reporting it as unreachable sends the
// operator to look at the network instead of at the game server.
if (!board.ok) {
await db.putState({ serverId: server.id, reachable: false, online: false })
// `markUnreachable`, not `putState`: nothing answered, so the only new fact
// is that nothing answered. Writing the whole row from that one fact would
// blank the hostname, the map, the seed and the wipe — the last thing this
// server said, which is exactly what the pages exist to render while it is
// off.
await db.markUnreachable(server.id, false)
engagement.serverObserved(server, false)
return
}
const frame = board.data
const boards = (board.data && board.data.boards) || {}
const frame = boards['server.hello']
if (!frame) {
await db.putState({ serverId: server.id, reachable: true, online: false })
// The sidecar is up and has never heard from the game. Presence is emptied
// rather than left alone: a stale list of players on a server nobody can
// reach is worse than an empty one, because it looks current.
await db.markUnreachable(server.id, true)
await ingest.applyBoards(server.id, {})
engagement.serverObserved(server, false)
return
}
// Unknown is not connected. A `/health` that did not answer while `/boards`
// did is odd enough to be worth a line, and reporting the server up on the
// strength of a board the game may have left behind hours ago is the defect
// this call exists to remove.
const connected = Boolean(health.ok && health.data && health.data.plugin_connected === true)
if (!health.ok) log.warn('the sidecar answered /boards but not /health', { server: server.id })
// The presence board is the plugin's last word too. While the game is not
// connected it names people as online who may have left hours ago, which is
// both wrong and — under §23's rule — a claim about named people nobody made.
await ingest.applyBoards(
server.id,
connected ? boards : { ...boards, 'players.online': { players: [] } },
)
await db.putState({
serverId: server.id,
reachable: true,
// A stored `server.hello` means the game connected; whether it is connected
// NOW is a different question, and `/health` is what answers it. The board
// alone cannot say, which is why `online` is not simply `true` here — it is
// decided by freshness in the model, from `updated_at`.
online: true,
players: Number(frame.players) || 0,
// The plugin is connected NOW (D68). A stored `server.hello` only says it
// connected once; the model still applies its own freshness on top.
online: connected,
// A board the game left behind is a description, not a sighting.
seen: connected,
players: connected ? Number(frame.players) || 0 : 0,
maxPlayers: Number(frame.maxPlayers) || 0,
hostname: frame.hostname || null,
level: frame.level || null,
@@ -102,9 +178,26 @@ async function refreshOne(server) {
worldSize: frame.worldSize === undefined ? null : Number(frame.worldSize),
bootId: frame.bootId || null,
saveCreatedAt: frame.saveCreatedAt || null,
wipeId: frame.wipeId || null,
protocol: frame.protocol === undefined ? null : Number(frame.protocol),
raw: frame,
})
// After the write, so a transition announced is one a page already shows.
engagement.serverObserved(server, connected)
// A restart or a wipe under a running event is the moment core must be told
// to ask what the world still holds (§11.1). Only a CONNECTED plugin's hello
// counts: a board the game left behind says nothing about now.
if (connected) {
eventWorld.observeServer(server.id, { bootId: frame.bootId, wipeId: frame.wipeId, worldReady: frame.worldReady })
// A new boot, wipe or map is a reason to ask what the map is now (D110).
// Started, never awaited: a picture is a megabyte over the game link, and
// the board poll does not wait on one. `mapImages` keeps one fetch per
// server and backs off on its own.
mapImages.observe(server, frame)
}
} catch (err) {
// A failure here is one server's, and it must not reach `Promise.allSettled`
// as a rejection that hides which one. Log with the id and carry on.
@@ -119,14 +212,85 @@ async function refreshOne(server) {
* built to look like it — so a module that only needs core at boot time can skip
* `core.init` entirely and use this argument.
*/
/** Runs the cursor for every configured server, independently. */
async function ingestAll() {
let rows
try {
rows = await servers.listForPolling()
} catch (err) {
log.warn('could not read the server list', { error: err.message })
return
}
// `allSettled`, for the same reason the board poll uses it: six servers behind
// one unreachable host must not stop the other five being ingested.
await Promise.allSettled(rows.map((server) => ingest.ingestServer(server)))
}
async function prune() {
try {
const gone = await eventsDb.pruneEvents(EVENT_RETENTION_DAYS)
if (gone > 0) log.info('pruned old events', { events: gone, days: EVENT_RETENTION_DAYS })
} catch (err) {
log.warn('could not prune events', { error: err.message })
}
}
/**
* Login attempts that were never approved (D64, PLAN.md §25).
*
* On its own minute timer rather than the prune's hour: an attempt waits a
* minute for its approval, and a staff alert an hour late is not an alert. A
* query over stored rows, so it needs nothing kept in memory and a restart loses
* nothing; the dedupe key makes a second pass over the same attempt a no-op.
*/
async function sweep() {
let rows
try {
rows = await servers.listForPolling()
} catch (err) {
log.warn('could not read the server list', { error: err.message })
return
}
const sent = await engagement.sweepLoginDenied(rows)
if (sent > 0) log.info('unapproved logins reported', { attempts: sent })
}
async function onBoot() {
await refresh()
// The permission manager's rebuild (PLAN_REDESIGNS §1) keeps groups in new
// tables. Copied once, before the loop can push anything, so no sync ever
// sees a site with its groups missing. A failure is logged, not fatal: the
// copy runs again next boot, and until then the site simply has no groups.
try {
const copied = await permissionsDb.migrateGroups()
if (copied) log.info('permission groups copied into the rebuilt tables', { groups: copied })
} catch (err) {
log.error('could not copy the permission groups', { error: err.message })
}
// The permission mirror owns its own loop and its own cadence (see
// `permSync.js`). It is started rather than run here: a first pass would write
// to every configured game server before the website had finished booting, and
// nothing about R2 is urgent enough to delay a listener for.
permSync.start()
// The chat titles have a loop of their own for the same reason (phase 17).
titleSync.start()
// So do the NPC profiles, adopted and pushed to each server's RunicNPC
// (runicnpc stage 4, D244): a first push reads a server before it writes it.
npcSync.start()
refreshTimer = setInterval(refresh, REFRESH_MS)
ingestTimer = setInterval(ingestAll, INGEST_MS)
pruneTimer = setInterval(prune, PRUNE_MS)
sweepTimer = setInterval(sweep, SWEEP_MS)
// Node keeps the process alive for a pending timer. Core's own intervals are
// unref'd for exactly this reason: a module that forgets turns `Ctrl-C` into a
// thirty-second wait, and on a host it turns a `systemctl stop` into a SIGKILL.
if (typeof refreshTimer.unref === 'function') refreshTimer.unref()
log.info('booted', { refreshMs: REFRESH_MS })
for (const timer of [refreshTimer, ingestTimer, pruneTimer, sweepTimer]) {
if (timer && typeof timer.unref === 'function') timer.unref()
}
log.info('booted', { refreshMs: REFRESH_MS, ingestMs: INGEST_MS, permSyncMs: permSync.TICK_MS })
}
/**
@@ -138,9 +302,30 @@ async function onBoot() {
* rather than cancelled, since nothing can stop a promise that is still running.
*/
async function onShutdown() {
if (refreshTimer) clearInterval(refreshTimer)
permSync.stop()
titleSync.stop()
npcSync.stop()
for (const timer of [refreshTimer, ingestTimer, pruneTimer, sweepTimer]) {
if (timer) clearInterval(timer)
}
refreshTimer = null
ingestTimer = null
pruneTimer = null
sweepTimer = null
log.info('shut down')
}
module.exports = { onBoot, onShutdown, refresh, refreshOne, REFRESH_MS }
module.exports = {
onBoot,
onShutdown,
refresh,
refreshOne,
ingestAll,
prune,
REFRESH_MS,
INGEST_MS,
EVENT_RETENTION_DAYS,
}

203
server/catalogue.js Normal file
View File

@@ -0,0 +1,203 @@
// ── What the bridge can say, and who may hear it ──────────────────────────
//
// One file, because these two questions have to be answered together or the
// second one rots: which frame kinds exist, and which of them a member of the
// public may see.
//
// ── The boundary ──────────────────────────────────────────────────────────
//
// Protocol 2's catalogue includes frames carrying **IP addresses** (a login
// attempt, an approval, a ban) and **one player's complaint about another** (a
// report), and one — a destroyed structure — that names where somebody lives.
// They are stored, because an operator chasing ban evasion needs them and
// because the sidecar persists what it is told. They must never reach a public
// page.
//
// **The boundary is enforced HERE, on the side that serves, and not on the wire.**
// The plugin could have stamped a `class` on every frame and saved this file the
// trouble; it deliberately does not (PROTOCOL.md §8.5). A boundary declared by
// the sender is a boundary a compromised — or merely out-of-date — game host can
// widen. Core's own shard fan-out works the same way: a public stream with an
// allowlist of kinds, and an admin stream that adds the rest.
//
// ── Default deny, and why it is not paranoia ──────────────────────────────
//
// `isPublic` answers `false` for a kind it has never heard of. That matters
// because of the shape of the mistake it prevents: the next protocol version
// adds a kind, this module ingests it happily (`rust_events` stores what it is
// given), and a page that filtered by a DENY list would publish it the day it
// first arrived — before anybody had decided whether it should be public. With
// an allowlist the new kind is invisible until somebody adds it here, which is
// the same moment they think about it.
//
// The test holds this list against `docs/rust-link/PROTOCOL.md` §8.4's table, so
// adding a kind to the spec without classifying it fails a build rather than
// shipping an address to a public page.
/**
* Kinds a public, signed-out visitor may see.
*
* Each entry is a decision. `player.chat` is here because a shard's chat is
* public by the same logic that makes a killfeed public — it happened in front
* of everyone who was on the server — and an operator who disagrees turns the
* feature off rather than relying on this list being wrong.
*/
const PUBLIC_KINDS = Object.freeze([
'player.connected',
'player.disconnected',
'player.respawned',
'player.death',
'player.chat',
'player.tally',
'server.wipe',
'server.initialized',
'server.shutdown',
])
/**
* Kinds an admin may see and nobody else.
*
* Listed rather than implied by absence, so that "we know about this kind and it
* is restricted" is distinguishable from "nobody has classified this kind" — the
* second is a finding, and a bare allowlist cannot tell you which you are
* looking at.
*/
const STAFF_KINDS = Object.freeze([
'entity.destroyed',
'player.reported',
'player.banned',
'player.unbanned',
'player.login.attempt',
'player.approved',
// Protocol 3's two account frames. Neither carries a code — the code travels
// through the player, which is what makes typing it proof — but both name a
// Steam id ALONGSIDE a website account's activity, which is exactly the join a
// public page must not be able to make: "this player is that person" is a fact
// about somebody's identity, not about what happened on the server.
'account.link.requested',
'account.unlinked',
// Protocol 4. Who holds which privilege in game, and the fact that somebody
// changed it by hand — a question about a person's standing and about an
// operator's own console, neither of which is a public page's business.
'perm.drift',
// Protocol 13. How a configuration save's reload ended — and, when it failed,
// the tail of the game server's own log, which is an operator's console and
// can hold anything a plugin chose to print.
'config.outcome',
// Protocol 13 (F8, D184). Which plugins a server runs, and which permissions
// each one registers: an operator's inventory, and the map of what can be
// granted there — not a public page's business.
'plugin.loaded',
'plugin.unloaded',
// The world an event borrowed or made, ending on its own deadline:
// `lease.expired` since protocol 8 and `world.expired` since protocol 9 — the
// latter recognisable only from protocol 13 (F13). Neither was ever classified
// (default deny kept both off public pages); both are an event's machinery,
// and the public learns what an event did from core's own announcements.
'lease.expired',
'world.expired',
// Protocol 6. Clan membership, which the org lead made members-only (D49):
// who joined which clan, and who threw whom out, is the clan's business. It
// reaches a clan's own members through core's Team feed, where core resolves
// who is a member, and it reaches the server's public feed not at all.
'clan.created',
'clan.disbanded',
'clan.member.added',
'clan.member.left',
'clan.member.kicked',
// RunicNPC (runicnpc stage 4). `npc.died` names the player who killed it and
// everyone who hurt it, so it is a roll call like `player.tally`: staff until
// an operator says otherwise. What the public sees of a kill is the tally's
// per-profile count on the leaderboard (D250).
'npc.died',
'npc.health',
'npc.placement.changed',
])
/**
* The public kinds that say a NAMED player was on the server at a given moment.
*
* A subset of `PUBLIC_KINDS`, not a third list: these are public-page material
* whose audience an operator chooses (`model/visibility`), where the rest of
* `PUBLIC_KINDS` is public by construction. The org lead's rule, settled
* 2026-09-22: **nothing tells who is online by default** — the narrowest
* audience (staff) unless an operator widens it, and a count is never a name.
*
* `player.death` and `player.chat` are here, and that was decided rather than
* overlooked. They are the killfeed and the chat — the content a feed exists
* for — and each one says "this person was on at 12:03" as plainly as a connect
* frame does. `player.tally` is a per-minute flush that is only ever sent for a
* player who is playing, which makes it a roll call with extra steps.
*
* What is left in the public set once these are removed is the server's own
* story — a wipe, a start, a shutdown — which names nobody.
*/
const PRESENCE_KINDS = Object.freeze([
'player.connected',
'player.disconnected',
'player.respawned',
'player.death',
'player.chat',
'player.tally',
])
/** Every event kind the protocol defines, through protocol 13. */
const ALL_KINDS = Object.freeze([...PUBLIC_KINDS, ...STAFF_KINDS])
const PUBLIC = new Set(PUBLIC_KINDS)
const STAFF = new Set(STAFF_KINDS)
const PRESENCE = new Set(PRESENCE_KINDS)
/**
* May a signed-out visitor see this kind?
*
* Default deny: an unknown kind is not public. Callers pass whatever arrived on
* the wire, including a kind from a newer protocol this build has never seen.
*/
function isPublic(kind) {
return PUBLIC.has(kind)
}
/** Is this a kind this build knows about at all? */
function isKnown(kind) {
return PUBLIC.has(kind) || STAFF.has(kind)
}
/** Does this kind name a player who was on the server at the time? */
function isPresence(kind) {
return PRESENCE.has(kind)
}
/**
* Narrows a list of requested kinds to the ones a viewer may have.
*
* Returning the allowlist itself when nothing was requested is what makes the
* public route safe by construction rather than by remembering to filter: there
* is no code path where "no filter" means "everything".
*
* `presence` defaults to `false` for the same reason `admin` does: a caller that
* forgets to say what the viewer may see gets the narrowest answer. The route
* resolves it from the operator's setting (`model/visibility`); nothing else
* should be passing `true`.
*/
function kindsFor({ admin = false, presence = false, requested = null } = {}) {
const permitted = admin
? ALL_KINDS
: PUBLIC_KINDS.filter((k) => presence || !PRESENCE.has(k))
if (!requested || requested.length === 0) return [...permitted]
const allowed = new Set(permitted)
return requested.filter((k) => allowed.has(k))
}
module.exports = {
PUBLIC_KINDS,
STAFF_KINDS,
PRESENCE_KINDS,
ALL_KINDS,
isPublic,
isKnown,
isPresence,
kindsFor,
}

View File

@@ -0,0 +1,111 @@
// ── `/clan name [server]` — one clan, and its roster where the caller may see it
//
// D50 deferred it here. A clan's name, colour, score and member count are public
// (D58); its ROSTER — who is in it and which of them is on — sits behind the
// roster audience (D48), which defaults to the clan's own members plus staff.
//
// The roster decision is `clans.getForViewer`'s, the same function the web page
// and core's `projectRoster` use, so the three cannot disagree about who may
// look. What this file adds is D127: **a roster shown to anything short of a
// `public` audience goes to the caller alone**, never to the channel.
const c = require('./common')
const clans = require('../model/clans/clans.model')
/** The candidates an ambiguous name lists. */
const CANDIDATES = 10
/**
* Every clan on the servers searched, with the server each came from, and the
* servers whose clan board cannot be trusted right now.
*/
async function gather(servers) {
const boards = await Promise.all(servers.map(async (s) => ({ server: s, ...(await clans.listForServer(s.id)) })))
return {
rows: boards.flatMap((b) => b.clans.map((clan) => ({ clan, server: b.server }))),
unreadable: boards.filter((b) => !b.board.supported || !b.board.fresh).map((b) => b.server),
}
}
/** An exact name (case-insensitive), then a unique prefix. */
function find(rows, wanted) {
const needle = wanted.trim().toLowerCase()
const exact = rows.filter((r) => r.clan.name.toLowerCase() === needle)
if (exact.length === 1) return { hit: exact[0] }
if (exact.length > 1) return { ambiguous: exact }
const prefix = rows.filter((r) => r.clan.name.toLowerCase().startsWith(needle))
if (prefix.length === 1) return { hit: prefix[0] }
if (prefix.length > 1) return { ambiguous: prefix }
return {}
}
function memberLine(m) {
const tags = [m.leader ? 'leader' : null, m.online ? 'online' : null].filter(Boolean)
return `${m.name || 'Unknown player'}${tags.length ? ` (${tags.join(', ')})` : ''}`
}
async function handler({ options, actor }) {
const wanted = options && typeof options.name === 'string' ? options.name.trim() : ''
if (!wanted) return c.refuse('Name a clan.')
const picked = c.pickServer(await c.listServers(), options.server)
const refusal = c.pickRefusal(picked)
if (refusal) return refusal
const searched = picked.server ? [picked.server] : picked.all
const { rows, unreadable } = await gather(searched)
const { hit, ambiguous } = find(rows, wanted)
if (ambiguous) {
const list = ambiguous.slice(0, CANDIDATES).map((r) => (searched.length > 1 ? `${r.clan.name} on ${r.server.name}` : r.clan.name))
return c.refuse(`Several clans match “${wanted}”: ${list.join(', ')}${ambiguous.length > CANDIDATES ? ', …' : ''}`)
}
if (!hit) {
// A board that is missing, stale or unsupported proves nothing about a clan
// it does not list. Saying "no such clan" from it would be a guess presented
// as a fact.
if (unreadable.length) {
return c.refuse(
`No clan called “${wanted}” is on the boards that can be read right now. ` +
`The clan list for ${unreadable.map((s) => s.name).join(', ')} is not available, so it may be there.`,
)
}
return c.refuse(`No clan called “${wanted}”.`)
}
const answer = await clans.getForViewer(hit.clan.externalId, c.viewerOf(actor))
if (!answer) return c.refuse(`No clan called “${wanted}”.`)
const { clan, roster } = answer
const fields = [
{ name: 'Score', value: String(clan.score), inline: true },
{ name: 'Members', value: clan.maxMembers ? `${clan.memberCount}/${clan.maxMembers}` : String(clan.memberCount), inline: true },
{ name: 'Server', value: clan.serverName || hit.server.name, inline: true },
]
if (clan.color) fields.push({ name: 'Colour', value: clan.color, inline: true })
const base = { title: clan.name, url: c.pageUrl(`/rust/clans/${encodeURIComponent(clan.externalId)}`), fields }
if (!roster.visible || !roster.members.length) return base
// Leaders first, then whoever is on, then everyone else — the order a person
// looking for "who can I talk to" wants.
const members = [...roster.members].sort(
(a, b) => Number(b.leader) - Number(a.leader) || Number(b.online) - Number(a.online) || String(a.name).localeCompare(String(b.name)),
)
fields.push({ name: 'Roster', value: c.fitLines(members.map(memberLine)), inline: false })
// D127 and D48 together: a roster the whole site may see may be posted; any
// narrower one is for the caller.
return { ...base, ephemeral: roster.audience !== 'public' }
}
module.exports = {
name: 'clan',
description: 'A clan on a Rust server — score and members, and its roster where you may see it',
options: [
{ name: 'name', type: 'string', description: 'Clan name, or the start of it', required: true },
{ name: 'server', type: 'string', description: 'Server name or id (every server when left out)', required: false },
],
access: 'everyone',
handler,
}

187
server/commands/common.js Normal file
View File

@@ -0,0 +1,187 @@
// ── What the five commands share (phase 16, R11) ───────────────────────────
//
// Registered with `api.registerSlashCommands` (MODULE_API 1.6.0). The handlers
// run in the WEBSITE process: core pulls the definitions over its internal API to
// the bot and dispatches each call back here. Nothing in these files knows what
// Discord is — a handler is handed an `actor` and returns an envelope.
//
// ── The two privacy rules (D127) ──────────────────────────────────────────
//
// 1. **A refusal is private.** Core already delivers an `ephemeral` answer as a
// private follow-up; `refuse()` below is the one way these files say no, and
// it always sets the flag.
// 2. **An answer narrower than `public` is private too.** Core has no reverse
// case: an answer WITHOUT the flag is posted to the channel the command was
// run in, where everybody reads it. So a moderator running `/online` in a
// public channel must get the names privately, or the names they may see are
// published to everyone who may not. That is the leak module-uo's `/guild`
// has (D132, Module-uo#46), and every answer here decides it explicitly.
//
// ── Three seconds (`HANDLER_TIMEOUT_MS`) ──────────────────────────────────
//
// Every answer reads this module's own tables. **No command asks a sidecar**: a
// game that is slow to answer would cost the reply, and the tables already hold
// the last thing each server said.
const core = require('../core')
const servers = require('../model/servers/servers.model')
const visibility = require('../model/visibility/visibility.model')
/**
* Where the caller sits on the presence ladder.
*
* An UNLINKED caller is `public`, answered directly. Handing `visibility.viewer`
* a synthetic request with no user would make it fall through to
* `getUserFromRequest`, which expects real cookies (module-uo's phase 3 bug). A
* linked caller is handed over as `{ user }`, which `viewer` reads first and then
* re-reads from the account row — so a banned or demoted account is judged by
* what it is now, not by what core resolved.
*/
async function levelFor(actor) {
if (!actor || actor.userId == null) return 'public'
return visibility.viewerLevel({ user: { id: actor.userId, role: actor.role } })
}
/** The viewer shape `model/clans` takes: `{ userId, role }` or null. */
const viewerOf = (actor) => (actor && actor.userId != null ? { userId: actor.userId, role: actor.role || null } : null)
/** Every answer that says no. Private, always (D127 rule 1). */
const refuse = (text) => ({ text, ephemeral: true })
/** An absolute link to a page on the site. */
const pageUrl = (path) => `${core.baseUrl}${path}`
const serverUrl = (server) => pageUrl(`/rust/servers/${encodeURIComponent(server.id)}`)
/**
* Which server a `server` option names, among `list`.
*
* An exact id, then an exact name (case-insensitive), then a unique prefix of
* either. Servers are added at runtime and `choices` are fixed at load, so this
* is free text matched here. A wrong-server answer is worse than "say which one",
* so two prefix matches are ambiguous rather than a guess.
*
* Answers `{ server }`, `{ all }` (no option and more than one server),
* `{ none }` (no servers at all), `{ ambiguous }` or `{ missing }`.
*/
function pickServer(list, option) {
if (!list.length) return { none: true }
const wanted = typeof option === 'string' ? option.trim().toLowerCase() : ''
if (!wanted) return list.length === 1 ? { server: list[0] } : { all: list }
const byId = list.find((s) => s.id.toLowerCase() === wanted)
if (byId) return { server: byId }
const byName = list.filter((s) => s.name.toLowerCase() === wanted)
if (byName.length === 1) return { server: byName[0] }
const prefix = list.filter((s) => s.id.toLowerCase().startsWith(wanted) || s.name.toLowerCase().startsWith(wanted))
if (prefix.length === 1) return { server: prefix[0] }
if (prefix.length > 1) return { ambiguous: prefix }
return { missing: option.trim() }
}
/** The refusal for each way `pickServer` can fail to name exactly one server. */
function pickRefusal(picked, { needOne = false } = {}) {
const names = (list) => list.map((s) => `${s.name} (\`${s.id}\`)`).join(', ')
if (picked.none) return refuse('No Rust servers are set up on this site yet.')
if (picked.missing) return refuse(`No server matches “${picked.missing}”.`)
if (picked.ambiguous) return refuse(`Several servers match: ${names(picked.ambiguous)}. Name one.`)
if (needOne && picked.all) return refuse(`Which server? This site follows ${names(picked.all)}.`)
return null
}
/** Every enabled server, as the public shape. */
const listServers = (now = Date.now()) => servers.listPublic(now)
// ── Time, in words ────────────────────────────────────────────────────────
//
// Plain text, not a platform's timestamp markup: the envelope is platform-
// agnostic (§7.1), and a second platform would print `<t:…>` literally. So an
// instant is written in UTC, with how far away it is beside it — the relative
// part is the one every reader can use without converting.
const UTC_FORMAT = new Intl.DateTimeFormat('en-GB', {
timeZone: 'UTC',
weekday: 'short',
day: 'numeric',
month: 'short',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
})
function relative(ms, now = Date.now()) {
const diff = ms - now
const abs = Math.abs(diff)
const unit = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
let span
if (abs < 60_000) span = 'less than a minute'
else if (abs < 3_600_000) span = unit(Math.round(abs / 60_000), 'minute')
else if (abs < 172_800_000) span = unit(Math.round(abs / 3_600_000), 'hour')
else span = unit(Math.round(abs / 86_400_000), 'day')
return diff >= 0 ? `in ${span}` : `${span} ago`
}
/** `Thu 1 Oct, 18:00 UTC (in 6 days)`, or null for no instant. */
function when(value, now = Date.now()) {
if (!value) return null
const ms = value instanceof Date ? value.getTime() : Date.parse(value)
if (Number.isNaN(ms)) return null
return `${UTC_FORMAT.format(ms).replace(/,? (\d\d:\d\d)$/, ', $1')} UTC (${relative(ms, now)})`
}
/** Just the distance: `3 days ago`. */
function ago(value, now = Date.now()) {
if (!value) return null
const ms = value instanceof Date ? value.getTime() : Date.parse(value)
return Number.isNaN(ms) ? null : relative(ms, now)
}
const SOURCES = {
forced: 'the monthly forced wipe',
rule: 'the server’s own schedule',
once: 'rescheduled by the operator',
}
/** The next wipe in words, with what decided it — or `null` for no schedule. */
function nextWipeText(server, now = Date.now()) {
const next = server.nextWipe
if (!next) return null
return `${when(next.at, now)} — ${SOURCES[next.source] || next.source}`
}
/** Players, as a number out of the maximum, for a server that is up. */
const playerCount = (server) => (server.maxPlayers ? `${server.players}/${server.maxPlayers}` : String(server.players))
/**
* Cut a list of lines to fit one embed field (1 024 characters) and a count,
* ending in "and N more" when it had to cut.
*/
function fitLines(lines, { max = lines.length, limit = 1000 } = {}) {
const kept = []
let length = 0
for (const line of lines.slice(0, max)) {
if (length + line.length + 1 > limit - 20) break
kept.push(line)
length += line.length + 1
}
const rest = lines.length - kept.length
return rest > 0 ? `${kept.join('\n')}\nand ${rest} more` : kept.join('\n')
}
module.exports = {
levelFor,
viewerOf,
refuse,
pageUrl,
serverUrl,
pickServer,
pickRefusal,
listServers,
relative,
when,
ago,
nextWipeText,
playerCount,
fitLines,
}

16
server/commands/index.js Normal file
View File

@@ -0,0 +1,16 @@
// ── The slash commands (phase 16, R11, D126) ──────────────────────────────
//
// Five read-only questions, answered from this module's own tables. No write
// verbs, and no `/link`: the account link stays on R1's two surfaces.
//
// Registered as ONE batch in `index.js`. Names are bare words (§32.4 reading 1):
// Discord scopes commands to the bot that owns them, and one module per site
// (website#204) means no other module competes for them. None collides with the
// bot's own built-ins, which core cannot see and the bot resolves against us.
module.exports = [
require('./status.command'),
require('./wipe.command'),
require('./top.command'),
require('./online.command'),
require('./clan.command'),
]

View File

@@ -0,0 +1,93 @@
// ── `/online [server]` — how many, and who, where the caller may see it ─────
//
// The command with the gate. The org lead's rule (2026-09-22) is that nothing
// names who is online by default: the COUNT is public and the NAMES reach the
// server's presence audience (D42, per-server override D45), staff unless an
// operator widened it.
//
// And D127 on top of it: **a caller inside a narrower-than-public audience gets
// the names PRIVATELY.** The answer is posted where the command was run, and a
// moderator's `/online` in a public channel would otherwise hand the roll call to
// everyone reading the channel. Only a server whose audience is `public` posts
// its names in the open.
const c = require('./common')
const events = require('../model/events/events.model')
const visibility = require('../model/visibility/visibility.model')
/** Fifty names, then "and N more" (§32.4 reading 2). */
const LIMIT = 50
// The link nudge, and only when it is TRUE — module-uo's rule. Linking a Discord
// account to a site account earns `signed_in` and nothing above it; `staff` is a
// role an operator grants. So a server that shows names to staff is not a reason
// to tell anybody to link.
function linkNudge(actor, required) {
if (actor && actor.isLinked) return null
if (required !== 'signed_in') return null
return 'Link your Discord account on the site to see who is on — this server shows names to signed-in members.'
}
async function forServer(server, actor, level) {
const required = await visibility.presenceFor(server.id)
const visible = visibility.meets(level, required)
const count = server.online ? server.players : 0
// Offline, or nobody on: there are no names to decide about, and saying who
// was on when the server went down would be the presence board's last word
// presented as now.
if (!server.online) return { text: `${server.name} is offline.`, url: c.serverUrl(server) }
if (!visible || count === 0) {
return {
title: `${server.name} — ${count} online`,
url: c.serverUrl(server),
...(visible ? {} : { notice: linkNudge(actor, required) }),
}
}
const players = await events.online(server.id)
const names = players.map((p) => (p.sleeping ? `${p.name || 'Unknown player'} (sleeping)` : p.name || 'Unknown player'))
return {
title: `${server.name} — ${players.length} online`,
url: c.serverUrl(server),
text: c.fitLines(names, { max: LIMIT, limit: 1900 }),
// D127. Anything short of `public` is for the caller alone.
ephemeral: required !== 'public',
}
}
async function handler({ options, actor }) {
const now = Date.now()
const picked = c.pickServer(await c.listServers(now), options && options.server)
const refusal = c.pickRefusal(picked)
if (refusal) return refusal
const level = await c.levelFor(actor)
if (picked.server) return forServer(picked.server, actor, level)
// The fleet: counts only, which are public. Names are one server's question,
// and the closing line offers it only when naming a server would show some.
const visibleSomewhere = (
await Promise.all(picked.all.map(async (s) => visibility.meets(level, await visibility.presenceFor(s.id))))
).some(Boolean)
return {
title: 'Online now',
url: c.pageUrl('/rust'),
fields: picked.all.slice(0, 25).map((s) => ({
name: s.name,
value: s.online ? `${s.players} online` : 'Offline',
inline: true,
})),
...(visibleSomewhere ? { text: 'Name a server to see who is on.' } : {}),
}
}
module.exports = {
name: 'online',
description: 'How many are on a Rust server, and who, where this site shows names',
options: [{ name: 'server', type: 'string', description: 'Server name or id (counts for all when left out)', required: false }],
// Everyone, deliberately: `linked` would hide the command from the unlinked
// members the nudge exists to invite. The gate is inside the handler.
access: 'everyone',
handler,
}

View File

@@ -0,0 +1,60 @@
// ── `/status [server]` — is it up, how full, when did it wipe ───────────────
//
// Public at every setting: everything here is on the public server list already.
// The count is a number and names nobody; the names are `/online`'s business.
const c = require('./common')
/** One line per server, for the fleet view. */
function summary(server, now) {
const parts = [server.online ? `Online · ${c.playerCount(server)}` : 'Offline']
if (server.wipedAt) parts.push(`wiped ${c.ago(server.wipedAt, now)}`)
return parts.join(' · ')
}
function detail(server, now) {
const fields = [
{ name: 'Status', value: server.online ? 'Online' : 'Offline', inline: true },
{ name: 'Players', value: server.online ? c.playerCount(server) : '—', inline: true },
]
if (server.worldSize) {
fields.push({ name: 'Map', value: server.seed != null ? `${server.worldSize} · seed ${server.seed}` : String(server.worldSize), inline: true })
}
if (server.wipedAt) fields.push({ name: 'Last wipe', value: c.when(server.wipedAt, now), inline: false })
const next = c.nextWipeText(server, now)
if (next) fields.push({ name: 'Next wipe', value: next, inline: false })
// An offline server says when it was last heard from, which is the difference
// between "down for a restart" and "gone for a week". A server nothing has ever
// heard from says so rather than printing the epoch.
if (!server.online) {
fields.push({ name: 'Last seen', value: server.lastSeenAt ? c.when(server.lastSeenAt, now) : 'never', inline: false })
}
return { title: server.name, url: c.serverUrl(server), fields }
}
async function handler({ options }) {
const now = Date.now()
const picked = c.pickServer(await c.listServers(now), options && options.server)
const refusal = c.pickRefusal(picked)
if (refusal) return refusal
if (picked.server) return detail(picked.server, now)
// An embed takes 25 fields. A fleet larger than that is a site that has a
// server list page, and the title links to it.
return {
title: 'Rust servers',
url: c.pageUrl('/rust'),
fields: picked.all.slice(0, 25).map((s) => ({ name: s.name, value: summary(s, now), inline: false })),
}
}
module.exports = {
name: 'status',
description: 'Is a Rust server up, how many are on, and when it last wiped',
options: [{ name: 'server', type: 'string', description: 'Server name or id (all servers when left out)', required: false }],
// Everyone: nothing here is narrower than public, and the gates that DO matter
// in other commands are resolved inside their handlers.
access: 'everyone',
handler,
}

View File

@@ -0,0 +1,85 @@
// ── `/top [stat] [server] [alltime]` — the leaderboard's top ten (D126) ─────
//
// Public at every setting, as on the web: the leaderboard's NAMES are public, and
// only `lastSeen` sits behind presence (a tally refreshes it every minute a player
// is on, so it is the Online tab by another name). This answer never carries a
// `lastSeen`, and never a Steam id — `events.leaderboard` is asked with
// `presence: false`, so the field is not there to leak.
const c = require('./common')
const events = require('../model/events/events.model')
/** Ten rows: a summary a person reads, not a table they scroll (§32.4 reading 2). */
const LIMIT = 10
// `stat`'s choices are fixed, so they are a `choices` list rather than free
// text. The value is the leaderboard's own sort key.
const STATS = {
kills: { sort: 'kills', label: 'kills', value: (r) => r.kills },
deaths: { sort: 'deaths', label: 'deaths', value: (r) => r.deaths },
npckills: { sort: 'npcKills', label: 'NPC kills', value: (r) => r.npcKills },
playtime: { sort: 'playtime', label: 'playtime', value: (r) => r.playtimeSec, format: hours },
}
function hours(sec) {
const h = Math.floor(sec / 3600)
const m = Math.floor((sec % 3600) / 60)
return h ? `${h}h ${m}m` : `${m}m`
}
async function handler({ options }) {
const now = Date.now()
const stat = STATS[(options && options.stat) || 'kills'] || STATS.kills
// A leaderboard is one server's. With several and none named the command asks
// rather than choosing one, privately — the question is for the caller.
const picked = c.pickServer(await c.listServers(now), options && options.server)
const refusal = c.pickRefusal(picked, { needOne: true })
if (refusal) return refusal
const { server } = picked
// The current wipe unless asked for all-time. A server that has not reported
// a wipe yet has nothing to scope to, and all-time is the honest answer.
const allTime = Boolean(options && options.alltime) || !server.wipeId
const rows = await events.leaderboard({
serverId: server.id,
wipeId: allTime ? null : server.wipeId,
sort: stat.sort,
limit: LIMIT,
presence: false,
})
const scope = allTime ? 'all time' : 'this wipe'
const title = `${server.name} — top ${stat.label}, ${scope}`
if (!rows.length) return { title, url: c.serverUrl(server), text: `Nobody is on the board for ${scope} yet.` }
const format = stat.format || String
return {
title,
url: c.serverUrl(server),
text: rows.map((r, i) => `${i + 1}. ${r.name || 'Unknown player'} — ${format(stat.value(r))}`).join('\n'),
}
}
module.exports = {
name: 'top',
description: 'The top ten players on a Rust server by kills, deaths, NPC kills or playtime',
options: [
{
name: 'stat',
type: 'string',
description: 'What to rank by (kills when left out)',
required: false,
choices: [
{ name: 'Kills', value: 'kills' },
{ name: 'Deaths', value: 'deaths' },
{ name: 'NPC kills', value: 'npckills' },
{ name: 'Playtime', value: 'playtime' },
],
},
{ name: 'server', type: 'string', description: 'Server name or id (needed when there are several)', required: false },
{ name: 'alltime', type: 'boolean', description: 'Every wipe rather than the current one', required: false },
],
access: 'everyone',
handler,
}

View File

@@ -0,0 +1,38 @@
// ── `/wipe [server]` — when it wipes next, and when it last did (D128) ──────
//
// Public: a wipe date is announced to bring players back. The next wipe is the
// operator's schedule, computed on this read (`model/servers/nextWipe.js`); a
// server with no schedule says so and shows only the last wipe it reported.
const c = require('./common')
function lines(server, now) {
return [
`Next: ${c.nextWipeText(server, now) || 'no schedule set'}`,
`Last: ${server.wipedAt ? c.when(server.wipedAt, now) : 'not reported yet'}`,
].join('\n')
}
async function handler({ options }) {
const now = Date.now()
const picked = c.pickServer(await c.listServers(now), options && options.server)
const refusal = c.pickRefusal(picked)
if (refusal) return refusal
if (picked.server) {
return { title: `${picked.server.name} — wipes`, url: c.serverUrl(picked.server), text: lines(picked.server, now) }
}
return {
title: 'Wipes',
url: c.pageUrl('/rust'),
fields: picked.all.slice(0, 25).map((s) => ({ name: s.name, value: lines(s, now), inline: false })),
}
}
module.exports = {
name: 'wipe',
description: 'When a Rust server wipes next, and when it last wiped',
options: [{ name: 'server', type: 'string', description: 'Server name or id (all servers when left out)', required: false }],
access: 'everyone',
handler,
}

527
server/configEdit.js Normal file
View File

@@ -0,0 +1,527 @@
// ── Editing a plugin's config without rewriting the numbers ───────────────
//
// R18's base tier generates a form from a config file's VALUES — a boolean
// becomes a toggle, a number a field, a string a text box — so it works for
// whatever plugins an operator happens to have installed, including ones added
// after we shipped. This file is the half of that which cannot be done naively.
//
// ── The trap ──────────────────────────────────────────────────────────────
//
// **JavaScript cannot tell `1` from `1.0`.** `JSON.parse('{"Rate":1.0}')` yields
// the number `1`, and `JSON.stringify` writes it back as `1`. Both frameworks
// deserialize a config into typed C# classes, so a naive read-modify-write
// silently rewrites every whole-numbered float as an integer — **on fields
// nobody touched** — and Newtonsoft may coerce it or may throw. A throw at load
// means the plugin does not come back, and R6/R17 make four of them required.
//
// The fields at risk are exactly the ones a Rust server tunes: gather rates,
// multipliers, scales.
//
// ── So nothing here ever parses, mutates and re-serialises ────────────────
//
// `scan` is a JSON reader that records, for every value, the **span of source
// text** it came from. `applyEdits` splices new literals into those spans and
// leaves every other byte of the document exactly as it was — including the
// author's indentation, key order, and the `.0` on a float nobody edited.
//
// Two rules fall out of that and both are deliberate:
//
// 1. **A number's new value arrives as the literal text an admin typed**, never
// as a JavaScript number. `2.50` stays `2.50`; `1.0` stays `1.0`. The value
// never becomes a `Number` anywhere in this module, which is the only way to
// be sure it cannot be re-serialised into something else.
// 2. **The generated form is type-preserving.** An edit may change what a value
// IS, never what KIND of thing it is; changing a number into a string, or
// adding a key, is a structural change and belongs in the raw-JSON tier,
// where the admin is editing the document itself.
//
// Nothing in this file touches the network, a database, or core.
/** Value kinds this module names, in the language the form speaks. */
const KINDS = ['object', 'array', 'string', 'number', 'boolean', 'null']
/**
* A JSON number, by the grammar rather than by `Number()`.
*
* Used to judge a literal an admin typed. `Number('0x10')`, `Number('')` and
* `Number(' 1 ')` are all happily finite and none of the three is JSON, so the
* check has to be the grammar — which is also what keeps `1.0` and `1e3`
* acceptable, since preserving those is the entire point.
*/
const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/
/**
* Words that make a value a secret.
*
* Matched against the key split into WORDS, not as a substring: `Monkey` and
* `Keybind` contain "key" and neither is a credential, and a config editor that
* masked every third field would teach an operator to ignore the mask.
*/
const SECRET_WORDS = new Set([
'key',
'keys',
'apikey',
'token',
'tokens',
'secret',
'secrets',
'password',
'passwd',
'pass',
'webhook',
'webhooks',
'credential',
'credentials',
'auth',
])
class JsonScanError extends Error {}
/**
* Reads `text` into a tree of nodes that remember where they came from.
*
* Every node carries `start` and `end`, the half-open span of the value in the
* source. A caller that only wants the data can read `value`; a caller that
* wants to CHANGE the data uses the span, because the span is the only thing
* that survives a round trip unchanged.
*
* @param {string} text
* @returns {object} the root node
* @throws {JsonScanError} with a position, on anything that is not JSON
*/
function scan(text) {
const src = String(text)
let at = 0
function fail(message) {
throw new JsonScanError(`${message} at offset ${at}`)
}
function ws() {
while (at < src.length && (src[at] === ' ' || src[at] === '\t' || src[at] === '\n' || src[at] === '\r')) at += 1
}
function literal(word, value) {
if (src.startsWith(word, at)) {
const start = at
at += word.length
return { type: word === 'null' ? 'null' : 'boolean', value, start, end: at }
}
return null
}
function string() {
const start = at
at += 1 // the opening quote
let out = ''
while (at < src.length) {
const ch = src[at]
if (ch === '"') {
at += 1
return { type: 'string', value: out, start, end: at }
}
if (ch === '\\') {
const esc = src[at + 1]
at += 2
if (esc === 'u') {
const hex = src.slice(at, at + 4)
if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('bad unicode escape')
out += String.fromCharCode(parseInt(hex, 16))
at += 4
} else if (esc === 'n') out += '\n'
else if (esc === 't') out += '\t'
else if (esc === 'r') out += '\r'
else if (esc === 'b') out += '\b'
else if (esc === 'f') out += '\f'
else if (esc === '"' || esc === '\\' || esc === '/') out += esc
else fail('bad escape')
continue
}
out += ch
at += 1
}
return fail('unterminated string')
}
function number() {
const start = at
if (src[at] === '-') at += 1
while (at < src.length && /[0-9]/.test(src[at])) at += 1
if (src[at] === '.') {
at += 1
while (at < src.length && /[0-9]/.test(src[at])) at += 1
}
if (src[at] === 'e' || src[at] === 'E') {
at += 1
if (src[at] === '+' || src[at] === '-') at += 1
while (at < src.length && /[0-9]/.test(src[at])) at += 1
}
const raw = src.slice(start, at)
if (!JSON_NUMBER.test(raw)) fail(`'${raw}' is not a number`)
// `raw` is the fact; `value` is a convenience for rendering and comparison,
// and is never written back to the document.
return { type: 'number', value: Number(raw), raw, start, end: at }
}
function value() {
ws()
const ch = src[at]
if (ch === '{') return object()
if (ch === '[') return array()
if (ch === '"') return string()
if (ch === '-' || (ch >= '0' && ch <= '9')) return number()
const lit = literal('true', true) || literal('false', false) || literal('null', null)
if (lit) return lit
return fail('unexpected character')
}
function object() {
const start = at
at += 1 // {
const children = []
ws()
if (src[at] === '}') {
at += 1
return { type: 'object', children, start, end: at }
}
for (;;) {
ws()
if (src[at] !== '"') fail('expected a key')
const key = string()
ws()
if (src[at] !== ':') fail('expected a colon')
at += 1
const child = value()
child.key = key.value
child.keyStart = key.start
child.keyEnd = key.end
children.push(child)
ws()
if (src[at] === ',') {
at += 1
continue
}
if (src[at] === '}') {
at += 1
return { type: 'object', children, start, end: at }
}
return fail('expected a comma or a closing brace')
}
}
function array() {
const start = at
at += 1 // [
const children = []
ws()
if (src[at] === ']') {
at += 1
return { type: 'array', children, start, end: at }
}
for (;;) {
const child = value()
child.index = children.length
children.push(child)
ws()
if (src[at] === ',') {
at += 1
continue
}
if (src[at] === ']') {
at += 1
return { type: 'array', children, start, end: at }
}
return fail('expected a comma or a closing bracket')
}
}
const root = value()
ws()
if (at !== src.length) fail('trailing content')
return root
}
/** Splits a config key into words, across camelCase, snake_case, spaces and dots. */
function words(key) {
return String(key)
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.split(/[^A-Za-z0-9]+/)
.filter(Boolean)
.map((w) => w.toLowerCase())
}
/**
* Whether a key names a credential. See `SECRET_WORDS`.
*
* **A field flagged here is not emptied.** D37 decided the raw tier shows real
* values — an admin can already read the file over SSH — so the API answers with
* the document as it is, the form renders a flagged field masked with a reveal
* control, and the flag's load-bearing use is the audit trail, where the values
* genuinely never appear.
*/
function isSecretKey(key) {
return words(key).some((w) => SECRET_WORDS.has(w))
}
/** A pointer as a person reads it: `Settings.Rates[0].Wood`. */
function pointerPath(pointer) {
return pointer
.map((step) => (typeof step === 'number' ? `[${step}]` : step))
.join('.')
.replace(/\.\[/g, '[')
}
/**
* Walks a scanned tree into the flat description the form is built from.
*
* **What is NOT here is as deliberate as what is.** There are no descriptions,
* no minimums, no maximums and no allowed-value sets, because a config file
* carries none: the key name is the entire label. An empty array and a `null`
* carry no type at all, so nothing can be inferred for them and they are marked
* `advanced` — the raw tier is where a value with no shape gets edited.
*
* @param {object} root from `scan`
* @param {object} [options]
* @param {number} [options.maxDepth] past this, a subtree is advanced-only
* @param {string[]} [options.locked] top-level keys that may not be edited (D38)
*/
function describe(root, { maxDepth = 6, locked = [] } = {}) {
const lockedSet = new Set(locked.map((k) => String(k).toLowerCase()))
const fields = []
function visit(node, pointer, depth, inheritedSecret, inheritedLock) {
const key = pointer.length ? pointer[pointer.length - 1] : ''
const secret = inheritedSecret || (typeof key === 'string' && isSecretKey(key))
const isLocked =
inheritedLock || (pointer.length === 1 && typeof key === 'string' && lockedSet.has(key.toLowerCase()))
if (node.type === 'object' || node.type === 'array') {
const tooDeep = depth >= maxDepth
fields.push({
pointer: [...pointer],
path: pointerPath(pointer),
key: typeof key === 'number' ? `[${key}]` : key,
type: node.type,
depth,
count: node.children.length,
secret,
locked: isLocked,
// An empty container has nothing to infer a member's shape from, and a
// container past the depth limit has more shape than a form should try
// to draw. Both are honest reasons to send somebody to the raw tier.
advanced: tooDeep || node.children.length === 0,
...(tooDeep ? { reason: 'deeper than the form will draw' } : {}),
...(node.children.length === 0 ? { reason: 'empty, so there is no shape to read' } : {}),
})
if (tooDeep) return
node.children.forEach((child, index) => {
visit(child, [...pointer, node.type === 'array' ? index : child.key], depth + 1, secret, isLocked)
})
return
}
fields.push({
pointer: [...pointer],
path: pointerPath(pointer),
key: typeof key === 'number' ? `[${key}]` : key,
type: node.type,
depth,
// A number is reported as its LITERAL as well as its value. The literal is
// what the form must round-trip; the value is for display and sorting.
...(node.type === 'number' ? { raw: node.raw } : {}),
value: node.value,
secret,
locked: isLocked,
// `null` has no type, so there is nothing to render but a raw editor.
advanced: node.type === 'null',
...(node.type === 'null' ? { reason: 'null carries no type to read' } : {}),
})
}
visit(root, [], 0, false, false)
return fields
}
/** Finds the node a pointer names, or null. */
function resolve(root, pointer) {
let node = root
for (const step of pointer) {
if (!node || (node.type !== 'object' && node.type !== 'array')) return null
if (node.type === 'array') {
if (typeof step !== 'number') return null
node = node.children[step]
} else {
node = node.children.find((child) => child.key === step)
}
if (!node) return null
}
return node
}
/** The exact source text a node was read from. */
function literalOf(text, node) {
return String(text).slice(node.start, node.end)
}
/**
* Turns one edit into the literal that will be spliced in, or explains why not.
*
* `raw` is used verbatim for a number — that is the whole mechanism — and is
* validated against the JSON grammar first, because verbatim and unvalidated
* would be a way to write anything at all into somebody's config file.
*/
function literalFor(node, edit) {
if (node.type === 'number') {
const raw = String(edit.raw !== undefined && edit.raw !== null ? edit.raw : edit.value).trim()
if (!JSON_NUMBER.test(raw)) return { error: `'${raw}' is not a number` }
return { literal: raw }
}
if (node.type === 'string') {
if (typeof edit.value !== 'string') return { error: 'expected text' }
return { literal: JSON.stringify(edit.value) }
}
if (node.type === 'boolean') {
if (typeof edit.value !== 'boolean') return { error: 'expected true or false' }
return { literal: edit.value ? 'true' : 'false' }
}
return { error: `a ${node.type} is edited in the raw tier` }
}
/**
* Applies a set of edits to a document and returns the new text.
*
* Spans are spliced from the **end of the document backwards**, so that an
* earlier edit never moves a later edit's offsets. Every edit is resolved and
* checked before any splice happens: a refusal leaves the caller with the
* original text rather than a partly-edited one.
*
* @param {string} text
* @param {Array<{pointer: Array<string|number>, value?: any, raw?: string}>} edits
* @returns {{ text?: string, changes?: object[], error?: string }}
*/
function applyEdits(text, edits, { locked = [] } = {}) {
let root
try {
root = scan(text)
} catch (err) {
return { error: `the file on the server is not valid JSON: ${err.message}` }
}
const lockedSet = new Set(locked.map((k) => String(k).toLowerCase()))
const staged = []
const seen = new Set()
for (const edit of edits || []) {
const pointer = Array.isArray(edit.pointer) ? edit.pointer : null
if (!pointer || pointer.length === 0) return { error: 'an edit must name a field' }
const path = pointerPath(pointer)
if (seen.has(path)) return { error: `'${path}' is edited twice in one save` }
seen.add(path)
if (typeof pointer[0] === 'string' && lockedSet.has(pointer[0].toLowerCase())) {
return { error: `'${path}' cannot be edited from the website` }
}
const node = resolve(root, pointer)
if (!node) return { error: `'${path}' is not in this file` }
const { literal, error } = literalFor(node, edit)
if (error) return { error: `'${path}': ${error}` }
staged.push({
path,
pointer,
start: node.start,
end: node.end,
from: literalOf(text, node),
to: literal,
secret: pointer.some((step) => typeof step === 'string' && isSecretKey(step)),
})
}
// Nothing to do is not an error, but it must not produce a write either: a
// save with no changes would spend a reload — and a reload is the one part of
// this feature that can take a plugin down.
const changed = staged.filter((s) => s.from !== s.to)
if (changed.length === 0) return { text: String(text), changes: [] }
let out = String(text)
for (const edit of [...changed].sort((a, b) => b.start - a.start)) {
out = out.slice(0, edit.start) + edit.to + out.slice(edit.end)
}
// The result must still be JSON. It always is when the pieces are — this is a
// guard against a bug in this file, not against the caller.
try {
scan(out)
} catch (err) {
return { error: `the edit produced something that is not JSON: ${err.message}` }
}
return { text: out, changes: changed.map(redactChange) }
}
/**
* What the audit trail records for one changed field.
*
* **A secret's values are never written down.** The raw tier shows real values
* to an admin who asks for them, which is a deliberate decision (D37) about a
* page somebody has to open — but an activity log is read by more people, for
* longer, and usually by somebody who was not there. Those are different
* exposures and they get different answers.
*/
function redactChange(change) {
return {
path: change.path,
from: change.secret ? '***' : change.from,
to: change.secret ? '***' : change.to,
...(change.secret ? { secret: true } : {}),
}
}
module.exports = {
KINDS,
JSON_NUMBER,
JsonScanError,
scan,
describe,
resolve,
applyEdits,
isSecretKey,
pointerPath,
words,
}

View File

@@ -86,6 +86,14 @@ module.exports = {
// that needs an identity needs to *read* one.
auth: { getUserFromRequest: (...args) => need().auth.getUserFromRequest(...args) },
// One user by id (MODULE_API.md §2.3, 1.1.0). Here for the presence gate
// (`model/visibility`): `getUserFromRequest` decodes a token and nothing more,
// so the role in it is the role the account had when the token was minted. A
// moderator demoted this morning would keep reading who is online until their
// token expired. Re-reading the row is what makes a demotion — or a ban — take
// effect on the next request, the same promise core's admin tier makes.
users: { getById: (...args) => need().users.getById(...args) },
// Core's middleware, taken as values rather than wrapped: express stores the
// function reference at mount time, so a wrapper is what would end up in the
// stack. Routers are built inside `register()`, so `ctx` is set by then.
@@ -141,9 +149,41 @@ module.exports = {
// would be worse, since a module has more than one thing it could reconcile.
reconcileEvents: () => need().events.reconcile(),
// MODULE_API 1.11.0 (PLAN_FIXES F14, D170, D183). The game ended one of this
// module's ledgered resources at its own deadline — a zone the plugin erased
// when its time was up (`world.expired`). Core files it `expired`: terminal,
// never taken back at teardown, and not `orphaned`, which is reconcile's word
// for something that vanished with nobody asking. Fire and forget, and a
// `{ kind, ref }` no run ledgered is not an error.
expireEvent: (resource) => need().events.expired(resource),
// Teams (MODULE_API.md §2.3, 1.6.0) — the push half of the provider this
// module registers (`model/clans/teamProvider.js`). Three calls, all
// fire-and-forget, and core's contract is that none of them can make this
// module's call site slow or turn a background failure into its error:
//
// publish(event) a membership or leadership change, as it happened
// reconcile({reason}) "the set may have changed, come and ask" — debounced
// pushActivity(items) the per-Team feed, idempotent on each item's dedupeKey
//
// Correctness comes from reconciliation either way; `publish` only makes a
// change visible sooner. Wrapped as calls, like `emit`, so a file that takes
// `core.teams` at require time still resolves `ctx` when it is used.
teams: {
publish: (event) => need().teams.publish(event),
reconcile: (options) => need().teams.reconcile(options),
pushActivity: (items) => need().teams.activity.push(items),
},
// Deployment facts. `moduleRoot` is the absolute path to `modules/<id>/` — the
// only correct way to find a file you shipped, because the working directory is
// core's and the module's location is the loader's business.
get moduleRoot() { return need().paths.moduleRoot },
get moduleId() { return need().moduleId },
// The site's public address, with no trailing slash (§2.3, 1.1.0). Phase 16's
// slash commands link an answer's title to its page; a chat message has no
// origin to be relative to. A getter over core's getter, so an operator who
// changes `APP_BASE_URL` is read at the call, never captured at load.
get baseUrl() { return need().site.baseUrl },
}

View File

@@ -19,5 +19,70 @@
-- it knows this module registered, because it is the side that knows which
-- registrant owned what.
-- RunicNPC (runicnpc PLAN.md stage 4). Children before `rust_npc_profiles`.
DROP TABLE IF EXISTS rust_npc_factions;
DROP TABLE IF EXISTS rust_npc_kills;
DROP TABLE IF EXISTS rust_npc_sync;
DROP TABLE IF EXISTS rust_npc_profile_servers;
DROP TABLE IF EXISTS rust_npc_profiles;
-- Zone presets (PLAN_REDESIGNS §3.1). The server list before its preset.
DROP TABLE IF EXISTS rust_zone_preset_servers;
DROP TABLE IF EXISTS rust_zone_presets;
-- The chat-title conditions (PLAN_REDESIGNS §5). No foreign keys; the stats
-- columns go with their table below.
DROP TABLE IF EXISTS rust_title_categories;
DROP TABLE IF EXISTS rust_weapon_kills;
-- The permission manager, rebuilt (PLAN_REDESIGNS §1). Children before
-- `rust_permgroups`, which they reference.
DROP TABLE IF EXISTS rust_perm_exceptions;
DROP TABLE IF EXISTS rust_perm_steam_grants;
DROP TABLE IF EXISTS rust_permgroup_chat;
DROP TABLE IF EXISTS rust_permgroup_steam_members;
DROP TABLE IF EXISTS rust_permgroup_members;
DROP TABLE IF EXISTS rust_permgroup_permissions;
DROP TABLE IF EXISTS rust_permgroup_servers;
DROP TABLE IF EXISTS rust_permgroups;
-- Phase 17. `rust_perm_group_chat` before `rust_perm_groups`, which it
-- references; the rest of this phase is columns, which go with their tables.
DROP TABLE IF EXISTS rust_perm_group_chat;
DROP TABLE IF EXISTS rust_title_rules;
-- Phase 14.
DROP TABLE IF EXISTS rust_map_overrides;
DROP TABLE IF EXISTS rust_map_images;
-- Phase 13b.
DROP TABLE IF EXISTS rust_perm_run_grants;
-- Phase 7b.
DROP TABLE IF EXISTS rust_clan_boards;
DROP TABLE IF EXISTS rust_clan_members;
DROP TABLE IF EXISTS rust_clans;
DROP TABLE IF EXISTS rust_settings;
DROP TABLE IF EXISTS rust_config_writes;
-- Phase 7. Children before parents: every one of these carries a foreign key
-- into `rust_servers`, `users` or `rust_perm_groups`.
DROP TABLE IF EXISTS rust_perm_catalogue;
DROP TABLE IF EXISTS rust_perm_sync;
DROP TABLE IF EXISTS rust_perm_revocations;
DROP TABLE IF EXISTS rust_perm_drift;
DROP TABLE IF EXISTS rust_perm_pushed;
DROP TABLE IF EXISTS rust_perm_grants;
DROP TABLE IF EXISTS rust_perm_group_members;
DROP TABLE IF EXISTS rust_perm_group_permissions;
DROP TABLE IF EXISTS rust_perm_groups;
DROP TABLE IF EXISTS rust_account_links;
DROP TABLE IF EXISTS rust_ingest_cursor;
DROP TABLE IF EXISTS rust_presence;
DROP TABLE IF EXISTS rust_events;
DROP TABLE IF EXISTS rust_gather_totals;
DROP TABLE IF EXISTS rust_player_wipe_stats;
DROP TABLE IF EXISTS rust_players;
DROP TABLE IF EXISTS rust_wipes;
DROP TABLE IF EXISTS rust_server_state;
DROP TABLE IF EXISTS rust_servers;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
// ── Named sets of people, over this module's own data ─────────────────────
//
// `registerAudiences` (MODULE_API.md §2.4; PLAN.md §25.2). An operator points a
// rule or a segment at one of these; core calls `resolve` when a rule fires.
//
// Three properties, each the contract rather than a style:
//
// • **A resolver returns website user ids and nothing else.** Never an
// address, a channel or a Steam id: core maps ids to people after the
// preferences, the suppression list and the verification gate, and a module
// that could hand it anything else would have a way to send mail.
// • **One that fails answers NOBODY** — never everybody, never its last good
// answer. A throw here is caught and returned as `[]`, and core treats a
// throw the same way; both are here so the property does not rest on
// either side alone.
// • **Params are constants**, fixed when an operator saves the rule. "The clan
// this event was about" is therefore not expressible as an audience — a
// clan trigger carries its own recipients instead (`emit.js`).
const core = require('../core')
const log = core.logger('audiences')
const LINKS = 'rust_account_links'
/** Wraps a resolver so a failure is an empty set, logged, and never a throw. */
function safe(id, fn) {
return async (params) => {
try {
const rows = await fn(params || {})
return rows.map((r) => Number(r.userId)).filter((n) => Number.isInteger(n) && n > 0)
} catch (err) {
log.warn('an audience could not be resolved; it answers nobody', { audience: id, error: err.message })
return []
}
}
}
const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null)
const AUDIENCES = Object.freeze([
{
id: 'rust.clan.members',
label: 'Members of a clan',
params: [{ id: 'clan', type: 'string', required: true }],
ceiling: 'members',
// A clan's LINKED members, as the store holds them now. A clan that has
// been disbanded has no roster, so a rule saved against it resolves to
// nobody — which is the truth, and not the same as the audience being gone.
resolve: safe('rust.clan.members', async ({ clan }) => {
const key = text(clan)
if (!key) return []
return core.query(
`SELECT DISTINCT l.user_id AS userId
FROM rust_clan_members m
JOIN rust_clans c ON c.external_id = m.external_id AND c.gone_at IS NULL
JOIN ${LINKS} l ON l.steam_id = m.steam_id
WHERE m.external_id = ?`,
[key],
)
}),
},
{
id: 'rust.server.players',
label: 'Everyone who has played on a server',
params: [{ id: 'serverId', type: 'string', required: true }],
ceiling: 'authenticated',
// Linked accounts with a stats row on this server in ANY wipe. The stats
// table is the record of having played, and it outlives both wipes and the
// raw event history (R12).
resolve: safe('rust.server.players', async ({ serverId }) => {
const id = text(serverId)
if (!id) return []
return core.query(
`SELECT DISTINCT l.user_id AS userId
FROM rust_player_wipe_stats s
JOIN ${LINKS} l ON l.steam_id = s.steam_id
WHERE s.server_id = ?`,
[id],
)
}),
},
{
id: 'rust.wipe.participants',
label: 'Everyone playing a server\'s current wipe',
params: [{ id: 'serverId', type: 'string', required: true }],
ceiling: 'authenticated',
// The same, narrowed to the wipe the server is on NOW. Resolved at send
// time, so a rule saved last month reaches this month's players — which is
// what "current" has to mean for a parameter fixed when the rule was saved.
// A server with no known wipe resolves to nobody rather than to every wipe.
resolve: safe('rust.wipe.participants', async ({ serverId }) => {
const id = text(serverId)
if (!id) return []
return core.query(
`SELECT DISTINCT l.user_id AS userId
FROM rust_server_state st
JOIN rust_player_wipe_stats s ON s.server_id = st.server_id AND s.wipe_id = st.wipe_id
JOIN ${LINKS} l ON l.steam_id = s.steam_id
WHERE st.server_id = ? AND st.wipe_id IS NOT NULL`,
[id],
)
}),
},
])
module.exports = { AUDIENCES }

644
server/engagement/emit.js Normal file
View File

@@ -0,0 +1,644 @@
// ── What happened, told to core's engagement engine ───────────────────────
//
// The fan-out behind `triggers.js` (PLAN.md §25). Ingest calls `onEvent` for
// every frame it stores; the refresh calls `serverObserved` for every poll;
// ingest calls `checkLeader` after a batch; the prune timer calls
// `sweepLoginDenied`; the link route calls `linked`.
//
// **Nothing here decides who is told.** It says what happened and, for a
// personal or clan event, who it is ABOUT. Core applies the rule, the ceiling,
// the preference, the suppression list and the verification gate. A module
// cannot send mail (MODULE_API.md §2.7), and this file is not the back door.
//
// **Nothing here throws into its caller.** Every entry point catches, because
// its callers are the ingest cursor and the refresh loop — a malformed frame or
// a core-side contract problem must cost one notification and never the feed.
//
// ── Three rules the whole file follows ────────────────────────────────────
//
// 1. **Emit on the transition, never on the poll** (R7). A server that is
// still up is not news. Transitions are tracked in memory, and a FIRST
// sighting is never one — so a website restart announces nothing.
//
// 2. **A replayed event notifies only while it is still news** (D63). After an
// outage the cursor replays hours of frames. A broadcast older than 15
// minutes tells nobody; a personal or staff event is kept for 24 hours,
// because "your base was raided at 03:10" is still true and still wanted.
//
// 3. **Every emit carries a dedupe key made from the EVENT, not the store.**
// Core's outbox is unique on (rule, user, channel, key), so the same frame
// replayed after a crash is a no-op. The key is built from what the event
// says — its server, time and subject — rather than from the sidecar's row
// id, because a sidecar whose database is replaced starts its ids again
// and would otherwise have every new alert swallowed as a repeat of an old
// one.
const crypto = require('crypto')
const core = require('../core')
const clans = require('../model/clans/clans.model')
const clansDb = require('../model/clans/clans.db')
const eventsDb = require('../model/events/events.db')
const linksDb = require('../model/links/links.db')
const serversDb = require('../model/servers/servers.db')
const { TRIGGER_IDS: T, PATHS, serverPath, leaderboardPath, clanPath } = require('./triggers')
const log = core.logger('engagement')
/** How old a broadcast may be and still be news (D63). */
const BROADCAST_MAX_AGE_MS = 15 * 60 * 1000
/** How old a personal or staff event may be and still be worth telling (D63). */
const PERSONAL_MAX_AGE_MS = 24 * 60 * 60 * 1000
/**
* How long a login attempt waits for its approval before it counts as denied
* (D64, PLAN.md §16.5). The game raises no rejection hook, so a denial is the
* ABSENCE of an approval — which is only knowable after a wait.
*/
const LOGIN_APPROVAL_WINDOW_MS = 60 * 1000
/** How far BEFORE an attempt an approval may be stamped and still answer it — clock grain, not policy. */
const LOGIN_APPROVAL_SLACK_MS = 5 * 1000
const STRUCTURE_LABELS = Object.freeze({
block: 'building block',
door: 'door',
wall: 'external wall',
cupboard: 'tool cupboard',
})
// ── Small helpers ──────────────────────────────────────────────────────────
const str = (value) => (value === undefined || value === null || value === '' ? undefined : String(value))
/** `rust:<what>:<sha1 of the parts>` — readable prefix, bounded length. */
function dedupeKey(what, ...parts) {
const digest = crypto.createHash('sha1').update(parts.map((p) => String(p ?? '')).join('\u0000')).digest('hex')
return `rust:${what}:${digest}`
}
function frameTime(item, frame) {
const t = Number(frame && frame.t) || Number(item && item.t)
return Number.isFinite(t) && t > 0 ? t : Date.now()
}
/** D63, as a question: is an event from `t` still worth telling, for this family? */
function stillNews(t, maxAgeMs, now = Date.now()) {
return now - t <= maxAgeMs
}
function serverVars(server) {
const serverId = String(server.id)
return { serverId, server: server.name || serverId, serverUrl: serverPath(serverId) }
}
/**
* The headline every trigger carries (`triggers.js` HEADLINE).
*
* Core's generic bodies fall back to a trigger's LABEL and DESCRIPTION when the
* payload has no `title`/`intro`, and on a multi-server site that fallback says
* "A server came online" without ever saying which. So the sentence is written
* here, from the payload, and core renders it. Plain register, no conditionals:
* a missing part falls back to a neutral word rather than leaving a hole.
*/
const HEADLINES = Object.freeze({
'rust.base.destroyed': (d) => ({
title: `Your base on ${d.server} is being raided`,
intro: `A ${d.structure} was destroyed${d.atGrid || ''} on ${d.server}.`,
}),
'rust.wipe.started': (d) => ({
title: `${d.server} has wiped`,
intro: `A new wipe has started on ${d.server}: a fresh map, and a fresh start for everyone.`,
}),
'rust.server.online': (d) => ({
title: `${d.server} is online`,
intro: `${d.server} is back up and talking to the website.`,
}),
'rust.server.offline': (d) => ({
title: `${d.server} is offline`,
intro: `${d.server} stopped, or stopped talking to the website.`,
}),
'rust.leaderboard.topped': (d) => ({
title: `${d.leader} leads ${d.server}`,
intro: `${d.leader} now leads this wipe's kills on ${d.server}, with ${d.kills}.`,
}),
'rust.player.linked': (d) => ({
title: 'A Steam account was linked to your account',
intro: `The Steam account ${d.player || d.steamId} was linked with an in-game code. `
+ 'If that was not you, unlink it from your Rust account page.',
}),
'rust.kit.entitled': (d) => ({
title: `You earned ${d.kit} on ${d.server}`,
intro: `An event on ${d.server} rewarded you: the ${d.kit} kit is waiting in the Kits menu, `
+ 'with one extra use. Redeem it in game.',
}),
'rust.clan.member.left': (d) => ({
title: `${d.member || 'A member'} left ${d.clan}`,
intro: `${d.member || 'A member'} left ${d.clan} on ${d.server}.`,
}),
'rust.clan.member.kicked': (d) => ({
title: `${d.member || 'A member'} was removed from ${d.clan}`,
intro: `${d.by || 'A clan leader'} removed ${d.member || 'a member'} from ${d.clan} on ${d.server}.`,
}),
'rust.clan.disbanded': (d) => ({
title: `${d.clan} was disbanded`,
intro: `${d.by || 'A clan leader'} disbanded ${d.clan} on ${d.server}.`,
}),
'rust.player.reported': (d) => ({
title: `${d.player || d.steamId} was reported on ${d.server}`,
intro: `${d.reporter || 'A player'} reported ${d.player || d.steamId}`
+ `${d.reportType ? ` (${d.reportType})` : ''}${d.topic ? `: ${d.topic}` : '.'}`,
}),
'rust.player.banned': (d) => ({
title: `${d.player || d.steamId} was banned on ${d.server}`,
intro: d.reason ? `Reason given: ${d.reason}` : 'No reason was given.',
}),
'rust.player.unbanned': (d) => ({
title: `${d.player || d.steamId} was unbanned on ${d.server}`,
intro: `The ban on ${d.player || d.steamId} (${d.steamId}) was lifted.`,
}),
'rust.npc.died': (d) => ({
title: `${d.npc || d.profile} was killed on ${d.server}`,
intro: `${d.killer ? `${d.killer} killed` : 'Something killed'} ${d.npc || 'an NPC'} (${d.profile}) on ${d.server}.`,
}),
'rust.npc.health': (d) => ({
title: `${d.npc || d.profile} is below ${d.percent}% on ${d.server}`,
intro: `${d.npc || 'An NPC'} (${d.profile}) fell to ${d.percent}% of its health on ${d.server}.`,
}),
'rust.login.denied': (d) => ({
title: `A login to ${d.server} was not approved`,
intro: `${d.player || 'Someone'} (${d.steamId}) tried to join ${d.server} and was not let in within a minute.`,
}),
})
function headline(triggerId, data) {
const make = HEADLINES[triggerId]
return make ? make(data || {}) : {}
}
/**
* Hands one event to core. Never throws.
*
* Core throws on a contract mismatch outside production, which is how a
* declaration and an emitter drifting apart is meant to be found. It is logged
* at `error` here rather than re-thrown, because the caller is the ingest
* cursor — and an `error` line is what a rig walk reads.
*/
function fire(triggerId, envelope) {
try {
const data = envelope.data || {}
core.emit(triggerId, { ...envelope, data: { ...headline(triggerId, data), ...data } })
return true
} catch (err) {
log.error('core refused an emit', { trigger: triggerId, error: err.message })
return false
}
}
/** Steam id -> website user id, for the ids that are linked. Unlinked ones are simply absent. */
async function usersFor(steamIds) {
const ids = [...new Set((steamIds || []).map(String).filter(Boolean))]
if (!ids.length) return new Map()
const rows = await linksDb.userIdsForSteamIds(ids)
return new Map(rows.map((r) => [String(r.steamId), Number(r.userId)]))
}
// ── Per-kind handlers ──────────────────────────────────────────────────────
/**
* The raid alert (D59-D61, D66, D67).
*
* One emit per authorised, LINKED person, each with `ownerUserId` — so the
* `owner` ceiling holds per emit and "nobody else" is structural rather than a
* filter somebody could forget. Two Steam accounts held by one website user are
* one person: they get one alert, online if either account is.
*/
async function onRaid(server, item, frame) {
const t = frameTime(item, frame)
if (!stillNews(t, PERSONAL_MAX_AGE_MS)) return 0
// D67: no cupboard, nobody to tell. Absent — not empty — is also what a
// protocol-6 plugin sends, so a half-upgraded deployment alerts nobody rather
// than guessing an owner from the placer.
if (!frame.buildingId || !Array.isArray(frame.authorized)) return 0
const authorized = frame.authorized.filter((a) => a && a.steamId)
const attacker = str(frame.attackerId)
// An authorised attacker is demolishing their own base, or a teammate's.
if (attacker && authorized.some((a) => String(a.steamId) === attacker)) return 0
const users = await usersFor(authorized.map((a) => a.steamId))
if (!users.size) return 0
const byUser = new Map()
for (const a of authorized) {
const userId = users.get(String(a.steamId))
if (!userId) continue
byUser.set(userId, byUser.get(userId) === true || a.online === true)
}
const base = {
...serverVars(server),
building: String(frame.buildingId),
structure: STRUCTURE_LABELS[frame.structure] || 'structure',
grid: str(frame.grid),
atGrid: str(frame.grid) ? ` in ${frame.grid}` : undefined,
}
const key = dedupeKey('raid', server.id, frame.buildingId, t, frame.prefab)
let sent = 0
for (const [userId, online] of byUser) {
if (fire(T['rust.base.destroyed'], {
data: { ...base, ownerOnline: online },
ownerUserId: userId,
dedupeKey: key,
occurredAt: t,
})) sent += 1
}
return sent
}
async function onWipe(server, item, frame) {
const t = frameTime(item, frame)
if (!stillNews(t, BROADCAST_MAX_AGE_MS)) return 0
const wipeId = str(frame.wipeId)
if (!wipeId) return 0
return fire(T['rust.wipe.started'], {
data: { ...serverVars(server), wipeId },
dedupeKey: dedupeKey('wipe', server.id, wipeId),
occurredAt: t,
}) ? 1 : 0
}
/**
* Clan departures and disbands. Recipients travel on the envelope, because
* "the clan this was about" is a different set every firing.
*
* Nobody is told about what they did themselves: the leaver is not told they
* left, the one who kicked is not told they kicked, the one who disbanded is not
* told they disbanded. The one KICKED is told — it happened to them.
*/
async function onClan(server, item, frame) {
const t = frameTime(item, frame)
if (!stillNews(t, PERSONAL_MAX_AGE_MS)) return 0
const externalId = await clans.resolveExternalId(server.id, frame)
if (!externalId) return 0
const kind = frame.kind
const subject = str(frame.steamId)
let steamIds
let actor
if (kind === 'clan.disbanded') {
// From the frame (protocol 7): by the time this runs the next board may
// already have removed the roster the store would answer with.
steamIds = Array.isArray(frame.members) ? frame.members.map(String) : null
if (!steamIds) steamIds = (await clansDb.listMembers(externalId)).map((m) => String(m.steamId))
actor = subject
} else {
steamIds = (await clansDb.listMembers(externalId)).map((m) => String(m.steamId))
if (kind === 'clan.member.kicked') {
if (subject) steamIds.push(subject)
actor = str(frame.bySteamId)
} else {
actor = subject
}
}
const users = await usersFor(steamIds.filter((id) => id !== actor))
const recipientUserIds = [...new Set(users.values())]
if (!recipientUserIds.length) return 0
const data = {
...serverVars(server),
clanKey: externalId,
clan: str(frame.clanName) || 'your clan',
clanUrl: clanPath(externalId),
}
if (kind === 'clan.member.left') data.member = str(frame.name)
if (kind === 'clan.member.kicked') {
data.member = str(frame.name)
data.by = str(frame.byName)
}
if (kind === 'clan.disbanded') data.by = str(frame.name)
const triggerId = kind === 'clan.disbanded' ? T['rust.clan.disbanded'] : T[`rust.${kind}`]
return fire(triggerId, {
data,
recipientUserIds,
dedupeKey: dedupeKey(kind, server.id, externalId, subject, t),
occurredAt: t,
}) ? 1 : 0
}
async function onReported(server, item, frame) {
const t = frameTime(item, frame)
if (!stillNews(t, PERSONAL_MAX_AGE_MS)) return 0
const steamId = str(frame.targetId)
if (!steamId) return 0
return fire(T['rust.player.reported'], {
data: {
...serverVars(server),
steamId,
player: str(frame.targetName),
reporter: str(frame.reporterName),
reportType: str(frame.reportType),
topic: str(frame.subject),
message: str(frame.message),
},
dedupeKey: dedupeKey('reported', server.id, steamId, frame.reporterId, t),
occurredAt: t,
}) ? 1 : 0
}
async function onBan(server, item, frame) {
const t = frameTime(item, frame)
if (!stillNews(t, PERSONAL_MAX_AGE_MS)) return 0
const steamId = str(frame.steamId)
if (!steamId) return 0
const banned = frame.kind === 'player.banned'
const data = { ...serverVars(server), steamId, player: str(frame.name) }
// The address the frame carries is deliberately NOT copied: no trigger
// declares one, so no template can ever put it in a mail.
if (banned) data.reason = str(frame.reason)
return fire(banned ? T['rust.player.banned'] : T['rust.player.unbanned'], {
data,
dedupeKey: dedupeKey(frame.kind, server.id, steamId, t),
occurredAt: t,
}) ? 1 : 0
}
/**
* RunicNPC's NPCs (runicnpc stage 4): a death, and a health threshold. What a
* phase gate counts, so the window is short: a death an hour old is history, not
* a wave falling. The dedupe key is the NPC's net id, which the game never
* reuses within a boot.
*/
const NPC_MAX_AGE_MS = 15 * 60 * 1000
function npcVars(server, frame) {
return {
...serverVars(server),
profile: str(frame.profile),
npc: str(frame.name),
byEvent: Boolean(frame.runId),
runId: str(frame.runId),
placement: str(frame.placement),
}
}
async function onNpc(server, item, frame) {
const t = frameTime(item, frame)
if (!stillNews(t, NPC_MAX_AGE_MS) || !str(frame.profile)) return 0
if (frame.kind === 'npc.died') {
const contributors = Array.isArray(frame.contributors) ? frame.contributors : []
return fire(T['rust.npc.died'], {
data: { ...npcVars(server, frame), killer: str(frame.killerName), killerSteamId: str(frame.killerId), contributors: contributors.length },
dedupeKey: dedupeKey('npc.died', server.id, frame.netId, t),
occurredAt: t,
}) ? 1 : 0
}
const percent = Math.round((Number(frame.threshold) || 0) * 100)
return fire(T['rust.npc.health'], {
data: { ...npcVars(server, frame), percent },
dedupeKey: dedupeKey('npc.health', server.id, frame.netId, percent),
occurredAt: t,
}) ? 1 : 0
}
const HANDLERS = Object.freeze({
'npc.died': onNpc,
'npc.health': onNpc,
'entity.destroyed': onRaid,
'server.wipe': onWipe,
'clan.member.left': onClan,
'clan.member.kicked': onClan,
'clan.disbanded': onClan,
'player.reported': onReported,
'player.banned': onBan,
'player.unbanned': onBan,
})
/**
* One stored frame. Called by ingest BEFORE the frame is applied, because
* applying a disband deletes the roster a clan notification is sent to.
*
* @returns {Promise<number>} emits handed to core, for the log and the tests
*/
async function onEvent(server, item) {
const frame = (item && item.frame) || {}
const kind = (item && item.kind) || frame.kind
const handler = HANDLERS[kind]
if (!handler || !server) return 0
try {
return await handler(server, item, { ...frame, kind })
} catch (err) {
log.warn('could not raise a notification', { server: server.id, kind, error: err.message })
return 0
}
}
// ── Transitions tracked in memory ──────────────────────────────────────────
//
// Deliberately NOT persisted. The question each one answers is "has THIS
// process seen a previous value", and a value restored from the database would
// make the first poll after a restart a transition against state the game may
// have left hours ago.
const tracker = { online: new Map(), leader: new Map() }
/** Forget every tracked value. For the tests. */
function reset() {
tracker.online.clear()
tracker.leader.clear()
}
/**
* One poll's verdict on one server (D68): is its game connected now?
*
* Synchronous and fire-and-forget — the refresh must not wait on core.
*/
function serverObserved(server, connected) {
try {
if (!server) return 0
const id = String(server.id)
const now = Boolean(connected)
const before = tracker.online.get(id)
tracker.online.set(id, now)
// First sight is never a transition: a restart announces nothing.
if (before === undefined || before === now) return 0
return fire(now ? T['rust.server.online'] : T['rust.server.offline'], {
data: serverVars(server),
// A transition observed by a poll is observed NOW, so it needs no age check;
// the key is per minute so that one real flap is one event even if two
// polls land either side of a restart of this process.
dedupeKey: dedupeKey(now ? 'online' : 'offline', id, Math.floor(Date.now() / 60000)),
}) ? 1 : 0
} catch (err) {
log.warn('could not raise a server transition', { server: server && server.id, error: err.message })
return 0
}
}
/**
* After a batch: has somebody new taken the lead in this wipe's kills? (D64)
*
* Only a STRICT lead counts. The leaderboard breaks a tie on who was seen last,
* so two players level on kills trade the top row every time either one moves —
* and reading the top row alone would announce a new leader each time.
*/
async function checkLeader(server) {
try {
const state = await serversDb.getState(server.id)
const wipeId = state && state.wipeId
if (!wipeId) return 0
const rows = await eventsDb.leaderboard({ serverId: server.id, wipeId, sort: 'kills', limit: 2 })
const top = rows[0]
const kills = top ? Number(top.kills) || 0 : 0
const id = String(server.id)
const before = tracker.leader.get(id)
if (!top || kills <= 0) {
tracker.leader.set(id, { wipeId, steamId: null })
return 0
}
const tied = rows[1] && Number(rows[1].kills) === kills
const steamId = String(top.steamId)
// First sight, or a new wipe: remember, announce nothing.
if (!before || before.wipeId !== wipeId) {
tracker.leader.set(id, { wipeId, steamId: tied ? null : steamId })
return 0
}
if (tied || before.steamId === steamId) return 0
tracker.leader.set(id, { wipeId, steamId })
return fire(T['rust.leaderboard.topped'], {
data: {
...serverVars(server),
leader: str(top.name) || 'A player',
kills,
leaderboardUrl: leaderboardPath(id),
},
dedupeKey: dedupeKey('leader', id, wipeId, steamId, kills),
}) ? 1 : 0
} catch (err) {
log.warn('could not check the leaderboard', { server: server && server.id, error: err.message })
return 0
}
}
/**
* Login attempts that were never approved (D64).
*
* A query over what is stored rather than a timer per attempt, so a restart
* loses nothing and running it twice is a no-op (the key is the attempt's own
* server, Steam id and time). Bounded by D63's personal age: an attempt a day
* old is not worth a staff mail.
*/
async function sweepLoginDenied(servers, now = Date.now()) {
let sent = 0
for (const server of servers || []) {
try {
const rows = await eventsDb.unapprovedLogins({
serverId: server.id,
from: now - PERSONAL_MAX_AGE_MS,
to: now - LOGIN_APPROVAL_WINDOW_MS,
windowMs: LOGIN_APPROVAL_WINDOW_MS,
slackMs: LOGIN_APPROVAL_SLACK_MS,
})
for (const row of rows) {
const t = Number(row.t)
if (fire(T['rust.login.denied'], {
data: {
...serverVars(server),
steamId: String(row.steamId),
player: str(row.name),
attemptedAt: new Date(t),
},
dedupeKey: dedupeKey('login-denied', server.id, row.steamId, t),
occurredAt: t,
})) sent += 1
}
} catch (err) {
log.warn('could not sweep login attempts', { server: server && server.id, error: err.message })
}
}
return sent
}
/** A Steam account was just linked (R1). Called by the link route, once, on a NEW link. */
function linked({ userId, steamId, name }) {
try {
const uid = Number(userId)
if (!Number.isInteger(uid) || uid < 1 || !steamId) return 0
return fire(T['rust.player.linked'], {
data: { steamId: String(steamId), player: str(name), accountUrl: PATHS.account },
ownerUserId: uid,
dedupeKey: dedupeKey('linked', steamId, uid),
}) ? 1 : 0
} catch (err) {
log.warn('could not raise the link notification', { error: err.message })
return 0
}
}
/**
* `rust.kit.entitled` for each user one reward step granted (phase 13b). Never
* throws: a notification that could not be raised must not fail the grant it
* is about. Returns how many were raised.
*/
function entitled({ userIds, kit, server, mode, runId, stepId }) {
let raised = 0
try {
const rewardKey = `${runId}:${stepId}`
for (const userId of new Set(userIds || [])) {
const uid = Number(userId)
if (!Number.isInteger(uid) || uid < 1) continue
const ok = fire(T['rust.kit.entitled'], {
data: { rewardKey, kit: String(kit), ...serverVars(server), ...(mode ? { mode: String(mode) } : {}), accountUrl: PATHS.account },
ownerUserId: uid,
dedupeKey: dedupeKey('entitled', runId, stepId, uid),
})
if (ok) raised++
}
} catch (err) {
log.warn('could not raise the reward notification', { error: err.message })
}
return raised
}
module.exports = {
onEvent,
serverObserved,
checkLeader,
sweepLoginDenied,
linked,
entitled,
reset,
dedupeKey,
headline,
stillNews,
BROADCAST_MAX_AGE_MS,
PERSONAL_MAX_AGE_MS,
LOGIN_APPROVAL_WINDOW_MS,
STRUCTURE_LABELS,
}

334
server/engagement/seeds.js Normal file
View File

@@ -0,0 +1,334 @@
// ── What the notifications read like, and the rules that use them ─────────
//
// `registerEngagementSeeds` (MODULE_API.md §2.4 and §1.1 under 1.9.0; PLAN.md
// §25.2). Data only: nothing here names a recipient, and nothing here turns a
// rule on.
//
// ── Two bespoke bodies, and why only two ──────────────────────────────────
//
// A body earns its place when the message has something to say that core's
// structural projection cannot. The raid alert does — it is the one message
// here somebody acts on at 3am, and it must say WHERE and WHAT in the first
// line. The wipe does — it is the one broadcast a whole community waits for.
// Everything else is "this happened, here is the link", which is exactly what
// core's `notify.event` / `inapp.event` already say, so it points at those and
// authors nothing (§4.6.1 property 1).
//
// The register is plain, not in-universe. Rust has no court or herald to write
// in the voice of, and a raid alert dressed as fiction is a raid alert read a
// second later than it should be.
//
// ── Three rules for editing a body ────────────────────────────────────────
//
// 1. **No conditionals, and never an optional inside a clause.** An unset
// optional interpolates to the EMPTY STRING. `atGrid` is a fragment that
// carries its own leading space for exactly that reason; `grid` on its own
// belongs on a line of its own or nowhere.
// 2. **No brand.** `siteName` and friends are supplied by the renderer, so one
// image mails as whichever site it is running as.
// 3. **Bump `seedVersion` when a body changes, never for a comment.** It is how
// a better default reaches deployments whose operators did not edit it.
//
// ── One rule group per family ─────────────────────────────────────────────
//
// A group is seeded ONCE (per deployment, per key), so a rule appended to a
// group in a later version reaches fresh installs only. Eight families, eight
// keys: a future raid rule takes `raid-v2` without disturbing anybody's clan
// rules. Every rule is disabled — core ignores `enabled` rather than trusting it
// — so installing this module mails nobody until an operator decides it should.
// ── Block helpers ──────────────────────────────────────────────────────────
const text = (id, body, opts = {}) => ({
id,
type: 'email.text',
props: opts.muted ? { text: body, muted: true } : { text: body },
})
const heading = (id, body, level = 'h1') => ({ id, type: 'email.heading', props: { level, text: body } })
const button = (id, label, url, textLead) => ({
id,
type: 'email.button',
props: textLead ? { label, url, textLead } : { label, url },
})
const divider = (id) => ({ id, type: 'email.divider', props: {} })
// Every email ends with the unsubscribe pair; `unsubscribeUrl` is core's
// per-delivery variable, not something a trigger declares.
const unsubscribe = () => [
divider('rule'),
button('unsub', 'Unsubscribe', '{{unsubscribeUrl}}', 'To stop these messages, use this link:'),
]
const email = (key, name, triggerId, subject, blocks) => ({
key,
name,
channel: 'email',
triggerId,
triggerVersion: 1,
seedVersion: 1,
subject,
blocks: [...blocks, ...unsubscribe()],
})
/** In-app: heading = the row's title, button = its one action, the rest = its body. */
const inapp = (key, name, triggerId, title, body, action, url) => ({
key,
name,
channel: 'inapp',
triggerId,
triggerVersion: 1,
seedVersion: 1,
subject: null,
blocks: [heading('h', title, 'h3'), text('intro', body), button('cta', action, url)],
})
const TEMPLATES = Object.freeze([
email(
'rust.base.destroyed',
'Rust — your base was raided',
'rust.base.destroyed',
'Your base on {{server}} is being raided',
[
heading('h', 'Your base is being raided'),
text('p1', 'A {{structure}} of a base you are authorised on was destroyed{{atGrid}} on {{server}}.'),
text('p2',
'You are getting this because you are on the base\'s tool cupboard. Further damage to the '
+ 'same base will not send another alert for a while.', { muted: true }),
button('cta', 'Open the server page', '{{serverUrl}}'),
],
),
inapp(
'rust.base.destroyed-inapp',
'Rust — your base was raided (in-app)',
'rust.base.destroyed',
'Your base is being raided',
'A {{structure}} was destroyed{{atGrid}} on {{server}}.',
'Open the server',
'{{serverUrl}}',
),
email(
'rust.wipe.started',
'Rust — a server wiped',
'rust.wipe.started',
'{{server}} has wiped',
[
heading('h', '{{server}} has wiped'),
text('p1', 'A new wipe has started on {{server}}: a fresh map, and a fresh start for everyone.'),
button('cta', 'Open the server page', '{{serverUrl}}'),
],
),
inapp(
'rust.wipe.started-inapp',
'Rust — a server wiped (in-app)',
'rust.wipe.started',
'{{server}} has wiped',
'A new wipe has started: a fresh map, and a fresh start for everyone.',
'Open the server',
'{{serverUrl}}',
),
])
// ── The rules — every one of them off ──────────────────────────────────────
/** Core's generic bodies (§4.6.1 property 1). */
const GENERIC = { email: 'notify.event', inapp: 'inapp.event', digest: 'notify.digest' }
/** This module's bodies for a trigger, and core's digest. */
const bodies = (key) => ({ email: key, inapp: `${key}-inapp`, digest: 'notify.digest' })
const RULE_GROUPS = Object.freeze([
{
key: 'raid-v1',
note: 'module-rust: the raid alert (disabled)',
rules: [
{
trigger_id: 'rust.base.destroyed',
name: 'Raid alert — offline owners',
audience: 'owner',
// Push is allowed because this trigger is also a stream (D65); the
// tickle carries no content, and the app pulls the inbox row.
channels: ['email', 'inapp', 'push'],
template_keys: bodies('rust.base.destroyed'),
// Per BUILDING (the subjectKey): a raid is dozens of walls and one alert.
cooldown_seconds: 1800,
max_sends_per_hour: 500,
// D61: "offline raid alert" is this condition, not code. An operator who
// wants online raids too deletes it.
conditions: { variable: 'ownerOnline', cmp: 'eq', value: false },
},
],
},
{
key: 'wipe-v1',
note: 'module-rust: wipe announcements (disabled)',
rules: [
{
trigger_id: 'rust.wipe.started',
name: 'Server wiped',
audience: 'subscribers',
channels: ['email', 'inapp', 'push'],
template_keys: bodies('rust.wipe.started'),
cooldown_seconds: 6 * 3600,
max_sends_per_hour: 2000,
},
],
},
{
key: 'server-v1',
note: 'module-rust: server up and down (disabled)',
rules: [
{
trigger_id: 'rust.server.online',
name: 'Server came online',
audience: 'subscribers',
channels: ['inapp', 'push'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 3600,
max_sends_per_hour: 2000,
},
{
trigger_id: 'rust.server.offline',
name: 'Server went offline',
audience: 'subscribers',
channels: ['inapp', 'push'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 3600,
max_sends_per_hour: 2000,
// A plugin reload, or a restart that is back within five minutes, is not
// an outage anybody needs to hear about. `cancel_on` withdraws the
// pending notice when the server comes back inside the window.
delay_seconds: 300,
cancel_on: ['rust.server.online'],
},
],
},
{
key: 'leaderboard-v1',
note: 'module-rust: a new kills leader (disabled)',
rules: [
{
trigger_id: 'rust.leaderboard.topped',
name: 'New kills leader',
audience: 'subscribers',
channels: ['inapp'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 3600,
max_sends_per_hour: 2000,
},
],
},
{
key: 'account-v1',
note: 'module-rust: a Steam account was linked (disabled)',
rules: [
{
trigger_id: 'rust.player.linked',
name: 'Steam account linked',
audience: 'owner',
// Email as well as in-app: the case this exists for is a link the person
// did NOT make, and they will not be looking at the site's inbox for it.
channels: ['email', 'inapp'],
template_keys: GENERIC,
cooldown_seconds: 0,
max_sends_per_hour: 200,
},
],
},
{
// Its own group, not a rule appended to `account-v1`: a group is seeded once,
// so an appended rule would reach fresh installs only (R7).
key: 'rewards-v1',
note: 'module-rust: an event rewarded you a kit (disabled)',
rules: [
{
trigger_id: 'rust.kit.entitled',
name: 'Kit reward earned',
audience: 'owner',
// Email as well: a reward granted at 03:00 is news the person reads the
// next morning, before they are next in game or on the site.
channels: ['email', 'inapp'],
template_keys: GENERIC,
cooldown_seconds: 0,
max_sends_per_hour: 200,
},
],
},
{
key: 'clans-v1',
note: 'module-rust: clan departures and disbands (disabled)',
rules: [
{
trigger_id: 'rust.clan.member.left',
name: 'Clan — a member left',
audience: 'members',
channels: ['inapp'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 0,
max_sends_per_hour: 500,
},
{
trigger_id: 'rust.clan.member.kicked',
name: 'Clan — a member was removed',
audience: 'members',
channels: ['inapp'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 0,
max_sends_per_hour: 500,
},
{
trigger_id: 'rust.clan.disbanded',
name: 'Clan — disbanded',
audience: 'members',
channels: ['email', 'inapp'],
template_keys: GENERIC,
cooldown_seconds: 0,
max_sends_per_hour: 500,
},
],
},
{
key: 'moderation-v1',
note: 'module-rust: reports, bans and unapproved logins, to staff (disabled)',
rules: [
{
trigger_id: 'rust.player.reported',
name: 'Player reported',
audience: 'staff',
channels: ['email', 'inapp'],
template_keys: GENERIC,
// Per REPORTED player: a pile-on of ten reports is one notice an hour.
cooldown_seconds: 3600,
max_sends_per_hour: 200,
},
{
trigger_id: 'rust.player.banned',
name: 'Player banned',
audience: 'staff',
channels: ['inapp'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 0,
max_sends_per_hour: 200,
},
{
trigger_id: 'rust.player.unbanned',
name: 'Player unbanned',
audience: 'staff',
channels: ['inapp'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 0,
max_sends_per_hour: 200,
},
{
trigger_id: 'rust.login.denied',
name: 'Login not approved',
audience: 'staff',
channels: ['inapp'],
template_keys: { inapp: GENERIC.inapp },
cooldown_seconds: 3600,
max_sends_per_hour: 200,
},
],
},
])
module.exports = { TEMPLATES, RULE_GROUPS }

View File

@@ -0,0 +1,53 @@
// ── The push facet: which triggers may reach a phone ──────────────────────
//
// `registerNotificationStreams` (MODULE_API.md §2.4). A stream is what a device
// subscribes to, and **core delivers an engagement rule's push only to devices
// subscribed to a stream whose id IS the trigger id** (`pushChannel.deliver` ->
// `publishToUsers(row.trigger_id)`). So a trigger with no stream here can never
// buzz a phone, however its rule is set — which is exactly how the families
// that should not are kept off it (D65).
//
// Every id here is ALSO a trigger in `triggers.js`. That is the one namespace
// core enforces across both facets: one event, with a payload contract and a
// subscription toggle, owned by one module. An id that appeared only here would
// be a toggle nothing could ever fire.
//
// **The tickle carries nothing.** A push is `{ stream, ref }` and the app pulls
// the real item over the authenticated inbox API, so a leaked relay topic says
// that something happened and not what. That is core's guarantee and it is why
// a raid alert may be a push at all.
const STREAMS = Object.freeze([
{
id: 'rust.base.destroyed',
label: 'Your base was raided',
description: 'Part of a base you are authorised on was destroyed by another player.',
// Delivered only to the owner's devices, never fanned out: `owner` ceiling,
// one emit per authorised person (D59).
personal: true,
requiresLinkedAccount: true,
},
{
id: 'rust.server.online',
label: 'A server came online',
description: 'A Rust server started or came back.',
personal: false,
requiresLinkedAccount: false,
},
{
id: 'rust.server.offline',
label: 'A server went offline',
description: 'A Rust server stopped or stopped answering.',
personal: false,
requiresLinkedAccount: false,
},
{
id: 'rust.wipe.started',
label: 'A server wiped',
description: 'A Rust server started a new wipe.',
personal: false,
requiresLinkedAccount: false,
},
])
module.exports = { STREAMS }

View File

@@ -0,0 +1,479 @@
// ── What can happen, as core's engagement engine is told it ───────────────
//
// The payload contracts behind every notification this module can cause
// (MODULE_API.md §2.4, `registerEventTriggers`; PLAN.md §25). A trigger says
// what an event IS, what a template may interpolate, and — the part that is a
// security boundary — the widest audience a rule on it may EVER be given.
//
// ── The ceiling is containment, not size ──────────────────────────────────
//
// `owner` is not a small `staff`, and `staff` does not permit `owner`. For the
// raid alert "one person" is the person whose base it was; for a ban it is
// nobody outside the staff room. Each ceiling below is chosen against that
// lattice and not against a ladder, and core refuses a rule that widens one.
//
// ── What no variable here carries, on purpose ─────────────────────────────
//
// • An IP address. The login and ban frames carry one; the triggers do not,
// so no template an operator writes can put an address in a mail. The
// admin feed still shows it, to staff, where it is useful.
// • The raider (D66). The raid alert says what was destroyed, where and
// when. Who did it is gameplay intelligence the game does not hand the
// victim, and a variable that is not declared cannot be interpolated.
// • A Steam id other than the subject's own.
//
// ── Why `subjectKey` is what it is ────────────────────────────────────────
//
// Core's cooldown is per (rule, user, subject, channel). So the subject is the
// thing a recipient should hear about once per cooldown: a BUILDING for a raid
// (however many walls fall), a SERVER for a broadcast (however often it
// bounces), a CLAN for a membership change. A subject that changed every firing
// — a boot id, a timestamp — would make every cooldown a no-op.
//
// ── `version` ──────────────────────────────────────────────────────────────
//
// The prop-schema version a template records it was authored against. Bump one
// on a rename or a type change, never for a label.
const ID = 'rust'
/** Site-relative paths, built the way the client registers them. */
const PATHS = {
servers: `/${ID}`,
account: `/player/${ID}`,
}
// A server id is VARCHAR(64) of the operator's choosing, and a clan's
// `externalId` is `<serverId>:<clanId>:<createdMs>`. Core validates a `url`
// variable against a character class with no `:` in it, so every id that goes
// into a path is percent-encoded — without it the clan link would be dropped at
// emit in production, silently, for every clan there is.
const serverPath = (serverId) => `/${ID}/servers/${encodeURIComponent(serverId)}`
const leaderboardPath = (serverId) => `${serverPath(serverId)}?tab=leaderboard`
const clanPath = (externalId) => `/${ID}/clans/${encodeURIComponent(externalId)}`
const V1 = 1
// ── Shared variables ───────────────────────────────────────────────────────
// **Every trigger carries its own headline.** Most rules here point at core's
// generic `notify.event` / `inapp.event`, and core's structural projection fills
// `title` and `intro` from the trigger's LABEL and DESCRIPTION only when the
// payload does not define them — "the payload wins, the projection fills gaps"
// (ENGAGEMENT.md §4.6.1). Without these two, the phase-10 walk rendered a
// multi-server site's notice as "A server came online. A server's game
// started…" — true, and useless, because it never said which. The emitter
// writes the sentence (`emit.js` `headline`); an operator's own template can
// still ignore it and interpolate the parts.
const HEADLINE = [
{ name: 'title', type: 'string', required: false, example: 'Main is back online',
description: 'A one-line headline naming what happened and where. Core generic bodies use it as the title.' },
{ name: 'intro', type: 'string', required: false, example: 'Main is back up and taking players.',
description: 'One sentence of detail. Core generic bodies use it as the body.' },
]
const SERVER = [
{ name: 'serverId', type: 'string', required: true, example: 'main',
description: 'The server the event happened on, as configured in Admin -> Rust. Also the cooldown subject for broadcasts.' },
{ name: 'server', type: 'string', required: true, example: 'Runic Gateway | Main',
description: 'The server\'s display name.' },
{ name: 'serverUrl', type: 'url', required: false, example: '/rust/servers/main',
description: 'Site-relative path to the server\'s page.' },
]
const CLAN = [
{ name: 'clanKey', type: 'string', required: true, example: 'main:12:1790142840000',
description: 'The clan\'s stable identity. The cooldown subject; not meant for display.' },
{ name: 'clan', type: 'string', required: true, example: 'The Rust Belt',
description: 'The clan\'s name.' },
{ name: 'clanUrl', type: 'url', required: false, example: '/rust/clans/main%3A12%3A1790142840000',
description: 'Site-relative path to the clan\'s page.' },
]
// ── The raid alert ─────────────────────────────────────────────────────────
const RAID = {
id: 'rust.base.destroyed',
label: 'Your base was raided',
description:
'Part of a base you are authorised on was destroyed by another player: a wall, a door, ' +
'an external wall or gate, or the tool cupboard.',
kind: 'event',
// One per base per cooldown, however many walls fall. The building is the
// tool cupboard's id — the game's own answer to "which base is this".
subjectKey: 'building',
// One emit per authorised, linked person, each with `ownerUserId` set (D59).
// `owner` is the ceiling AND the default: there is nobody else this may reach.
audience: 'owner',
ceiling: 'owner',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'building', type: 'string', required: true, example: '8113',
description: 'The base, as the id of its tool cupboard. The cooldown subject.' },
{ name: 'structure', type: 'string', required: true, example: 'door',
description: 'What was destroyed: "building block", "door", "external wall" or "tool cupboard".' },
{ name: 'grid', type: 'string', required: false, example: 'H7',
description: 'The map grid square. Absent when the server could not work one out.' },
// A FRAGMENT, for use inside a sentence. An unset optional interpolates to
// the empty string, so "your door in {{grid}} was destroyed" reads "your
// door in was destroyed" when the grid is unknown; this carries its own
// leading space and vanishes cleanly instead.
{ name: 'atGrid', type: 'string', required: false, example: ' in H7',
description: 'Sentence fragment: " in H7" with its own leading space, or nothing when the grid is unknown.' },
{ name: 'ownerOnline', type: 'boolean', required: true, example: false,
description: 'Whether YOU were online when it happened. The seeded rule alerts only when this is false.' },
],
}
// ── Server lifecycle ───────────────────────────────────────────────────────
//
// `everyone` because a server being up is what a server page already says to
// anyone. The DEFAULT is `subscribers` — the people who asked — and an operator
// widens deliberately.
const BROADCASTS = [
{
id: 'rust.wipe.started',
label: 'A server wiped',
description: 'A server started a new wipe: a fresh map, and everything built on the old one gone.',
kind: 'event',
subjectKey: 'serverId',
audience: 'subscribers',
ceiling: 'everyone',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'wipeId', type: 'string', required: true, example: '1790142840-3000-1234',
description: 'The new wipe\'s identity.' },
],
},
{
id: 'rust.server.online',
label: 'A server came online',
description: 'A server\'s game started, or came back after being unreachable.',
kind: 'event',
subjectKey: 'serverId',
audience: 'subscribers',
ceiling: 'everyone',
version: V1,
variables: [...SERVER, ...HEADLINE],
},
{
id: 'rust.server.offline',
label: 'A server went offline',
description: 'A server\'s game stopped, crashed, or stopped talking to the website.',
kind: 'event',
subjectKey: 'serverId',
audience: 'subscribers',
ceiling: 'everyone',
version: V1,
variables: [...SERVER, ...HEADLINE],
},
{
id: 'rust.leaderboard.topped',
label: 'A new kills leader',
description: 'Somebody new leads the current wipe\'s kills on a server.',
kind: 'event',
subjectKey: 'serverId',
audience: 'subscribers',
ceiling: 'everyone',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'leader', type: 'string', required: true, example: 'Marisol',
description: 'The new leader\'s in-game name.' },
{ name: 'kills', type: 'int', required: true, example: 42,
description: 'Their kills this wipe.' },
{ name: 'leaderboardUrl', type: 'url', required: false, example: '/rust/servers/main?tab=leaderboard',
description: 'Site-relative path to the server\'s leaderboard.' },
],
},
]
// ── The player's own account ───────────────────────────────────────────────
const ACCOUNT = {
id: 'rust.player.linked',
label: 'A Steam account was linked',
description: 'A Steam account was linked to your website account with an in-game code.',
kind: 'event',
subjectKey: 'steamId',
// PLAN.md §10 said `self`; core has no such ceiling (§25.1). `owner` with the
// linking user as `ownerUserId` is the value that exists and means the same.
audience: 'owner',
ceiling: 'owner',
version: V1,
variables: [
...HEADLINE,
{ name: 'steamId', type: 'string', required: true, example: '76561198000000001',
description: 'The Steam account that was linked. Also the cooldown subject.' },
{ name: 'player', type: 'string', required: false, example: 'Marisol',
description: 'The in-game name the game reported when it was linked.' },
{ name: 'accountUrl', type: 'url', required: false, example: '/player/rust',
description: 'Site-relative path to your Rust account page.' },
],
}
// ── A reward (phase 13b) ───────────────────────────────────────────────────
//
// Deferred from phase 10 (D64) to the phase that grants something. Emitted once
// per recipient USER when an event's `rust.kit.entitle` writes their rows, with
// that user as `ownerUserId` — so, like the link notice, `owner` is both the
// ceiling and the only audience there is: a reward is nobody else's news.
//
// The subject is the run and the step, so one award is one notification however
// often a retried step writes the same rows.
const REWARD = {
id: 'rust.kit.entitled',
label: 'An event rewarded you a kit',
description: 'An event on a Rust server rewarded you: a kit is waiting in the in-game Kits menu, with one extra use.',
kind: 'event',
subjectKey: 'rewardKey',
audience: 'owner',
ceiling: 'owner',
version: V1,
variables: [
...HEADLINE,
{ name: 'rewardKey', type: 'string', required: true, example: '41:7',
description: 'The run and step that awarded it. The cooldown subject; not meant for display.' },
{ name: 'kit', type: 'string', required: true, example: 'vip-starter',
description: 'The kit name, as the server Kits plugin has it.' },
...SERVER,
{ name: 'mode', type: 'string', required: false, example: 'top',
description: 'How the recipients were chosen: everyone, top, minScore, random or topPercent.' },
{ name: 'accountUrl', type: 'url', required: false, example: '/player/rust',
description: 'Site-relative path to your Rust account page.' },
],
}
// ── Clans ──────────────────────────────────────────────────────────────────
//
// `members` ceiling — clan membership is the clan's business (D49). Recipients
// travel on the envelope as `recipientUserIds`, because "the clan this was
// about" is a different answer every firing and cannot be a saved audience.
//
// No `rust.clan.member.added`: core already fires `team.member.joined` for our
// clans through the Team sync, and a second trigger would notify twice (D64).
const CLANS = [
{
id: 'rust.clan.member.left',
label: 'Someone left your clan',
description: 'A member left a clan you are in.',
kind: 'event',
subjectKey: 'clanKey',
audience: 'members',
ceiling: 'members',
version: V1,
variables: [
...CLAN,
...SERVER,
...HEADLINE,
{ name: 'member', type: 'string', required: false, example: 'Darrow',
description: 'Who left.' },
],
},
{
id: 'rust.clan.member.kicked',
label: 'Someone was removed from your clan',
description: 'A member was removed from a clan you are in — or you were.',
kind: 'event',
subjectKey: 'clanKey',
audience: 'members',
ceiling: 'members',
version: V1,
variables: [
...CLAN,
...SERVER,
...HEADLINE,
{ name: 'member', type: 'string', required: false, example: 'Darrow',
description: 'Who was removed.' },
{ name: 'by', type: 'string', required: false, example: 'Marisol',
description: 'Who removed them.' },
],
},
{
id: 'rust.clan.disbanded',
label: 'Your clan was disbanded',
description: 'A clan you were in was disbanded.',
kind: 'event',
subjectKey: 'clanKey',
audience: 'members',
ceiling: 'members',
version: V1,
variables: [
...CLAN,
...SERVER,
...HEADLINE,
{ name: 'by', type: 'string', required: false, example: 'Marisol',
description: 'Who disbanded it.' },
],
},
]
// ── Moderation — staff, and never wider ────────────────────────────────────
const MODERATION = [
{
id: 'rust.player.reported',
label: 'A player was reported',
description: 'A player filed an in-game report against another.',
kind: 'event',
subjectKey: 'steamId',
audience: 'staff',
ceiling: 'staff',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'steamId', type: 'string', required: true, example: '76561198000000002',
description: 'The reported player\'s Steam id. The cooldown subject.' },
{ name: 'player', type: 'string', required: false, example: 'Darrow',
description: 'The reported player\'s name.' },
{ name: 'reporter', type: 'string', required: false, example: 'Marisol',
description: 'Who filed the report.' },
{ name: 'reportType', type: 'string', required: false, example: 'cheat',
description: 'The category the reporter chose.' },
{ name: 'topic', type: 'string', required: false, example: 'Aimbot at the dome',
description: 'The report\'s subject line.' },
{ name: 'message', type: 'string', required: false, example: 'Headshots through two walls.',
description: 'The report\'s text.' },
],
},
{
id: 'rust.player.banned',
label: 'A player was banned',
description: 'A player was banned on a server.',
kind: 'event',
subjectKey: 'steamId',
audience: 'staff',
ceiling: 'staff',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'steamId', type: 'string', required: true, example: '76561198000000002',
description: 'The banned player\'s Steam id. The cooldown subject.' },
{ name: 'player', type: 'string', required: false, example: 'Darrow',
description: 'The banned player\'s name.' },
{ name: 'reason', type: 'string', required: false, example: 'Cheating',
description: 'The reason given.' },
],
},
{
id: 'rust.player.unbanned',
label: 'A player was unbanned',
description: 'A ban on a server was lifted.',
kind: 'event',
subjectKey: 'steamId',
audience: 'staff',
ceiling: 'staff',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'steamId', type: 'string', required: true, example: '76561198000000002',
description: 'The player\'s Steam id. The cooldown subject.' },
{ name: 'player', type: 'string', required: false, example: 'Darrow',
description: 'The player\'s name.' },
],
},
{
id: 'rust.login.denied',
label: 'A login was not approved',
description:
'Somebody tried to join a server and was not let in within a minute: a ban, a failed ' +
'authentication, or a player who gave up while connecting.',
kind: 'event',
subjectKey: 'steamId',
audience: 'staff',
ceiling: 'staff',
version: V1,
variables: [
...SERVER,
...HEADLINE,
{ name: 'steamId', type: 'string', required: true, example: '76561198000000002',
description: 'The Steam id that tried to connect. The cooldown subject.' },
{ name: 'player', type: 'string', required: false, example: 'Darrow',
description: 'The name it connected with.' },
{ name: 'attemptedAt', type: 'datetime', required: true, example: '2026-09-23T03:10:00Z',
description: 'When the attempt was made.' },
],
},
]
// ── RunicNPC (docs/runicnpc/PLAN.md stage 4) ───────────────────────────────
//
// What an event's phase waits on: "8 guards died" (waves) and "the boss fell
// below 50%". Core counts a gate's firings from phase entry and does not know
// which run an NPC belongs to, so each firing says its profile, whether an event
// placed it and which run did; a gate's `where` names what it waits for. A
// profile only events place is the plain way to count only an event's NPCs.
//
// `staff`, both halves: a death names who killed it. A boss announced to
// players is stage 6's, with its own trigger.
const NPC_VARS = [
{ name: 'profile', type: 'string', required: true, example: 'guard',
description: 'The RunicNPC profile the NPC was made from. The cooldown subject, and what a phase gate usually names.' },
{ name: 'npc', type: 'string', required: false, example: 'Gate Guard',
description: 'The NPC\'s own name, as the victim\'s death screen shows it.' },
{ name: 'byEvent', type: 'boolean', required: true, example: true,
description: 'Whether an event placed it (rather than an admin\'s placement or another plugin).' },
{ name: 'runId', type: 'string', required: false, example: '42',
description: 'The event run that placed it, when one did.' },
{ name: 'placement', type: 'string', required: false, example: 'guard-3',
description: 'The placement it came from, when it came from one.' },
]
const NPCS = [
{
id: 'rust.npc.died',
label: 'A RunicNPC NPC died',
description: 'One of RunicNPC\'s NPCs was killed. A phase can wait for a number of them: "8 guards died".',
kind: 'event',
subjectKey: 'profile',
audience: 'staff',
ceiling: 'staff',
version: V1,
variables: [
...SERVER,
...HEADLINE,
...NPC_VARS,
{ name: 'killer', type: 'string', required: false, example: 'Marisol',
description: 'The player who landed the killing blow. Absent when no player did.' },
{ name: 'killerSteamId', type: 'string', required: false, example: '76561198000000002',
description: 'Their Steam id.' },
{ name: 'contributors', type: 'int', required: true, example: 3,
description: 'How many players took health from it, the killer included.' },
],
},
{
id: 'rust.npc.health',
label: 'A RunicNPC NPC fell to a health threshold',
description: 'One of RunicNPC\'s NPCs fell to a fraction of its health its profile names. A phase can wait for "the boss below 50%".',
kind: 'event',
subjectKey: 'profile',
audience: 'staff',
ceiling: 'staff',
version: V1,
variables: [
...SERVER,
...HEADLINE,
...NPC_VARS,
{ name: 'percent', type: 'int', required: true, example: 50,
description: 'The threshold it fell to, as a percentage of its health: 50 for half.' },
],
},
]
const TRIGGERS = Object.freeze([RAID, ...BROADCASTS, ACCOUNT, REWARD, ...CLANS, ...MODERATION, ...NPCS])
const TRIGGER_IDS = Object.freeze(Object.fromEntries(TRIGGERS.map((t) => [t.id, t.id])))
module.exports = { TRIGGERS, TRIGGER_IDS, PATHS, serverPath, leaderboardPath, clanPath }

440
server/eventLeases.js Normal file
View File

@@ -0,0 +1,440 @@
// ── What an event may BORROW on a Rust server (PLAN.md §27, protocol 8) ─────
//
// The module never takes a lease and never bounds one. An author puts core's
// `core.lease` in a step naming a lease, a target, a value and a number of
// minutes; core reads the baseline, reserves `<lease id>#<target>` against the
// two-events-one-target index, applies the value with its deadline and restores
// it at teardown. What is here is the four callables each lease ships, and the
// option sources that fill its target field.
//
// ── The target names the server (D73) ─────────────────────────────────────
//
// `core.lease` hands a lease only `{ target }` — never the run's scope — and
// reserves `<id>#<target>`. So every lease here is TARGETED and every target
// begins with the server id: `srv-a` for a single value, `srv-a/bear.population`
// or `srv-a/default/kits.vip` for a family. That makes the ledger's unique index
// bite at exactly the granularity Rust has: two runs on two servers never
// collide, and one value on one server has one holder.
//
// ── Game convars only (D74) ───────────────────────────────────────────────
//
// Vanilla Rust has no gather, craft or smelt rate convar; what it has, and what
// the plugin's allowlist lends, is decay, the population system, and its two
// minimum scalars — plus a group's permissions, the "weekend VIP" (D75). The
// plugin holds the allowlist, the bounds, the seven-day ceiling and the deadline
// timer. The bounds are declared here AS WELL, because this pair is what core
// checks when an author saves — a bad value is a refusal on a form rather than a
// step failing unattended at four in the morning.
const core = require('./core')
const client = require('./sidecarClient')
const serversDb = require('./model/servers/servers.db')
const servers = require('./model/servers/servers.model')
const log = core.logger('leases')
/** Seven days (D77). The plugin holds the same ceiling independently and refuses past it. */
const MAX_LEASE_MS = 7 * 24 * 60 * 60 * 1000
/** Core's bound on one option source's answer. A source that would exceed it says so in the log. */
const MAX_OPTIONS = 2000
/** The wire key of the one lease that is not a convar. */
const GROUP_PERMISSION_KEY = 'group.permission'
/**
* Split a target into its server and the rest (D73).
*
* At the FIRST slash: a server id is `[a-z0-9-]` and never contains one, while
* what follows may (a group name is free text an operator typed).
*/
function splitTarget(target) {
const text = String(target || '').trim()
const slash = text.indexOf('/')
if (slash < 0) return { serverId: text, rest: '' }
return { serverId: text.slice(0, slash), rest: text.slice(slash + 1) }
}
/**
* The server a target names, with its token — or a refusal.
*
* **`retry: false`**, because the second attempt carries the same params: a
* target naming a server that is not configured (or is switched off) is an
* authoring mistake or a deleted server, and neither is fixed by waiting.
*/
async function serverFor(serverId) {
if (!serverId) return { ok: false, retry: false, error: 'the target does not name a server' }
const row = await serversDb.getServer(serverId)
if (!row) return { ok: false, retry: false, error: `there is no Rust server "${serverId}" on this site` }
if (!row.enabled) return { ok: false, retry: false, error: `the Rust server "${row.name || serverId}" is switched off` }
return { ok: true, server: servers.withToken(row) }
}
/** The sentence for a transport failure, naming the server — every notice says which (§25.6). */
function transportError(server, result, what) {
const name = (server && (server.name || server.id)) || 'the server'
switch (result.status) {
case 'http-503':
return `${name} has no game connected, so its ${what} could not be reached`
case 'http-504':
case 'timeout':
return `${name} did not answer about its ${what} in time`
case 'protocol-mismatch':
return `${name}'s sidecar speaks a different protocol — update the module or the sidecar`
default:
return `${name} could not be reached about its ${what} (${result.status})`
}
}
/** A plugin's own refusal, which carries a sentence of its own. */
function pluginError(data, fallback) {
return (data && (data.message || data.reason)) || fallback
}
/**
* Build the four callables one lease shares with every other.
*
* `wire(rest)` turns what follows the server id into the plugin's `{ key,
* target }`, or a refusal. The callables differ in nothing else, so they are
* built rather than repeated: four copies of this would be four chances for one
* of them to forget the drift check, which is the one thing §F says a lease must
* not be allowed to skip.
*/
function lease({ id, label, description, type, min, max, family, targetLabel, source, example, wire }) {
async function resolve(target) {
const { serverId, rest } = splitTarget(target)
const found = await serverFor(serverId)
if (!found.ok) return found
const w = wire(rest)
if (!w.ok) return { ok: false, retry: false, error: w.error }
return { ok: true, server: found.server, key: w.key, target: w.target || undefined }
}
/** The plugin's row for this key and target, or a refusal. */
async function row(r) {
const result = await client.leaseList(r.server, { key: r.key, target: r.target })
if (!result.ok) return { ok: false, error: transportError(r.server, result, 'lease catalogue') }
const rows = (result.data && result.data.leases) || []
const found = rows.find((x) => x && x.key === r.key && (r.target === undefined || x.target === r.target))
if (!found) return { ok: false, retry: false, error: `${r.server.name || r.server.id} does not lend ${r.key}` }
if (family && found.family !== family) {
return { ok: false, retry: false, error: `${r.key} is not a ${family} value` }
}
return { ok: true, row: found, data: result.data }
}
return {
id,
label,
description,
type,
...(min === undefined ? {} : { min }),
...(max === undefined ? {} : { max }),
maxDurationMs: MAX_LEASE_MS,
target: { label: targetLabel, source, example },
async read({ target } = {}) {
const r = await resolve(target)
if (!r.ok) return r
const found = await row(r)
if (!found.ok) return found
// **A key the plugin already holds reads as its BASELINE, not its
// current value.** Core's reservation means a second run can never get
// this far, so a hold core does not know about is the first attempt of
// THIS run whose answer was lost — and the baseline to give back at the
// end is what was there before anybody borrowed it, not that attempt's
// value. Recording the current value here would restore the event's own
// change at teardown and call it baseline.
if (found.row.held && found.row.baseline !== undefined && found.row.baseline !== null) {
return { ok: true, value: String(found.row.baseline) }
}
if (found.row.unreadable) return { ok: false, retry: false, error: found.row.unreadable }
if (found.row.current === undefined || found.row.current === null) {
return { ok: false, error: `${r.server.name || r.server.id} could not read ${r.key}` }
}
return { ok: true, value: String(found.row.current) }
},
async apply(value, until, { target } = {}) {
const r = await resolve(target)
if (!r.ok) return r
// **A duration, not the deadline.** `until` is an absolute time computed
// here and honoured there, which is a deadline measured against two
// clocks; a game host ten minutes fast would end a ten-minute lease the
// instant it took it. The absolute time still rides along, for display.
const untilMs = new Date(until).getTime()
const holdMs = untilMs - Date.now()
if (!Number.isFinite(holdMs) || holdMs <= 0) {
return { ok: false, error: 'the lease deadline has already passed' }
}
const body = {
key: r.key,
...(r.target === undefined ? {} : { target: r.target }),
...(family ? { family } : {}),
value: String(value),
holdMs: Math.round(holdMs),
untilMs,
}
const result = await client.leaseApply(r.server, body)
if (!result.ok) {
// **An apply this end gave up on may still land.** The client's lease
// timeout is below the sidecar's own, so the command can still reach
// the game after core has been told it failed — and core then releases
// its reservation, believing nothing was taken. A release follows it
// down the same link, which the plugin handles in order: if the apply
// landed, the hold's own baseline goes back; if it never did, the
// compare finds nothing held and changes nothing. Not awaited: its
// answer changes nothing about this one.
if (result.status === 'timeout' || result.status === 'http-504') {
client
.leaseRelease(r.server, { key: r.key, target: r.target, expected: String(value) })
.catch(() => {})
}
return { ok: false, error: transportError(r.server, result, 'lease') }
}
const data = result.data || {}
if (data.kind === 'lease.ok') return { ok: true }
// A refusal the second attempt would repeat is `retry: false` — the
// switch is off, the key is not lent, the value is out of range. One that
// might pass later (a value the game could not read this second) is left
// to core's default.
const permanent = ['events-disabled', 'unknown-key', 'out-of-range', 'too-long', 'unresolved', 'target-gone', 'malformed']
return {
ok: false,
...(permanent.includes(data.reason) ? { retry: false } : {}),
error: pluginError(data, `${r.server.name || r.server.id} refused the lease`),
}
},
async restore(baseline, { expected, target } = {}) {
const r = await resolve(target)
if (!r.ok) return r
const result = await client.leaseRelease(r.server, {
key: r.key,
...(r.target === undefined ? {} : { target: r.target }),
expected: expected === undefined || expected === null ? undefined : String(expected),
baseline: baseline === undefined || baseline === null ? undefined : String(baseline),
})
if (!result.ok) return { ok: false, error: transportError(r.server, result, 'lease release') }
const data = result.data || {}
// **Drift is a 200 carrying `lease.drifted`, not a failure of the call.**
// The plugin did what it was asked: it compared, and declined to
// overwrite somebody's deliberate change. Core records that as its own
// outcome, with the current value beside it.
if (data.kind === 'lease.drifted') return { ok: false, drifted: true, current: data.current }
// A group deleted mid-hold has nothing to give back and nothing owed: a
// successful release, not a failure that would leave a ledger row
// unresolved for ever over something that is gone.
if (data.kind === 'lease.ok') return { ok: true }
return { ok: false, error: pluginError(data, `${r.server.name || r.server.id} could not give ${r.key} back`) }
},
/**
* Whether the plugin still has a record of the hold.
*
* **Never a comparison with `read()`** (MODULE_API §1.1). A value that
* differs from what the run applied is DRIFT, which `restore()` reports so
* the row lands `drifted`; answering "not in force" here would orphan the
* row first. A convar hold is memory-only on the game, so a restart ends it
* and this answers `held: false` — exactly the case core cannot otherwise
* see.
*/
async inForce({ target } = {}) {
const r = await resolve(target)
if (!r.ok) return r
const result = await client.leaseList(r.server, { key: r.key, target: r.target })
if (!result.ok) return { ok: false, error: transportError(r.server, result, 'lease catalogue') }
const holds = (result.data && result.data.holds) || []
const held = holds.some((h) => h && h.key === r.key && String(h.target || '') === String(r.target || ''))
return { ok: true, held }
},
}
}
/** A convar named in the target, of this family. */
const convarIn = (family) => (rest) =>
rest ? { ok: true, key: rest.toLowerCase() } : { ok: false, error: `name the ${family} value after the server, as server/convar` }
const LEASES = [
lease({
id: 'rust.decay.scale',
label: 'Decay rate',
description:
'How fast unprotected buildings decay. 1 is normal, 0 switches decay off, 2 doubles it. Read on every decay tick, so it takes effect at the next one.',
type: 'float',
min: 0,
max: 10,
family: 'decay',
targetLabel: 'Which server',
source: 'rust.options.servers',
example: 'main',
wire: (rest) => (rest ? { ok: false, error: 'the decay rate takes only a server as its target' } : { ok: true, key: 'decay.scale' }),
}),
lease({
id: 'rust.population',
label: 'Population',
description:
'How many of one animal or vehicle the game keeps topped up, per square kilometre. Applied on the next spawn tick, so the world fills toward the new number rather than jumping to it.',
type: 'float',
min: 0,
max: 50,
family: 'population',
targetLabel: 'Which server and population',
source: 'rust.options.populations',
example: 'main/bear.population',
wire: convarIn('population'),
}),
lease({
id: 'rust.spawn.scalar',
label: 'Spawn scalar',
description:
"The population system's minimum spawn rate or density — what it runs at on an empty or quiet server, scaling up toward the maximum as players arrive.",
type: 'float',
min: 0,
max: 10,
family: 'spawn',
targetLabel: 'Which server and scalar',
source: 'rust.options.spawnscalars',
example: 'main/spawn.min_rate',
wire: convarIn('spawn'),
}),
lease({
id: 'rust.group.permission',
label: 'Group permission',
description:
"Whether a permission group carries a permission — \"group default holds kits.vip until Monday\" makes everybody VIP for the weekend. Given back at the end whether or not the site is still up; the game holds the deadline.",
type: 'bool',
family: null,
targetLabel: 'Which server, group and permission',
source: 'rust.options.grouppermissions',
example: 'main/default/kits.vip',
wire: (rest) => {
const slash = rest.lastIndexOf('/')
if (slash <= 0 || slash >= rest.length - 1) {
return { ok: false, error: 'a group permission is named as server/group/permission' }
}
return {
ok: true,
key: GROUP_PERMISSION_KEY,
target: `${rest.slice(0, slash).trim().toLowerCase()}/${rest.slice(slash + 1).trim().toLowerCase()}`,
}
},
}),
]
// ── Option sources (D78: only what this phase's leases read) ─────────────────
//
// Every one resolves live, and a server that does not answer contributes
// nothing rather than failing the whole answer — one server being down must
// never blank the form for the other five (§9). A source that returns `[]`
// degrades its field to free text on core's side, which is the right failure:
// the operator very often already knows the value.
/** Bound one source's answer, and say so in the log when there was more. */
function bounded(rows, sourceId) {
if (rows.length <= MAX_OPTIONS) return rows
log.warn('option source truncated', { source: sourceId, available: rows.length, served: MAX_OPTIONS })
return rows.slice(0, MAX_OPTIONS)
}
/** Every enabled server's own answer, in parallel, skipping the ones that fail. */
async function perServer(ask) {
const list = await servers.listForPolling()
const settled = await Promise.allSettled(list.map(async (server) => ({ server, result: await ask(server) })))
return settled.filter((s) => s.status === 'fulfilled' && s.value.result && s.value.result.ok).map((s) => s.value)
}
/** The convars one family lends, per server, as whole targets. */
async function familyOptions(family, sourceId) {
const answers = await perServer((server) => client.leaseList(server))
const rows = []
for (const { server, result } of answers) {
for (const r of (result.data && result.data.leases) || []) {
if (!r || r.family !== family || r.unreadable) continue
rows.push({ value: `${server.id}/${r.key}`, label: r.key, group: server.name || server.id })
}
}
return bounded(rows, sourceId)
}
const OPTION_SOURCES = [
{
id: 'rust.options.servers',
label: 'Rust servers',
description: 'Every enabled server on this site. A lease holds a value on one of them (D73).',
async resolve() {
const list = await servers.listForPolling()
return list.map((s) => ({ value: s.id, label: s.name || s.id }))
},
},
{
id: 'rust.options.populations',
label: 'Populations',
description: 'The animal and vehicle populations each server lends, read live from the game.',
async resolve() {
return familyOptions('population', 'rust.options.populations')
},
},
{
id: 'rust.options.spawnscalars',
label: 'Spawn scalars',
description: "The population system's rate and density scalars each server lends.",
async resolve() {
return familyOptions('spawn', 'rust.options.spawnscalars')
},
},
{
// Groups times registered permissions is a catalogue bigger than a dropdown
// holds on any server with a few plugins, so it narrows by the term.
id: 'rust.options.grouppermissions',
label: 'Group permissions',
description: 'A permission group and a permission some loaded plugin registered, on each server.',
searchable: true,
async resolve({ q } = {}) {
const term = String(q || '').trim().toLowerCase()
const answers = await perServer((server) => client.permCatalogue(server))
const rows = []
for (const { server, result } of answers) {
const data = result.data || {}
const perms = (data.permissions || []).map((p) => String(p).toLowerCase())
for (const g of data.groups || []) {
const group = g && g.name ? String(g.name).toLowerCase() : null
if (!group) continue
for (const perm of perms) {
const value = `${server.id}/${group}/${perm}`
if (term && !value.includes(term)) continue
rows.push({ value, label: `${group} · ${perm}`, group: server.name || server.id })
}
}
}
return bounded(rows, 'rust.options.grouppermissions')
},
},
]
module.exports = {
MAX_LEASE_MS,
MAX_OPTIONS,
LEASES,
OPTION_SOURCES,
splitTarget,
serverFor,
transportError,
pluginError,
perServer,
bounded,
}

900
server/eventRewards.js Normal file
View File

@@ -0,0 +1,900 @@
// ── What an event GIVES on a Rust server (PLAN.md §29, protocol 10) ───────
//
// 13a made things in the world. This file records who was there, gives them
// something they can redeem, and can tell the server. Four verbs:
//
// rust.participation.open the game starts counting who takes part (D81)
// rust.participation.collect core files the count as the run's participants
// rust.kit.entitle the right to redeem a kit, and one more use of
// it (R16, D103), for the people a mode picks
// rust.announce one line in a server's chat, or every server's
//
// …and the announce leg, `rust.chat`, which says a published news post in the
// chat of every server whose switch is on (D104).
//
// Phase 17 gave both a delivery — chat, or a popup through PopupNotifications
// (D141, D142) — and a VOICE: the style of one permission group, which the
// plugin says the line in with no player as its sender (D140).
//
// ── Who decides what ─────────────────────────────────────────────────────────
//
// The GAME counts: presence, kills, the score (D81, D99). The SITE picks the
// recipients and holds the reward: the tally is read, a mode chosen per event
// picks from it (D101), and a row per recipient goes into
// `rust_perm_run_grants`, which the permission mirror pushes like any other
// grant (D84). So a reward granted at 03:00 to somebody offline is waiting when
// they next log in, and a wipe cannot take it away: the site re-pushes it.
//
// ── An action is never handed the participants ──────────────────────────────
//
// Core records participants from `collect`'s answer, but does not give them to
// a later step. So `kit.entitle` reads the tally from the plugin itself, as
// `uo.item.grant` reads it from the shard, and does not depend on a collect step
// having run.
const crypto = require('node:crypto')
const core = require('./core')
const client = require('./sidecarClient')
const servers = require('./model/servers/servers.model')
const permDb = require('./model/permissions/permissions.db')
const linksDb = require('./model/links/links.db')
const emit = require('./engagement/emit')
const voice = require('./model/permissions/voice')
const { serverFor, transportError, pluginError, perServer, bounded } = require('./eventLeases')
const { BUDGET_MS } = require('./eventWorld')
const log = core.logger('rewards')
// Mirrors of the plugin's bounds (§29.5). The plugin's are authoritative, and
// an operator may set them lower; these price a step and refuse a bad one on
// the authoring form rather than at four in the morning.
const MAX_RECIPIENTS = 100
const MAX_CHAT = 256
const TALLY_MAX_MINUTES = 7 * 24 * 60
const MAX_KILL_WEIGHT = 1000
const DEFAULT_KILL_WEIGHT = 5
const SCORES = ['seconds', 'kills', 'both']
const KILLS_OF = ['players', 'npcs', 'both']
const MODES = ['everyone', 'top', 'minScore', 'random', 'topPercent']
/** The fleet, in `rust.announce`'s `server` param (D105). */
const EVERY_SERVER = '*'
/** Where a line goes (D141). Chat is the default and what every server can do. */
const DELIVERIES = ['chat', 'popup']
/** The plugin's refusals a second attempt would repeat. */
const PERMANENT = new Set([
'events-disabled',
'malformed',
'out-of-range',
'already-open',
'no-zone',
'ambiguous-zone',
'too-many',
'too-long',
'kits-missing',
// Protocol 12: a popup on a server without PopupNotifications. Waiting does not
// install it.
'popup-unavailable',
])
const BUDGETS = [
{
id: 'rust.grants',
label: 'Kit rewards',
unit: 'rewards',
description:
'Kits an event rewards: one per recipient, each the right to redeem the kit and one more use of it. A mode that is not a count is priced at the most it could grant.',
},
{
id: 'rust.announcements',
label: 'Chat announcements',
unit: 'lines',
description: 'Lines an event says in a server\'s chat: one per server reached.',
},
]
/** A transport failure, classified. Only a missing configuration is one waiting cannot fix. */
function transportFailure(server, result, what) {
const permanent = result.status === 'not-configured' || result.status === 'no-token'
return { ok: false, ...(permanent ? { retry: false } : {}), error: transportError(server, result, what) }
}
/** A plugin refusal carried in a 200, classified by its reason. */
function refusal(server, data, what) {
return {
ok: false,
...(PERMANENT.has(data && data.reason) ? { retry: false } : {}),
error: pluginError(data, `${server.name || server.id} refused the ${what}`),
}
}
/** One word from a fixed set, or null. Compared without case: an author types these. */
function oneOf(raw, allowed) {
const text = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase()
return allowed.find((a) => a.toLowerCase() === text) || null
}
/** `<server>:<runId>` for a tally, `<server>:<runId>:<stepId>` for a reward (§29.3). */
const tallyRef = (serverId, runId) => `${serverId}:${runId}`
const entitlementRef = (serverId, runId, stepId) => `${serverId}:${runId}:${stepId}`
/** A ref's parts, split at every colon — a server id has none and core's ids are numbers. */
function refParts(ref) {
const [serverId, runId, stepId] = String(ref || '').split(':')
return { serverId: serverId || null, runId: runId || null, stepId: stepId || null }
}
// ── Picking recipients (D101) ────────────────────────────────────────────────
/**
* The mode's `count`, checked. Returns `{ ok, value }` or a refusal sentence.
* `everyone` takes none.
*/
function checkCount(mode, raw) {
if (mode === 'everyone') return { ok: true, value: null }
const value = Number(raw)
if (mode === 'top' || mode === 'random') {
if (!Number.isInteger(value) || value < 1 || value > MAX_RECIPIENTS) {
return { ok: false, error: `${mode} names 1 to ${MAX_RECIPIENTS} people, and "${raw}" is not that` }
}
} else if (mode === 'topPercent') {
if (!Number.isFinite(value) || value <= 0 || value > 100) {
return { ok: false, error: `topPercent is a percentage above 0 and at most 100, not "${raw}"` }
}
} else if (!Number.isFinite(value) || value < 0) {
return { ok: false, error: `minScore is a score of 0 or more, not "${raw}"` }
}
return { ok: true, value }
}
/** Highest first; a tie keeps the order the game joined them in, so a list reads the same twice. */
function ranked(people) {
return [...people].sort((a, b) => b.score - a.score || a.joinedAt - b.joinedAt || a.steamId.localeCompare(b.steamId))
}
/** The first `n` of a ranked list, and everybody tied with the last one in (D101). */
function withTies(list, n) {
if (n <= 0 || !list.length) return []
if (n >= list.length) return list
const floor = list[n - 1].score
return list.filter((p, i) => i < n || p.score === floor)
}
/**
* Who a mode picks from a tally. Pure, and the whole of D101:
*
* everyone every participant who scored above zero
* top the N highest scores, ties in
* minScore a score of at least X
* random N drawn from everyone who took part, seeded by the step's key
* topPercent the highest X per cent, rounded up, ties in
*
* A score of zero earns nothing in the ranked modes: "the highest scores" of a
* tally where nobody scored is nobody. `random` draws from everyone present,
* which is the point of a raffle.
*
* **The draw is seeded by the idempotency key**, so a retry after a lost answer
* draws the same winners — each person's place is a hash of the key and their
* Steam id, which needs no generator state to reproduce.
*/
function pickRecipients(people, mode, count, seedKey) {
const scored = ranked(people.filter((p) => p.score > 0))
switch (mode) {
case 'everyone':
return scored
case 'top':
return withTies(scored, count)
case 'minScore':
return ranked(people.filter((p) => p.score >= count))
case 'topPercent':
return withTies(scored, Math.ceil((scored.length * count) / 100))
case 'random': {
const draw = (p) => crypto.createHash('sha256').update(`${seedKey}\u0000${p.steamId}`).digest('hex')
return [...people].sort((a, b) => draw(a).localeCompare(draw(b))).slice(0, count)
}
default:
return []
}
}
/** The tally's rows as numbers, whatever the wire carried. */
function peopleOf(data) {
return ((data && data.people) || [])
.filter((p) => p && p.steamId)
.map((p) => ({
steamId: String(p.steamId),
name: p.name ? String(p.name) : String(p.steamId),
seconds: Number(p.seconds) || 0,
kills: Number(p.kills) || 0,
score: Number(p.score) || 0,
joinedAt: Number(p.joinedAt) || 0,
}))
}
/** Steam id -> website user, for the ids that are linked. */
async function usersFor(steamIds) {
const ids = [...new Set(steamIds.map(String))]
if (!ids.length) return new Map()
const rows = await linksDb.userIdsForSteamIds(ids)
return new Map(rows.map((r) => [String(r.steamId), Number(r.userId)]))
}
/** The tally for a run on one server, or a classified failure. */
async function readTally(server, runId) {
const result = await client.tallySnapshot(server, runId)
if (!result.ok) return transportFailure(server, result, 'tally')
const data = result.data || {}
if (data.kind !== 'tally.snapshot') {
// `no-tally` is permanent for THIS step: the tally it reads was never opened
// on this server, or teardown already closed it.
if (data.reason === 'no-tally') {
return {
ok: false,
retry: false,
error: `${server.name || server.id} holds no tally for this run — open one with rust.participation.open on the same server first`,
}
}
return refusal(server, data, 'tally')
}
return { ok: true, data }
}
// ── The kit, as its server's Kits plugin describes it ───────────────────────
/**
* `<serverId>/<kit>` split at the FIRST slash: a server id never contains one,
* and a kit name is whatever an operator typed into Kits.
*/
function splitKit(value) {
const text = String(value || '').trim()
const slash = text.indexOf('/')
if (slash <= 0 || slash === text.length - 1) return null
return { serverId: text.slice(0, slash), kit: text.slice(slash + 1) }
}
/** What a kit rewards, as the source's label says it and the verb checks it (R16, D103). */
function kitReward(row) {
const permission = String(row.permission || '').trim().toLowerCase()
const max = Number(row.max) || 0
return { permission, max, rewardsNothing: !permission && max <= 0 }
}
async function readKit(server, kit) {
const result = await client.kits(server)
if (!result.ok) return transportFailure(server, result, 'kits')
const data = result.data || {}
if (data.kind !== 'kits.list') return refusal(server, data, 'kit list')
const row = (data.kits || []).find((k) => k && String(k.name).toLowerCase() === kit.toLowerCase())
if (!row) return { ok: false, retry: false, error: `${server.name || server.id} has no kit called "${kit}"` }
const reward = kitReward(row)
if (reward.rewardsNothing) {
return {
ok: false,
retry: false,
error: `the kit "${row.name}" is open to everyone and has no use limit, so a reward of it gives nobody anything — give it a permission or a maximum number of uses in Kits`,
}
}
return { ok: true, kit: String(row.name), ...reward, maxRecipients: Number(data.maxRecipients) || MAX_RECIPIENTS }
}
// ── The verbs ────────────────────────────────────────────────────────────────
const participationOpen = {
id: 'rust.participation.open',
label: 'Start counting participants',
description:
'The game counts who takes part from here on: time present, kills, or both — in a zone this run opened, or on the whole server. It stops after its minutes; teardown forgets it.',
// It watches rather than changes anything, but it is ledgered, like
// `uo.participation.open`: the game holds a tally for the run, and teardown
// gives it back.
risk: 'inspect',
reversible: 'ledger',
version: 1,
budgetMs: BUDGET_MS,
params: [
{ name: 'server', type: 'string', required: true, example: 'main', source: 'rust.options.servers',
description: 'Which server counts.' },
{ name: 'zone', type: 'string', required: false, example: 'Airfield brawl', source: 'rust.options.runzones',
description: 'The name an earlier "Open a zone" step of this run gave its zone. Left blank, the whole server counts (D100).' },
{ name: 'score', type: 'string', required: true, example: 'both', source: 'rust.options.scoremodes',
description: 'What earns a place: seconds present, kills, or both.' },
{ name: 'killsOf', type: 'string', required: false, example: 'npcs', source: 'rust.options.killsof',
description: 'Whose deaths count as a kill: players, NPCs (animals included), or both. The last hit gets it. Needed unless the score is seconds.' },
{ name: 'killWeight', type: 'float', required: false, example: DEFAULT_KILL_WEIGHT,
description: `For a score of both: how many minutes one kill is worth. Left blank, ${DEFAULT_KILL_WEIGHT}.` },
{ name: 'minutes', type: 'int', required: false, example: 60,
description: `How long it counts, up to ${TALLY_MAX_MINUTES} (seven days). Left blank, seven days. The game forgets a tally seven days after it opened, however long it counted.` },
],
cost: () => ({}),
async perform({ runId, idempotencyKey, params, verify }) {
const score = oneOf(params.score, SCORES)
if (!score) return { ok: false, retry: false, error: `a tally scores seconds, kills or both, not "${params.score}"` }
const killsOf = score === 'seconds' ? null : oneOf(params.killsOf, KILLS_OF)
if (score !== 'seconds' && !killsOf) {
return { ok: false, retry: false, error: 'a tally that counts kills says whose: players, npcs or both' }
}
let killWeight
if (score === 'both') {
const raw = params.killWeight
killWeight = raw === undefined || raw === null || raw === '' ? DEFAULT_KILL_WEIGHT : Number(raw)
if (!Number.isFinite(killWeight) || killWeight < 0 || killWeight > MAX_KILL_WEIGHT) {
return { ok: false, retry: false, error: `a kill is worth 0 to ${MAX_KILL_WEIGHT} minutes, not "${raw}"` }
}
}
let minutes
if (params.minutes !== undefined && params.minutes !== null && params.minutes !== '') {
minutes = Number(params.minutes)
if (!Number.isInteger(minutes) || minutes < 1 || minutes > TALLY_MAX_MINUTES) {
return { ok: false, retry: false, error: `a tally counts for 1 to ${TALLY_MAX_MINUTES} minutes, not "${params.minutes}"` }
}
}
const zone = String(params.zone || '').trim()
const found = await serverFor(String(params.server || '').trim())
if (!found.ok) return found
// Whether the zone exists is not asked in a dry run: it is opened by an
// earlier step of the same run, so before the run it never does.
if (verify) return { ok: true }
const result = await client.tallyOpen(found.server, {
runId: String(runId),
key: idempotencyKey,
score,
...(killsOf ? { killsOf } : {}),
...(killWeight === undefined ? {} : { killWeight }),
...(minutes === undefined ? {} : { holdMs: minutes * 60000 }),
...(zone ? { zone } : {}),
})
if (!result.ok) return transportFailure(found.server, result, 'tally')
const data = result.data || {}
if (data.kind !== 'tally.ok') return refusal(found.server, data, 'tally')
return {
ok: true,
resources: [
{
kind: 'tally',
ref: tallyRef(found.server.id, runId),
payload: { serverId: found.server.id, score, ...(zone ? { zone } : {}) },
},
],
detail: {
server: found.server.name || found.server.id,
counting: zone ? `in the zone "${zone}"` : 'on the whole server',
...(data.repeat ? { repeat: true, note: 'answered from the first attempt; the tally was already open' } : {}),
},
}
},
/**
* Forget the tally on every server the ledger names — or, when core lost the
* answer and holds none, on every server, since `runId` is all a tally is
* keyed by. A tally already gone is a success.
*/
async revert({ runId, resources }) {
const targets = resources && resources.length
? [...new Set(resources.map((r) => (r.payload && r.payload.serverId) || refParts(r.ref).serverId))]
: (await servers.listForPolling()).map((s) => s.id)
const failed = []
const errors = []
for (const serverId of targets) {
const found = await serverFor(serverId)
if (!found.ok) {
// A server deleted or switched off cannot be asked, and its tally ends on
// its own seven days after it opened; the ledger row is not held for it.
continue
}
const result = await client.tallyClose(found.server, { runId: String(runId) })
const refused = result.ok && (!result.data || result.data.kind !== 'tally.ok')
if (!result.ok || refused) {
failed.push(...(resources || []).filter((r) => refParts(r.ref).serverId === serverId).map((r) => r.ref))
errors.push(result.ok ? pluginError(result.data, `${found.server.name || found.server.id} refused to close the tally`) : transportError(found.server, result, 'tally'))
}
}
if (!errors.length) return { ok: true }
if (!resources || !resources.length || failed.length === resources.length) return { ok: false, error: errors.join('; ') }
return { ok: true, failed }
},
/** A tally is in force while its server still holds it. A server that cannot be asked has said nothing. */
async reconcile({ runId, resources }) {
const inForce = []
for (const r of resources || []) {
const found = await serverFor(refParts(r.ref).serverId)
if (!found.ok) {
inForce.push(r.ref)
continue
}
const result = await client.tallySnapshot(found.server, runId)
const gone = result.ok && result.data && result.data.kind !== 'tally.snapshot' && result.data.reason === 'no-tally'
if (!gone) inForce.push(r.ref)
}
return { ok: true, inForce }
},
}
const participationCollect = {
id: 'rust.participation.collect',
label: 'Record participants',
description:
'Files everybody the tally counted as this run\'s participants, with their score, time and kills. The tally keeps counting if its minutes are not up.',
risk: 'inspect',
reversible: 'none',
version: 1,
budgetMs: BUDGET_MS,
params: [
{ name: 'server', type: 'string', required: true, example: 'main', source: 'rust.options.servers',
description: 'The server whose tally to read.' },
],
cost: () => ({}),
async perform({ runId, params, verify }) {
const found = await serverFor(String(params.server || '').trim())
if (!found.ok) return found
if (verify) return { ok: true }
const tally = await readTally(found.server, runId)
if (!tally.ok) return tally
const people = peopleOf(tally.data)
const users = await usersFor(people.map((p) => p.steamId))
return {
ok: true,
// The member vocabulary is the Steam id, as the team provider's is.
participants: people.map((p) => ({
memberKey: p.steamId,
...(users.has(p.steamId) ? { userId: users.get(p.steamId) } : {}),
score: p.score,
...(p.joinedAt > 0 ? { joinedAt: new Date(p.joinedAt).toISOString() } : {}),
meta: { name: p.name, seconds: p.seconds, kills: p.kills },
})),
detail: {
server: found.server.name || found.server.id,
participants: people.length,
linked: users.size,
...(Number(tally.data.overflow) > 0 ? { overflow: Number(tally.data.overflow) } : {}),
},
}
},
}
const kitEntitle = {
id: 'rust.kit.entitle',
label: 'Reward a kit',
description:
'Gives the people a mode picks from this run\'s tally the right to redeem a kit on its server, and one more use of it. Waits for them if they are offline. Teardown withdraws what is not yet redeemed.',
risk: 'change',
reversible: 'ledger',
version: 1,
budgetMs: BUDGET_MS,
params: [
{ name: 'kit', type: 'string', required: true, example: 'main/vip-starter', source: 'rust.options.kits',
description: 'The kit, as server/kit. The reward reaches only that server (D102).' },
{ name: 'recipients', type: 'string', required: true, example: 'top', source: 'rust.options.recipientmodes',
description: 'Who gets it: everyone who scored, the top N, a score of at least X, N drawn at random, or the top X per cent.' },
{ name: 'count', type: 'float', required: false, example: 3,
description: 'N for top and random, X for a minimum score, the percentage for top per cent. Not used for everyone.' },
],
// Priced before the tally is read, so at the most it could grant: the count
// for a count, and the server's recipient bound for every other mode. An
// author who wants a tight cap picks a count.
cost: (p) => {
const mode = oneOf(p.recipients, MODES)
const n = Math.round(Number(p.count) || 0)
return { 'rust.grants': mode === 'top' || mode === 'random' ? Math.max(0, n) : MAX_RECIPIENTS }
},
async perform({ runId, stepId, idempotencyKey, params, verify }) {
const parsed = splitKit(params.kit)
if (!parsed) return { ok: false, retry: false, error: `"${params.kit}" is not a kit — pick one from the list, as server/kit` }
const mode = oneOf(params.recipients, MODES)
if (!mode) return { ok: false, retry: false, error: `recipients is one of ${MODES.join(', ')}, not "${params.recipients}"` }
const count = checkCount(mode, params.count)
if (!count.ok) return { ok: false, retry: false, error: count.error }
const found = await serverFor(parsed.serverId)
if (!found.ok) return found
const server = found.server
const kit = await readKit(server, parsed.kit)
if (!kit.ok) return kit
if ((mode === 'top' || mode === 'random') && count.value > kit.maxRecipients) {
return { ok: false, retry: false, error: `${server.name || server.id} rewards at most ${kit.maxRecipients} people in one step, not ${count.value}` }
}
if (verify) return { ok: true }
const ref = entitlementRef(server.id, runId, stepId)
const resource = { kind: 'entitlement', ref, payload: { serverId: server.id, kit: kit.kit } }
// A repeated key finds its rows already written and changes nothing — the
// rows ARE the grant, and a set written twice is the same set.
const existing = await permDb.listRunGrantsForStep(runId, stepId)
if (existing.length) {
return {
ok: true,
resources: [resource],
detail: { repeat: true, granted: new Set(existing.map((r) => r.userId)).size, note: 'answered from the first attempt; nothing new was granted' },
}
}
const tally = await readTally(server, runId)
if (!tally.ok) return tally
const picked = pickRecipients(peopleOf(tally.data), mode, count.value, idempotencyKey)
const bound = Number(tally.data.maxRecipients) || kit.maxRecipients
if (picked.length > bound) {
return {
ok: false,
retry: false,
error: `${picked.length} people qualify, and ${server.name || server.id} rewards at most ${bound} in one step — pick a count-based mode or a higher bar`,
}
}
const users = await usersFor(picked.map((p) => p.steamId))
const rows = []
const byUser = new Set()
const missed = []
for (const p of picked) {
const userId = users.get(p.steamId)
if (!userId) {
missed.push(p.name)
continue
}
// One reward per website user: two linked accounts that both took part are
// one person, and one win is one use (D103). The higher score, being
// earlier in the list, is the account that gets the credit.
if (byUser.has(userId)) continue
byUser.add(userId)
rows.push({
runId,
stepId,
idemKey: idempotencyKey,
userId,
serverId: server.id,
steamId: p.steamId,
permission: kit.permission,
kit: kit.kit,
credit: kit.max > 0,
})
}
await permDb.insertRunGrants(rows)
await permDb.markDirty(server.id)
emit.entitled({ userIds: [...byUser], kit: kit.kit, server, mode, runId, stepId })
log.info('kit rewarded', { server: server.id, run: runId, step: stepId, kit: kit.kit, mode, granted: rows.length, missed: missed.length })
return {
ok: true,
resources: [resource],
detail: {
kit: kit.kit,
server: server.name || server.id,
mode,
...(count.value === null ? {} : { count: count.value }),
granted: rows.length,
...(missed.length ? { missed: missed.slice(0, 50), missedCount: missed.length, note: 'missed took part but have linked no website account' } : {}),
},
}
},
/**
* Withdraw a step's rows and push. The permission goes and each unredeemed
* credit is put back by the plugin; a redemption already made stands (R16).
* A row already gone is a success.
*/
async revert({ runId, resources, idempotencyKey }) {
const touched = new Set()
if (!resources || !resources.length) {
for (const serverId of await permDb.deleteRunGrantsForKey(runId, idempotencyKey)) touched.add(serverId)
} else {
for (const r of resources) {
const { runId: refRun, stepId } = refParts(r.ref)
if (!stepId) continue
for (const serverId of await permDb.deleteRunGrantsForStep(refRun || runId, stepId)) touched.add(serverId)
}
}
for (const serverId of touched) await permDb.markDirty(serverId)
return { ok: true }
},
/** The site holds the entitlement and re-pushes it, so a restart or a wipe cannot take it away. */
async reconcile({ resources }) {
return { ok: true, inForce: (resources || []).map((r) => r.ref) }
},
}
/**
* The body of a chat line: its delivery, and the voice's format when the line
* goes to chat and a voice is chosen (D140). A popup is not a chat line and
* carries no format. Chat, the default, is left off the wire — the shape a
* protocol-11 caller sent — so a line with nothing new looks exactly as before.
*/
function lineBody(base, delivery, format) {
return {
...base,
...(delivery === 'popup' ? { delivery } : {}),
...(delivery !== 'popup' && format ? { format } : {}),
}
}
/**
* Say one line on one server, and classify the answer. `repeat` is a success:
* the plugin remembered the key, and the line was already said.
*/
async function sayOn(server, body) {
const result = await client.chat(server, body)
if (!result.ok) return { state: 'down', result }
const data = result.data || {}
if (data.kind !== 'chat.ok') return { state: 'refused', data }
return { state: data.said === false ? 'repeat' : 'said', data }
}
const announce = {
id: 'rust.announce',
label: 'Say it in game chat',
description: 'One line in a Rust server\'s chat, or in every server\'s. A line said cannot be taken back.',
risk: 'notify',
reversible: 'none',
version: 1,
budgetMs: BUDGET_MS,
params: [
{ name: 'server', type: 'string', required: true, example: 'main', source: 'rust.options.chatservers',
description: 'Which server, or * for every server (D105).' },
{ name: 'message', type: 'string', required: true, example: 'The airfield brawl starts in five minutes!',
description: `The line, up to ${MAX_CHAT} characters.` },
// Optional, and the action stays version 1: a bump would stop every step
// already written from dispatching until somebody re-saved it (§33.2).
{ name: 'delivery', type: 'string', required: false, example: 'chat', source: 'rust.options.delivery',
description: 'chat (the default), or popup — which needs PopupNotifications on the server, and is refused with a reason where it is missing (D141).' },
],
// One per server reached. `*` is priced at the enabled servers when core asks,
// which is synchronous — so at the count this module last saw.
cost: (p) => ({ 'rust.announcements': String(p.server || '').trim() === EVERY_SERVER ? Math.max(1, servers.lastEnabledCount()) : 1 }),
async perform({ runId, idempotencyKey, params, verify }) {
const message = String(params.message || '').replace(/\s+/g, ' ').trim()
if (!message) return { ok: false, retry: false, error: 'a chat line needs a message' }
if (message.length > MAX_CHAT) {
return { ok: false, retry: false, error: `a chat line is at most ${MAX_CHAT} characters, and this one is ${message.length}` }
}
const rawDelivery = params.delivery === undefined || params.delivery === null || params.delivery === '' ? 'chat' : params.delivery
const delivery = oneOf(rawDelivery, DELIVERIES)
if (!delivery) return { ok: false, retry: false, error: `a line is delivered to chat or to a popup, not to "${rawDelivery}"` }
const target = String(params.server || '').trim()
let list
if (target === EVERY_SERVER) {
list = await servers.listForPolling()
if (!list.length) return { ok: false, retry: false, error: 'there are no enabled Rust servers to say it on' }
} else {
const found = await serverFor(target)
if (!found.ok) return found
list = [found.server]
}
if (verify) return { ok: true }
const format = delivery === 'chat' ? await voice.currentFormat() : null
const body = lineBody({ key: idempotencyKey || `run:${runId}`, message, event: true }, delivery, format)
const outcomes = await Promise.all(list.map(async (server) => ({ server, ...(await sayOn(server, body)) })))
const name = (o) => o.server.name || o.server.id
// One server named: its answer is the step's.
if (target !== EVERY_SERVER) {
const o = outcomes[0]
if (o.state === 'down') return transportFailure(o.server, o.result, 'chat')
if (o.state === 'refused') return refusal(o.server, o.data, 'chat line')
return { ok: true, detail: { said: [name(o)], ...(o.state === 'repeat' ? { repeat: true } : {}) } }
}
// Every server: a success for each that took the line, and the rest named
// (D104's reason — a line said an hour late in a restarted server is noise).
const said = outcomes.filter((o) => o.state === 'said' || o.state === 'repeat').map(name)
const down = outcomes.filter((o) => o.state === 'down').map(name)
const refused = outcomes.filter((o) => o.state === 'refused').map((o) => `${name(o)}: ${pluginError(o.data, 'refused')}`)
if (!said.length && refused.length) return { ok: false, retry: false, error: refused.join('; ') }
if (!said.length) return { ok: false, error: `no server could be reached: ${down.join(', ')}` }
return { ok: true, detail: { said, ...(down.length ? { down } : {}), ...(refused.length ? { refused } : {}) } }
},
}
// ── The announce leg (D104) ──────────────────────────────────────────────────
/** A news post as one chat line: its title, or failing that its excerpt, flattened and bounded. */
function chatLine(post) {
const text = String((post && (post.title || post.excerpt)) || '').replace(/\s+/g, ' ').trim()
return text.length > MAX_CHAT ? `${text.slice(0, MAX_CHAT - 1)}…` : text
}
/**
* The plugin's memory of recent keys, keyed off the post: its id when core's
* news path gives one, else what it says — `core.announce` hands a leg a post
* with no id. Either way a retried leg never says the same line twice.
*/
function chatKey(post, line) {
if (post && post.id !== undefined && post.id !== null) return `news:${post.id}`
return `news:${crypto.createHash('sha1').update(line).digest('hex')}`
}
const LEG = {
leg: 'rust.chat',
label: 'Rust in-game chat',
/**
* Say a post in the chat of every server whose switch is on. Never throws, as
* every leg client must not. The answer is one outcome per switched-on
* server, for `classify`.
*/
async dispatch(post) {
try {
const line = chatLine(post)
if (!line) return { ok: false, empty: true, outcomes: [] }
const list = (await servers.listForPolling()).filter((s) => s.announceNews)
const key = chatKey(post, line)
// Read once for the post, not once per server: every server says it in the
// same voice (D140). Each server's own delivery decides chat or popup (D142).
const format = list.some((s) => s.newsDelivery !== 'popup') ? await voice.currentFormat() : null
const outcomes = await Promise.all(
list.map(async (server) => ({
server: server.name || server.id,
...(await sayOn(server, lineBody({ key, message: line }, server.newsDelivery, format))),
})),
)
return { ok: true, outcomes }
} catch (err) {
log.warn('news chat leg failed', { error: err.message })
return { ok: false, error: err.message, outcomes: [] }
}
},
/**
* `done` when every switched-on server that is up took the line — or when no
* server is switched on, since there is nothing to deliver. `retry` only when
* every switched-on server is down. A server that refused is named; one that
* was down is skipped, never queued (D104).
*/
classify(result) {
if (!result || (!result.ok && !result.empty && !result.outcomes)) return { outcome: 'retry', error: (result && result.error) || 'no answer' }
if (result.empty) return { outcome: 'terminal', error: 'the post has no title or excerpt to say' }
if (!result.ok) return { outcome: 'retry', error: result.error || 'the leg failed' }
const outcomes = result.outcomes || []
if (!outcomes.length) return { outcome: 'done' }
const took = outcomes.filter((o) => o.state === 'said' || o.state === 'repeat')
const down = outcomes.filter((o) => o.state === 'down').map((o) => o.server)
const refused = outcomes.filter((o) => o.state === 'refused').map((o) => `${o.server}: ${pluginError(o.data, 'refused')}`)
if (down.length === outcomes.length) return { outcome: 'retry', error: `every server is down: ${down.join(', ')}` }
if (!took.length) return { outcome: 'terminal', error: refused.join('; ') }
const notes = [...(down.length ? [`skipped (down): ${down.join(', ')}`] : []), ...refused]
return notes.length ? { outcome: 'done', error: notes.join('; ') } : { outcome: 'done' }
},
}
// ── Option sources ───────────────────────────────────────────────────────────
/** A fixed choice as a dropdown — core has no enum type, so a source is how a field offers words. */
const fixed = (id, label, description, rows) => ({ id, label, description, async resolve() { return rows } })
const OPTION_SOURCES = [
{
// Live from each server's Kits, so the form offers only kits that exist. The
// label says what a reward of each one gives (R16, D103).
id: 'rust.options.kits',
label: 'Kits',
description: "Each server's Kits, flagged by what a reward of one gives.",
searchable: true,
async resolve({ q } = {}) {
const term = String(q || '').trim().toLowerCase()
const answers = await perServer((server) => client.kits(server))
const rows = []
for (const { server, result } of answers) {
const data = result.data || {}
if (data.kind !== 'kits.list') continue
for (const k of data.kits || []) {
if (!k || !k.name) continue
const value = `${server.id}/${k.name}`
if (term && !value.toLowerCase().includes(term)) continue
const reward = kitReward(k)
const flags = [
reward.permission ? null : 'open to everyone',
reward.max > 0 ? `${reward.max} use${reward.max === 1 ? '' : 's'}` : null,
reward.rewardsNothing ? 'rewards nothing' : null,
].filter(Boolean)
rows.push({ value, label: flags.length ? `${k.name} · ${flags.join(' · ')}` : String(k.name), group: server.name || server.id })
}
}
return bounded(rows, 'rust.options.kits')
},
},
// Free text: the zones a run will open do not exist when it is authored, and
// the name is checked when the step runs (D100). Declared so the field is
// documented rather than a bare box, and answers nothing.
fixed('rust.options.runzones', 'Zones this run opens', 'The name an earlier "Open a zone" step of the same run gave its zone. Type it; it is checked when the step runs.', []),
fixed('rust.options.scoremodes', 'Score', 'What earns a place in a tally.', [
{ value: 'seconds', label: 'Seconds present' },
{ value: 'kills', label: 'Kills' },
{ value: 'both', label: 'Both — minutes plus a weight per kill' },
]),
fixed('rust.options.killsof', 'Kills of', 'Whose deaths count as a kill.', [
{ value: 'players', label: 'Players' },
{ value: 'npcs', label: 'NPCs, animals included' },
{ value: 'both', label: 'Players and NPCs' },
]),
fixed('rust.options.recipientmodes', 'Recipients', 'Who a reward goes to (D101).', [
{ value: 'everyone', label: 'Everyone who scored' },
{ value: 'top', label: 'The top N (ties in)' },
{ value: 'minScore', label: 'A score of at least X' },
{ value: 'random', label: 'N drawn at random' },
{ value: 'topPercent', label: 'The top X per cent (ties in)' },
]),
fixed('rust.options.delivery', 'Delivery', 'Where a line goes (D141).', [
{ value: 'chat', label: 'Chat' },
{ value: 'popup', label: 'A popup — needs PopupNotifications on the server' },
]),
{
id: 'rust.options.chatservers',
label: 'Chat servers',
description: 'Every enabled server, or * for all of them.',
async resolve() {
const list = await servers.listForPolling()
return [{ value: EVERY_SERVER, label: 'Every server' }, ...list.map((s) => ({ value: s.id, label: s.name || s.id }))]
},
},
]
const ACTIONS = [participationOpen, participationCollect, kitEntitle, announce]
module.exports = {
MAX_RECIPIENTS,
MAX_CHAT,
EVERY_SERVER,
DELIVERIES,
BUDGETS,
ACTIONS,
LEG,
OPTION_SOURCES,
pickRecipients,
checkCount,
splitKit,
kitReward,
chatLine,
chatKey,
lineBody,
refParts,
}

973
server/eventWorld.js Normal file
View File

@@ -0,0 +1,973 @@
// ── What an event MAKES on a Rust server (PLAN.md §28, protocol 9) ────────
//
// A lease borrows a value that was already there. These three verbs make
// something that was not — a zone, crates, NPCs — and
// give it back at teardown. Everything that decides what is allowed lives on the
// plugin: the allowlist, the bounds, the monument vocabulary, the registry of
// what each run owns. What is here is the contract's half: declarations core can
// check an author's step against, and the three callables core calls.
//
// ── Four facts from the rig shape all of it (§28.1) ──────────────────────────
//
// * A restart is NOT proof a placed thing is gone. Crates are saved by the
// game and come back with the same net id; NPCs are not. So `reconcile` asks
// the plugin, which looks — `module-uo`'s `reconcileByBootId` trick would
// orphan every crate on every restart.
// * A wipe IS proof everything is gone, and the plugin drops its registry.
// * The bridge has no at-most-once store, so its registry is keyed by core's
// idempotency key: a retried step is answered with the first call's ids.
// * Monument names repeat, so a monument is named by kind and instance (D93).
//
// ── The ref names the server ─────────────────────────────────────────────────
//
// Every resource is `<serverId>:<id>`. `revert` and `reconcile` are handed
// resources and not the step's params, and a run may reach six servers; the ref
// is the only place the server can travel with the thing.
const core = require('./core')
const client = require('./sidecarClient')
const servers = require('./model/servers/servers.model')
const zones = require('./model/zones/zones.model')
const zoneOptions = require('./model/zones/zoneOptions')
const voice = require('./model/permissions/voice')
const npcs = require('./model/npcs/npcs.model')
const npcsDb = require('./model/npcs/npcs.db')
const npcProfile = require('./model/npcs/npcProfile')
const clansDb = require('./model/clans/clans.db')
const { serverFor, transportError, pluginError, perServer, bounded } = require('./eventLeases')
const log = core.logger('world')
/**
* The budget every verb here declares. It must EXCEED the client's own timeout
* (`TIMEOUT_MS`, 12 s), which in turn exceeds the sidecar's ten-second reply
* timeout — otherwise core gives up first and a `retry: false` this module
* answered is unreachable (MODULE_API §2.4). `world.test.js` asserts the order.
*/
const BUDGET_MS = 15000
// Mirrors of the plugin's bounds (D95, D96). The plugin's are authoritative and
// an operator may set them lower, in which case its refusal is the one that
// lands; these exist so a bad step is a refusal on the AUTHORING FORM and in a
// dry run, rather than a step failing unattended at four in the morning.
const MAX_CRATES = 25
const MAX_NPCS = 20
const MAX_SPREAD = 50
const MAX_OFFSET = 150
const ZONE_MIN_RADIUS = 5
const ZONE_MAX_RADIUS = 150
const ZONE_MAX_MINUTES = 7 * 24 * 60
const ZONE_MESSAGE_MAX = 256
const DOME_STACK_MAX = 10
/**
* ZoneDomes' own sphere types, by the number its API takes (D194). Only Standard
* is a whole dome: Rust's shaded sphere, darker with each stacked copy. The four
* colours are the Twitch battle-royale spheres, which show only where they cut
* terrain or a structure (ZoneDomes says so itself), so they read as a ring at
* the zone's edge. Standard is the default (D212).
*/
const DOMES = [
{ value: 'standard', type: 0, label: 'Full dome (shaded) — the default' },
{ value: 'red', type: 1, label: 'Red — only where it meets the ground or a building' },
{ value: 'blue', type: 2, label: 'Blue — only where it meets the ground or a building' },
{ value: 'green', type: 3, label: 'Green — only where it meets the ground or a building' },
{ value: 'purple', type: 4, label: 'Purple — only where it meets the ground or a building' },
]
/** The ledger kind both verbs file under. */
const OWNED_KIND = 'world'
/**
* What the plugin will place, mirroring its allowlist (D88).
*
* **Two copies of a short list, deliberately** — `module-uo`'s `GRANTABLE`
* argument. This one prices a step (`cost()` is synchronous and cannot ask a
* game) and fills the dropdown with every server off; the plugin's is what is
* true when this one is wrong.
*/
const PLACEABLE = [
{ key: 'crate.basic', kind: 'crate', label: 'Basic crate' },
{ key: 'crate.normal', kind: 'crate', label: 'Military crate' },
{ key: 'crate.normal2', kind: 'crate', label: 'Crate' },
{ key: 'crate.elite', kind: 'crate', label: 'Elite crate' },
{ key: 'crate.tools', kind: 'crate', label: 'Tool box' },
{ key: 'crate.hackable', kind: 'crate', label: 'Locked crate (hackable)' },
{ key: 'supply.drop', kind: 'crate', label: 'Supply drop' },
{ key: 'barrel.loot', kind: 'crate', label: 'Loot barrel' },
{ key: 'npc.scientist', kind: 'npc', label: 'Scientist' },
{ key: 'npc.scientist.heavy', kind: 'npc', label: 'Heavy scientist' },
{ key: 'npc.scientist.tethered', kind: 'npc', label: 'Scientist (stays put)' },
{ key: 'npc.bandit.guard', kind: 'npc', label: 'Bandit guard' },
]
/** The plugin's refusals a second attempt would repeat. Anything else is left to core's default. */
const PERMANENT = new Set([
'events-disabled',
'malformed',
'unknown-prefab',
'out-of-range',
'no-monument',
'off-map',
'zonemanager-missing',
// PLAN_REDESIGNS §3: a flag or setting this server's ZoneManager does not have,
// and a dome asked of a server without ZoneDomes or the domes helper.
'bad-option',
'dome-unavailable',
// runicnpc stage 4 (D243): a profile the server does not have, or no RunicNPC.
'unknown-profile',
'runicnpc-missing',
// runicnpc stage 5 (D272): no zone of the run holds the point; a RunicNPC
// older than the API escort, ally and tether need. An escort who is not on
// the server (`escort-offline`) is left to retry: they may join.
'no-zone',
'runicnpc-old',
])
const BUDGETS = [
{
id: 'rust.prefabs',
label: 'Crates placed',
unit: 'crates',
description: 'Crates, barrels and supply drops an event puts in the world. Counted per server a run reaches.',
},
{
id: 'rust.npcs',
label: 'NPCs placed',
unit: 'NPCs',
description: 'Scientists and guards an event puts in the world — its own dial, so fights can be capped apart from loot (D89).',
},
{
id: 'rust.zone.minutes',
label: 'Zone time',
unit: 'minutes',
description: 'How long the zones an event opens stand, added up. Every zone declares its minutes, and the game erases it when they run out (D96).',
},
]
/**
* Why a dome cannot go on this server, from its last hello, or null when it can
* (or when the server has not said, which leaves the plugin to answer). The
* words name what is missing, because the fix is to install one of two files.
*/
function domeMissing(mods) {
const zd = mods && mods.zoneDomes
if (!zd) return null
if (!zd.loaded) return 'ZoneDomes is not loaded on this server, so a zone cannot have a dome'
const state = zd.helper && zd.helper.state
if (state === 'missing') return 'RunicGatewayDomes.cs is not installed on this server, and ZoneDomes cannot be called without it'
if (state && state !== 'patched') return `RunicGatewayDomes.cs could not patch this server's ZoneDomes (${state})`
return null
}
/** A number param, or undefined when left blank. */
function num(raw) {
if (raw === undefined || raw === null || raw === '') return undefined
const value = Number(raw)
return Number.isFinite(value) ? value : NaN
}
/**
* Where a step puts its thing — a monument plus an offset, or raw coordinates,
* and exactly one of the two (D87) — and which server that is on.
*
* A monument value carries its server (`srv-a/harbor_1#2`, D93), so a monument
* step needs no `server`; one that gives both must agree. Raw coordinates name
* nothing, so they need `server`. Every refusal is `retry: false`: the second
* attempt has the same params.
*/
function location(params) {
const monument = String(params.monument || '').trim()
const x = num(params.x)
const z = num(params.z)
const y = num(params.y)
const byCoords = x !== undefined || z !== undefined
let serverId = String(params.server || '').trim()
if (Boolean(monument) === byCoords) {
return { ok: false, error: 'a location is a monument or x and z, and exactly one of them' }
}
if (monument) {
const slash = monument.indexOf('/')
if (slash <= 0 || slash === monument.length - 1) {
return { ok: false, error: `"${monument}" is not a monument — pick one from the list, as server/monument` }
}
const onServer = monument.slice(0, slash)
if (serverId && serverId !== onServer) {
return { ok: false, error: `that monument is on ${onServer}, not ${serverId}` }
}
serverId = onServer
const offsetX = num(params.offsetX) ?? 0
const offsetZ = num(params.offsetZ) ?? 0
if (Number.isNaN(offsetX) || Number.isNaN(offsetZ)) return { ok: false, error: 'an offset is a number of metres' }
if (Math.hypot(offsetX, offsetZ) > MAX_OFFSET) {
return { ok: false, error: `an offset from a monument is at most ${MAX_OFFSET} m` }
}
return { ok: true, serverId, wire: { monument: monument.slice(slash + 1), offsetX, offsetZ } }
}
if (x === undefined || z === undefined || Number.isNaN(x) || Number.isNaN(z)) {
return { ok: false, error: 'coordinates need both x and z, as numbers' }
}
if (Number.isNaN(y)) return { ok: false, error: 'y is a number of metres, or left blank for the ground' }
if (!serverId) return { ok: false, error: 'coordinates do not say which server — pick one' }
return { ok: true, serverId, wire: { x, z, ...(y === undefined ? {} : { y }) } }
}
/** `<serverId>:<id>` — see the header. */
const refOf = (serverId, id) => `${serverId}:${id}`
/** A ref split back into its server and id, at the FIRST colon (a server id has none). */
function splitRef(ref) {
const text = String(ref || '')
const colon = text.indexOf(':')
return colon <= 0 ? { serverId: null, id: text } : { serverId: text.slice(0, colon), id: text.slice(colon + 1) }
}
/**
* A zone the plugin erased at its deadline (`world.expired`, PLAN_FIXES F13, F14).
*
* D96 said the website maps this frame to nothing and learns of it through
* `reconcile` and `revert`. The first player walk showed what that costs: three
* zones expired in the game on time and sat `confirmed` on the run console until
* the runs were cancelled, when teardown found them "already gone" and called that
* a success. D170 changed it, and D183 put the record in core: the resource row is
* marked `expired`.
*
* Until protocol 13 this frame could not be recognised at all — the plugin wrote
* the zone's kind over the frame's — so `what` is new with it, and a frame without
* an `id` names nothing to expire.
*/
function expired(serverId, frame) {
if (!serverId || !frame || frame.id === undefined || frame.id === null || frame.id === '') return false
try {
core.expireEvent({ kind: OWNED_KIND, ref: refOf(serverId, String(frame.id)) })
} catch (err) {
log.warn('could not tell core a zone expired', { server: serverId, id: frame.id, error: err.message })
return false
}
return true
}
/** Resources grouped by the server each one is on. */
function byServer(resources) {
const groups = new Map()
for (const resource of resources || []) {
const serverId = (resource.payload && resource.payload.serverId) || splitRef(resource.ref).serverId
if (!groups.has(serverId)) groups.set(serverId, [])
groups.get(serverId).push(resource)
}
return groups
}
/** A transport failure, classified. Only a missing configuration is one waiting cannot fix. */
function transportFailure(server, result, what) {
const permanent = result.status === 'not-configured' || result.status === 'no-token'
return { ok: false, ...(permanent ? { retry: false } : {}), error: transportError(server, result, what) }
}
/**
* Send one world write and file what came back.
*
* One resource per id — per crate, per NPC, per zone — like `module-uo`'s one
* per serial, so a group half of which players looted reconciles per crate
* rather than all or nothing.
*/
async function place(server, send, body, what) {
const result = await send(server, body)
if (!result.ok) return transportFailure(server, result, what)
const data = result.data || {}
if (data.kind !== 'world.ok') {
return {
ok: false,
...(PERMANENT.has(data.reason) ? { retry: false } : {}),
error: pluginError(data, `${server.name || server.id} refused the ${what}`),
}
}
const placed = Array.isArray(data.placed) ? data.placed : []
return {
ok: true,
resources: placed.map((row) => ({
kind: OWNED_KIND,
ref: refOf(server.id, row.id),
payload: {
serverId: server.id,
what: row.kind,
...(row.prefab ? { prefab: row.prefab } : {}),
...(row.name ? { name: row.name } : {}),
},
})),
...(data.repeat ? { detail: { repeat: true, note: 'answered from the first attempt; nothing new was placed' } } : {}),
}
}
/**
* Give back what a step made.
*
* **No idempotency key goes with it.** `module-uo` shipped exactly that
* mistake: its despawn carried the key the spawn went out under, the shard
* recognised a repeat of the DO and answered with the spawn's reply, and every
* teardown was a no-op that reported success (MODULE_API §2.4). A repeated
* revert is safe here without one — the second finds everything `gone`.
*
* The one case the key IS for is the lost answer: core knows a dispatch went
* out under it and never learned what it made, so `resources` is empty. The
* step's server is not known then either — it was a param, and params do not
* reach `revert` — so every enabled server is asked to give back whatever this
* run placed under that key. A server that cannot be asked leaves the row
* visible rather than guessing.
*/
async function revert({ runId, resources, idempotencyKey }) {
const failed = []
const errors = []
if (!resources || resources.length === 0) {
if (!idempotencyKey) return { ok: true }
for (const server of await servers.listForPolling()) {
const result = await client.worldRevert(server, { runId: String(runId), key: idempotencyKey })
if (!result.ok) errors.push(transportError(server, result, 'revert'))
else if (!result.data || result.data.kind !== 'world.ok') errors.push(pluginError(result.data, `${server.name || server.id} refused the revert`))
}
return errors.length ? { ok: false, error: errors.join('; ') } : { ok: true }
}
for (const [serverId, group] of byServer(resources)) {
const found = await serverFor(serverId)
if (!found.ok) {
failed.push(...group.map((r) => r.ref))
errors.push(found.error)
continue
}
const result = await client.worldRevert(found.server, {
runId: String(runId),
ids: group.map((r) => splitRef(r.ref).id),
})
if (!result.ok) {
failed.push(...group.map((r) => r.ref))
errors.push(transportError(found.server, result, 'revert'))
continue
}
// **A 200 is not a success on this bridge** — a refusal comes back as one,
// carrying `world.error` (`not-ready` while the world is still loading).
// Read as success it would mark every row reverted while the game still
// held every crate.
if (!result.data || result.data.kind !== 'world.ok') {
failed.push(...group.map((r) => r.ref))
errors.push(pluginError(result.data, `${found.server.name || found.server.id} refused the revert`))
continue
}
// `gone` is not reported: a crate a player looted is the point of having
// placed it. `refused` IS — the plugin found something there that this run
// did not make, and nothing will ever remove it through this path.
const refused = new Set(((result.data && result.data.refused) || []).map(String))
for (const r of group) if (refused.has(splitRef(r.ref).id)) failed.push(r.ref)
}
if (!failed.length) return { ok: true }
if (failed.length === resources.length && errors.length) return { ok: false, error: errors.join('; ') }
return { ok: true, failed }
}
/**
* Which of these does the world still hold?
*
* The plugin LOOKS for each one, by net id or zone id. A server that cannot be
* asked has said nothing, so its resources are all reported in force — "I do
* not know" is never "it is gone" (MODULE_API §1.1).
*/
async function reconcile({ runId, resources }) {
const inForce = []
for (const [serverId, group] of byServer(resources)) {
const found = await serverFor(serverId)
const result = found.ok ? await client.worldOwned(found.server, { runId: String(runId) }) : null
if (!result || !result.ok || !result.data || !Array.isArray(result.data.owned)) {
inForce.push(...group.map((r) => r.ref))
continue
}
const held = new Set(result.data.owned.map((row) => String(row.id)))
for (const r of group) if (held.has(splitRef(r.ref).id)) inForce.push(r.ref)
}
return { ok: true, inForce }
}
/** The location params both verbs share, so two declarations cannot drift apart. */
const LOCATION_PARAMS = [
{
name: 'monument',
type: 'string',
required: false,
example: 'main/powerplant_1',
source: 'rust.options.monuments',
description: 'Where, by monument. Give this OR x and z. Names the server too.',
},
{
name: 'offsetX',
type: 'float',
required: false,
example: 20,
description: `Metres east of the monument's centre (negative is west). Up to ${MAX_OFFSET} m from it in all.`,
},
{
name: 'offsetZ',
type: 'float',
required: false,
example: -15,
description: "Metres north of the monument's centre (negative is south).",
},
{
name: 'server',
type: 'string',
required: false,
example: 'main',
source: 'rust.options.servers',
description: 'Which server, when the location is coordinates. A monument already says.',
},
{ name: 'x', type: 'float', required: false, example: -604, description: 'World x, instead of a monument.' },
{ name: 'z', type: 'float', required: false, example: -342, description: 'World z, instead of a monument.' },
{
name: 'y',
type: 'float',
required: false,
example: 30,
description: 'Height. Left blank, the ground at x and z.',
},
]
const WORLD_COMMON = {
// Something appears where there was nothing. §K puts the default-off line
// between `inspect` and `change`, so an operator switches these on
// deliberately — the right consent for an unattended change to a live world.
risk: 'change',
reversible: 'ledger',
version: 1,
budgetMs: BUDGET_MS,
revert,
reconcile,
}
/**
* One placing verb per KIND (D97), not one verb for both.
*
* Core learns which caps an action accepts by pricing that action's declared
* EXAMPLES once, and drops a dimension priced at zero. So a single verb whose
* cost moved between `rust.prefabs` and `rust.npcs` by its `prefab` param could
* only ever show the operator the crates cap, and D89's separate dial for fights
* would be unreachable. Two verbs, each pricing exactly one dimension, is also
* what lets the switchboard allow crates and leave NPCs off.
*/
function placeVerb({ id, kind, budget, max, label, description, source, example }) {
const noun = kind === 'npc' ? 'NPCs' : 'crates'
return {
...WORLD_COMMON,
id,
label,
description,
cost: (p) => ({ [budget]: Math.max(0, Math.round(Number(p.count) || 0)) }),
params: [
{
name: 'prefab',
type: 'string',
required: true,
example,
source,
description:
kind === 'npc'
? "Which NPCs: one of this site's NPC profiles (Admin → Rust NPC profiles, on a server with RunicNPC), or one of the server's own scientists."
: `Which of the server's own ${noun} to place.`,
},
{
name: 'count',
type: 'int',
required: true,
example: 3,
description: `How many — 1 to ${max} at a time.`,
},
{
name: 'spread',
type: 'float',
required: false,
example: 10,
description: `How widely to scatter a group, up to ${MAX_SPREAD} m. Left blank, 10.`,
},
...LOCATION_PARAMS,
...(kind === 'npc' ? NPC_ORDER_PARAMS : []),
],
async perform({ runId, idempotencyKey, params, verify }) {
const picked = String(params.prefab || '').trim()
// D243: one of the site's RunicNPC profiles, beside Rust's own.
const profile = kind === 'npc' && picked.startsWith(npcs.PROFILE_PREFIX) ? picked.slice(npcs.PROFILE_PREFIX.length) : null
const known = profile === null ? PLACEABLE.find((x) => x.key === picked) : null
if (profile !== null ? !npcProfile.NAME_RULE.test(profile) : !known || known.kind !== kind) {
return { ok: false, retry: false, error: `"${params.prefab}" is not one of the ${noun} a Rust server places for events` }
}
const count = Number(params.count)
if (!Number.isInteger(count) || count < 1 || count > max) {
return { ok: false, retry: false, error: `place 1 to ${max} ${noun} at a time, and "${params.count}" is not that` }
}
const spread = num(params.spread)
if (Number.isNaN(spread) || (spread !== undefined && (spread < 0 || spread > MAX_SPREAD))) {
return { ok: false, retry: false, error: `a scatter is 0 to ${MAX_SPREAD} m, not "${params.spread}"` }
}
const where = location(params)
if (!where.ok) return { ok: false, retry: false, error: where.error }
const found = await serverFor(where.serverId)
if (!found.ok) return found
if (profile !== null) {
const missing = await profileMissing(found.server, profile)
if (missing) return { ok: false, retry: false, error: missing }
}
// Stage 5: escort, ally and tether are RunicNPC's, so only a profile takes them.
const orders = kind === 'npc' ? npcOrders(params, found.server) : { ok: true, wire: {} }
if (!orders.ok) return { ok: false, retry: false, error: orders.error }
if (profile === null && Object.keys(orders.wire).length) {
return { ok: false, retry: false, error: "escort, ally and tether are for one of the site's NPC profiles (RunicNPC), not Rust's own scientists" }
}
if (verify) return { ok: true }
return place(
found.server,
client.worldPlace,
{
runId: String(runId),
key: idempotencyKey,
...(profile !== null ? { profile } : { prefab: known.key }),
count,
...(spread === undefined ? {} : { spread }),
...where.wire,
...orders.wire,
},
profile !== null ? `NPCs of the profile "${profile}"` : known.label.toLowerCase(),
)
},
}
}
/** A Steam id: seventeen digits, as Rust's are. */
const STEAM_ID = /^\d{17}$/
/**
* Stage 5 (D269, D270, D272): what a RunicNPC profile's NPCs are told besides
* their profile. Each is optional; the server refuses a step whose order it
* cannot honour (an escort who is not on, a clan it does not have, no zone of
* the run around the point), so nothing half-placed is left behind.
*/
const NPC_ORDER_PARAMS = [
{
name: 'escort',
type: 'string',
required: false,
example: '76561198000000001',
description:
"A player's Steam id, or a {placeholder} from the run's start params: the NPCs keep close to that player and fight whoever attacks them, and walk back to their spot if the player dies or leaves (D269). The player must be on the server. RunicNPC profiles only.",
},
{
name: 'allyClan',
type: 'string',
required: false,
source: 'rust.options.clans',
example: 'main/1234567',
description:
"A clan on the same server: the NPCs never target its members and defend them and what they own (D257). RunicNPC profiles only; give this or allyTeamOf, not both.",
},
{
name: 'allyTeamOf',
type: 'string',
required: false,
example: '76561198000000001',
description:
"A player's Steam id, or a {placeholder}: the NPCs are allied to that player and their team (D257, D270). RunicNPC profiles only.",
},
{
name: 'tether',
type: 'boolean',
required: false,
example: true,
description:
'Keep the NPCs inside the zone this event made around the point (D272): a Make a zone step must come first. RunicNPC profiles only.',
},
]
/** The orders, checked, as the bridge reads them: `{ ok, wire }` or `{ ok: false, error }`. */
function npcOrders(params, server) {
const wire = {}
const escort = String(params.escort === undefined || params.escort === null ? '' : params.escort).trim()
if (escort) {
if (!STEAM_ID.test(escort)) return { ok: false, error: `an escort is a player's Steam id, and "${escort}" is not one` }
wire.escort = escort
}
const clan = String(params.allyClan === undefined || params.allyClan === null ? '' : params.allyClan).trim()
const teamOf = String(params.allyTeamOf === undefined || params.allyTeamOf === null ? '' : params.allyTeamOf).trim()
if (clan && teamOf) return { ok: false, error: 'an ally is a clan or a player and their team, not both' }
if (clan) {
const m = /^([^/]+)\/(-?\d{1,20})$/.exec(clan)
if (!m) return { ok: false, error: `"${clan}" is not a clan from the list` }
if (m[1] !== server.id) return { ok: false, error: `that clan is on ${m[1]}, and these NPCs are placed on ${server.id}` }
wire.ally = { kind: 'clan', id: m[2] }
}
if (teamOf) {
if (!STEAM_ID.test(teamOf)) return { ok: false, error: `an ally's team is named by a player's Steam id, and "${teamOf}" is not one` }
wire.ally = { kind: 'player', id: teamOf }
}
if (params.tether === true || params.tether === 'true') wire.tether = true
return { ok: true, wire }
}
/**
* Why a profile cannot be placed on this server, from what the site knows, or
* null (D243). A server without RunicNPC offers only Rust's own until stage 9;
* a profile the site does not push there is not on it. What the server itself
* holds is the plugin's to answer (`unknown-profile`).
*/
async function profileMissing(server, profile) {
const [list, profiles] = await Promise.all([npcsDb.listNpcServers(), npcsDb.listProfiles()])
const here = list.find((s) => s.id === server.id)
const name = server.name || server.id
if (!npcs.npcReady(here)) return `${name} cannot place the profile "${profile}": ${npcs.npcAbsence(here)}. Pick one of the server's own scientists.`
if (!profiles.some((p) => !p.replaced && p.name === profile && npcs.covers(p, server.id))) {
return `the site has no NPC profile "${profile}" for ${name} (Admin → Rust NPC profiles)`
}
return null
}
const ACTIONS = [
{
...WORLD_COMMON,
id: 'rust.zone.open',
label: 'Open a zone',
description:
'A ZoneManager zone at a monument or a point, for a set number of minutes. The game erases it when they run out, even if this site is down; teardown erases it sooner.',
cost: (p) => ({ 'rust.zone.minutes': Math.max(0, Math.round(Number(p.minutes) || 0)) }),
params: [
...LOCATION_PARAMS,
{
name: 'radius',
type: 'float',
required: true,
example: 40,
description: `How far the zone reaches, ${ZONE_MIN_RADIUS} to ${ZONE_MAX_RADIUS} m.`,
},
{
name: 'minutes',
type: 'int',
required: true,
example: 120,
description: `How long it stands, up to ${ZONE_MAX_MINUTES} (seven days). Counted against zone time.`,
},
{ name: 'name', type: 'string', required: false, example: 'Airfield brawl', description: 'What the zone is called.' },
{
name: 'options',
type: 'string',
required: false,
example: 'NoBuild, NoPlayerLoot, radiation=10',
source: 'rust.options.zone_presets',
description:
'ZoneManager flags and settings, separated by commas. Pick a preset (Admin → Rust zone presets) to fill it; the step keeps its own copy. Settings: radiation, comfort, temperature, safezone, permission.',
},
{ name: 'enterMessage', type: 'string', required: false, example: 'You entered the arena.', description: `Said to a player who walks in, up to ${ZONE_MESSAGE_MAX} characters.` },
{ name: 'leaveMessage', type: 'string', required: false, example: 'You left the arena.', description: `Said to a player who walks out, up to ${ZONE_MESSAGE_MAX} characters.` },
{
name: 'delivery',
type: 'string',
required: false,
example: 'chat',
source: 'rust.options.delivery',
description: 'How the two messages are said: chat (the default) or popup. Without PopupNotifications on the server a popup is said in chat instead.',
},
{
name: 'dome',
type: 'string',
required: false,
example: 'standard',
source: 'rust.options.domes',
description:
'A ZoneDomes dome over the zone. "standard" is a full shaded dome; the colours show only where the sphere meets the ground or a building. Needs ZoneDomes and RunicGatewayDomes.cs on the server. Blank is no dome.',
},
{ name: 'domeStack', type: 'int', required: false, example: 1, description: `How many spheres the dome stacks, 1 to ${DOME_STACK_MAX}; more is darker. Left blank, 1.` },
],
async perform({ runId, idempotencyKey, params, verify }) {
const where = location(params)
if (!where.ok) return { ok: false, retry: false, error: where.error }
const radius = Number(params.radius)
if (!Number.isFinite(radius) || radius < ZONE_MIN_RADIUS || radius > ZONE_MAX_RADIUS) {
return { ok: false, retry: false, error: `a zone's radius is ${ZONE_MIN_RADIUS} to ${ZONE_MAX_RADIUS} m, not "${params.radius}"` }
}
const minutes = Number(params.minutes)
if (!Number.isInteger(minutes) || minutes < 1 || minutes > ZONE_MAX_MINUTES) {
return { ok: false, retry: false, error: `a zone stands for 1 to ${ZONE_MAX_MINUTES} minutes, not "${params.minutes}"` }
}
const found = await serverFor(where.serverId)
if (!found.ok) return found
// §3.1: the flags and settings, checked against the flag list this server's
// last hello carried (D211). A server that has not said is left to the
// plugin, which checks every one against its live ZoneManager.
const mods = await zones.serverZoneMods(found.server.id)
const known = mods && mods.zoneManager && mods.zoneManager.flags && mods.zoneManager.flags.length ? mods.zoneManager.flags : null
const opts = zoneOptions.parse(params.options, known)
if (!opts.ok) return { ok: false, retry: false, error: opts.error }
const messages = {}
for (const key of ['enterMessage', 'leaveMessage']) {
const text = params[key] === undefined || params[key] === null ? '' : String(params[key]).trim()
if (text.length > ZONE_MESSAGE_MAX) return { ok: false, retry: false, error: `a zone's message is at most ${ZONE_MESSAGE_MAX} characters` }
if (text) messages[key] = text
}
const delivery = params.delivery === undefined || params.delivery === null || params.delivery === '' ? 'chat' : String(params.delivery)
if (delivery !== 'chat' && delivery !== 'popup') {
return { ok: false, retry: false, error: `a zone's messages go to chat or to a popup, not to "${params.delivery}"` }
}
// §3.2: a dome, where the server said it has ZoneDomes and the helper.
let dome = null
const domeName = params.dome === undefined || params.dome === null ? '' : String(params.dome).trim().toLowerCase()
if (domeName) {
const kind = DOMES.find((d) => d.value === domeName)
if (!kind) return { ok: false, retry: false, error: `a dome is ${DOMES.map((d) => d.value).join(', ')} or blank, not "${params.dome}"` }
const stack = num(params.domeStack)
if (Number.isNaN(stack) || (stack !== undefined && (!Number.isInteger(stack) || stack < 1 || stack > DOME_STACK_MAX))) {
return { ok: false, retry: false, error: `a dome stacks 1 to ${DOME_STACK_MAX} spheres, not "${params.domeStack}"` }
}
const missing = domeMissing(mods)
if (missing) return { ok: false, retry: false, error: missing }
dome = { type: kind.type, stack: stack === undefined ? 1 : stack }
}
// The dry run stops here, and has checked everything it can without the
// game. It does not ask whether the monument exists: a step authored for
// next wipe's map would fail every dry run until the wipe.
if (verify) return { ok: true }
// The chat voice (D140), as a chat line has it; a popup ignores it.
const hasMessage = Boolean(messages.enterMessage || messages.leaveMessage)
const format = hasMessage && delivery === 'chat' ? await voice.currentFormat() : null
return place(
found.server,
client.worldZone,
{
runId: String(runId),
key: idempotencyKey,
...where.wire,
radius,
holdMs: minutes * 60000,
...(params.name ? { name: String(params.name).slice(0, 64) } : {}),
...(opts.flags.length ? { flags: opts.flags } : {}),
...(Object.keys(opts.settings).length ? { settings: opts.settings } : {}),
...messages,
...(hasMessage ? { delivery } : {}),
...(format ? { format } : {}),
...(dome ? { dome } : {}),
},
'zone',
)
},
},
placeVerb({
id: 'rust.crate.place',
kind: 'crate',
budget: 'rust.prefabs',
max: MAX_CRATES,
label: 'Place crates',
description:
'Crates, barrels or a supply drop at a monument or a point, scattered a little. Taken away at teardown; a crate somebody looted is simply gone.',
source: 'rust.options.crates',
example: 'crate.elite',
}),
placeVerb({
id: 'rust.npc.place',
kind: 'npc',
budget: 'rust.npcs',
max: MAX_NPCS,
label: 'Place NPCs',
description:
"NPCs of one of the site's profiles (RunicNPC), or the server's own scientists or guards, at a monument or a point. Taken away at teardown. NPCs are never saved, so a restart ends them; the ledger then says so.",
source: 'rust.options.npcs',
example: 'npc.scientist',
}),
]
const OPTION_SOURCES = [
{
// Every server's map, live. A procedural map changes at every wipe, so a
// cached list would offer monuments that are not there any more.
id: 'rust.options.monuments',
label: 'Monuments',
description: "Each server's monuments on its current map. A kind that repeats is numbered, #1 first (D93).",
searchable: true,
async resolve({ q } = {}) {
const term = String(q || '').trim().toLowerCase()
const answers = await perServer((server) => client.worldMonuments(server))
const rows = []
for (const { server, result } of answers) {
for (const m of (result.data && result.data.monuments) || []) {
if (!m || !m.value) continue
const label = `${m.label}${m.of > 1 ? ` #${m.instance}` : ''}${m.grid ? ` · ${m.grid}` : ''}`
const value = `${server.id}/${m.value}`
if (term && !value.toLowerCase().includes(term) && !label.toLowerCase().includes(term)) continue
rows.push({ value, label, group: server.name || server.id })
}
}
return bounded(rows, 'rust.options.monuments')
},
},
// From the mirror, so both answer with every server off (the field they fill
// must never be taken away by an outage, MODULE_API §2.4). One per verb (D97).
//
// D243: the NPC list puts the site's RunicNPC profiles first, then Rust's own,
// each group named. A site without a server that has RunicNPC has no profile
// rows, and its list reads as it always did.
...['crate', 'npc'].map((kind) => ({
id: kind === 'npc' ? 'rust.options.npcs' : 'rust.options.crates',
label: kind === 'npc' ? 'NPCs' : 'Crates',
description:
kind === 'npc'
? "The site's NPC profiles, on servers with RunicNPC, then the NPCs a Rust server places of its own."
: 'The crates a Rust server places for events.',
async resolve() {
const own = PLACEABLE.filter((p) => p.kind === kind).map((p) => ({ value: p.key, label: p.label }))
if (kind !== 'npc') return own
let profiles = []
try {
profiles = await npcs.optionRows()
} catch (err) {
log.warn('could not list the NPC profiles for the picker', { error: err.message })
}
return profiles.length ? [...profiles, ...own.map((row) => ({ ...row, group: "Rust's own" }))] : own
},
})),
{
// Stage 5 (D270): an ally for a Place NPCs step. From the site's own clan
// mirror, so it answers with every server off. A row's value carries its
// server, because a clan id means something only on its own server.
id: 'rust.options.clans',
label: 'Clans',
description: "Each server's clans, as the site last read them.",
searchable: true,
async resolve({ q } = {}) {
const term = String(q || '').trim().toLowerCase()
const rows = (await clansDb.listActiveClans())
.filter((c) => c.clanId !== null && c.clanId !== undefined)
.map((c) => ({ value: `${c.serverId}/${c.clanId}`, label: `${c.name} (${c.memberCount})`, group: c.serverName || c.serverId }))
.filter((r) => !term || r.label.toLowerCase().includes(term))
return bounded(rows, 'rust.options.clans')
},
},
{
// D210: the admins' own presets. A row's VALUE is the options line itself,
// so picking one writes that line into the step, and the step keeps its own
// copy: a preset edited later changes no published event. From the site's
// own tables, so it answers with every server off.
id: 'rust.options.zone_presets',
label: 'Zone presets',
description: 'The zone presets saved under Admin → Rust zone presets, by the servers each is for.',
async resolve() {
return zones.optionRows()
},
},
{
id: 'rust.options.domes',
label: 'Domes',
description: "ZoneDomes' dome colours (D194). A coloured dome shows only where it meets terrain or a structure.",
async resolve() {
return DOMES.map((d) => ({ value: d.value, label: d.label }))
},
},
]
// ── The watch (§11.1) ───────────────────────────────────────────────────────
//
// Core asks the module what the world still holds once, at its own boot, and
// otherwise waits to be told. A game that restarted or wiped under a running
// event is the moment to tell it: the boot id changes on a restart, the wipe
// id on a wipe, and neither changes on a sidecar reconnect — which loses
// nothing and must not provoke a sweep.
const lastSeen = new Map()
/**
* Note a server's identity as the refresh saw it, and ask core to reconcile when
* it moved — once its world is loaded. The first sighting after this module boots is a baseline, not a
* change: core's own boot reconcile already covered it.
*/
function observeServer(serverId, { bootId, wipeId, worldReady } = {}) {
if (!serverId || (!bootId && !wipeId)) return false
// **Not until the world is loaded** (§28.6). The plugin connects before the
// save loads, so the new boot id arrives while every crate still looks gone;
// asked then, reconcile would orphan the lot. The plugin says when it is
// ready, and the change is noticed on that hello instead. An older plugin
// that never says is taken as ready, as it always was.
if (worldReady === false) return false
const previous = lastSeen.get(serverId)
lastSeen.set(serverId, { bootId: bootId || null, wipeId: wipeId || null })
if (!previous) return false
const restarted = Boolean(bootId && previous.bootId && bootId !== previous.bootId)
const wiped = Boolean(wipeId && previous.wipeId && wipeId !== previous.wipeId)
if (!restarted && !wiped) return false
log.info('game changed under the events ledger; asking core to reconcile', {
server: serverId,
...(restarted ? { restarted: { from: previous.bootId, to: bootId } } : {}),
...(wiped ? { wiped: { from: previous.wipeId, to: wipeId } } : {}),
})
try {
Promise.resolve(core.reconcileEvents()).catch((err) => log.warn('reconcile failed', { error: err.message }))
} catch (err) {
log.warn('reconcile failed', { error: err.message })
}
return true
}
/** For tests. */
function resetWatch() {
lastSeen.clear()
}
module.exports = {
BUDGET_MS,
MAX_CRATES,
MAX_NPCS,
ZONE_MAX_MINUTES,
PLACEABLE,
BUDGETS,
ACTIONS,
OPTION_SOURCES,
location,
splitRef,
revert,
reconcile,
observeServer,
expired,
resetWatch,
}

View File

@@ -50,7 +50,17 @@ module.exports = function register(ctx, api) {
const publicRust = require('./router/public/rust.router')
const playerRust = require('./router/player/rust.router')
const adminRust = require('./router/admin/rust.router')
const usersRust = require('./router/admin/usersRust.router')
const teamProvider = require('./model/clans/teamProvider')
const { TRIGGERS } = require('./engagement/triggers')
const { STREAMS } = require('./engagement/streams')
const { AUDIENCES } = require('./engagement/audiences')
const seeds = require('./engagement/seeds')
const eventLeases = require('./eventLeases')
const eventWorld = require('./eventWorld')
const eventRewards = require('./eventRewards')
const boot = require('./boot')
const commands = require('./commands')
/* eslint-enable global-require */
const log = core.logger()
@@ -78,6 +88,57 @@ module.exports = function register(ctx, api) {
admin: { '/rust': adminRust },
})
// R13's first extension slot (§2.4). Core declares `admin.users.detail` on
// `/api/v1/admin/users/:id` and we fill it; the router receives the parent's
// `req.params.id` through `mergeParams`. Core's own routes on the resource are
// declared before the slot is mounted, so core wins any path conflict — it owns
// the user, and this module owns what it can say about one.
//
// **It is declared twice, in two different places, on purpose.** This call is
// the SERVER half and `module.json`'s `extensions` array is held against it by
// the loader. The CLIENT half is `registry.registerExtension(ID,
// 'admin.users.detail', …)` in `entry.jsx` and must NOT appear in that array —
// phase 1 found that the hard way with `site.footer.status`, which is a client
// slot and fails the load outright when named there.
api.registerExtension('admin.users.detail', usersRust)
// Teams (R5, PLAN.md §24). A first-party Rust clan is a Team, and this module
// becomes the deployment's one authoritative source of them. Core asks; the
// provider answers from the clan boards (`model/clans`), and refuses rather
// than guessing whenever no board is current.
//
// **One provider per deployment**, so a site running module-uo as well cannot
// have both — the second registration is a collision core reports against the
// module that made it. That is core's rule and a real constraint on a mixed
// UO + Rust site; it is recorded in §24 rather than worked around here.
api.registerTeamProvider(teamProvider)
// Notifications and engagement (R7, PLAN.md §25). Four registrations that are
// one decision, because they only mean something together:
//
// triggers what can happen, what a template may say about it, and the
// widest audience a rule on it may EVER have — the security
// boundary; core refuses a rule that widens a ceiling
// streams which of those may reach a phone. Core pushes an engagement
// rule only to devices subscribed to a stream of the SAME id, so
// a trigger missing here can never buzz anybody (D65)
// audiences named sets of people over this module's data, for an operator
// to point a rule at; each answers user ids and nothing else
// seeds the two bodies worth writing, and one disabled rule group per
// family — installing this module mails nobody
//
// What fires them is `engagement/emit.js`, off the ingest cursor and the
// refresh. Registration is a claim, not a call: nothing here touches the
// database, and the seeds are written by core after the schema is up.
//
// The announce leg arrived with phase 13b (D62, D104), when there was a chat
// verb to deliver through; it is registered below with the rewards. There is
// still no post hook: nothing in game mirrors a post as state.
api.registerEventTriggers(TRIGGERS)
api.registerNotificationStreams(STREAMS)
api.registerAudiences(AUDIENCES)
api.registerEngagementSeeds({ templates: seeds.TEMPLATES, ruleGroups: seeds.RULE_GROUPS })
// The lifecycle hooks (§2.5). `onBoot` runs after core's schema, after this
// module's schema fragment, and BEFORE the HTTP listener binds — so a module
// that must not serve traffic until it has warmed a cache gets that for free.
@@ -90,16 +151,59 @@ module.exports = function register(ctx, api) {
api.onBoot(boot.onBoot)
api.onShutdown(boot.onShutdown)
// Everything else this module will register — the Team provider, the event
// triggers and audiences, the engagement seeds, the four event catalogues, the
// notification streams, the slash commands and the two extension slots — is
// deliberately absent. Each arrives with the phase that has something real to
// put in it. A registration with nothing behind it is worse than a missing one:
// a declared trigger nothing emits and a declared slot nothing fills are both
// surfaces an operator can configure and then wait on.
// The leases (PLAN.md §27, protocol 8): what an event may BORROW on a server
// and must give back. Core's `core.lease` is the verb; these are the values it
// may name and the four callables each ships. Every lease is targeted and the
// target names the server (D73), which is how one value on one server gets
// exactly one holder without core learning what a server is.
//
// The option sources are the three targets' own (D78).
api.registerEventLeases(eventLeases.LEASES)
// The world verbs (PLAN.md §28, protocol 9): what an event MAKES and gives
// back — a zone, crates, NPCs — and the budgets that price them, each declared
// beside the verb that spends it (D79, D89). A lease spends none of them.
//
// The rewards (PLAN.md §29, protocol 10) join them: the tally, the kit reward
// and the chat line, with the two budgets they spend. Registered in the same
// calls' neighbours, not merged into eventWorld's arrays, so each file keeps
// its own statement of what it declares.
api.registerEventBudgets([...eventWorld.BUDGETS, ...eventRewards.BUDGETS])
api.registerEventActions([...eventWorld.ACTIONS, ...eventRewards.ACTIONS])
// News in game chat (D104). Core enqueues every registered leg for every
// published post, so the leg itself sends only to the servers whose switch an
// operator turned on — off by default, and a server that is down is skipped.
api.registerAnnounceLeg(eventRewards.LEG)
// ONE call for every option source: core takes a batch once, as this module's
// complete statement, and refuses a second.
api.registerEventOptionSources([
...eventLeases.OPTION_SOURCES,
...eventWorld.OPTION_SOURCES,
...eventRewards.OPTION_SOURCES,
])
// The slash commands (phase 16, R11). The handlers run HERE, in the website
// process; the bot pulls the definitions and dispatches each call back. Every
// command is `access: 'everyone'` and resolves its own audience gate inside the
// handler, and every answer narrower than public is sent to the caller alone
// (D127) — see `commands/common.js`.
api.registerSlashCommands(commands)
log.info('registered', {
version: require('../module.json').version,
routes: 'public:/rust player:/rust admin:/rust',
extensions: 'admin.users.detail',
teams: 'first-party clans',
triggers: TRIGGERS.length,
streams: STREAMS.length,
audiences: AUDIENCES.length,
leases: eventLeases.LEASES.length,
actions: eventWorld.ACTIONS.length + eventRewards.ACTIONS.length,
budgets: eventWorld.BUDGETS.length + eventRewards.BUDGETS.length,
announceLeg: eventRewards.LEG.leg,
commands: commands.map((cmd) => cmd.name).join(' '),
optionSources: eventLeases.OPTION_SOURCES.length + eventWorld.OPTION_SOURCES.length + eventRewards.OPTION_SOURCES.length,
})
}

393
server/ingest.js Normal file
View File

@@ -0,0 +1,393 @@
// ── Reading a sidecar's feed, and turning it into a record ────────────────
//
// One job: move each server's cursor forward, and apply what it passed.
//
// ── Why a cursor and not a socket ─────────────────────────────────────────
//
// The obvious design is a WebSocket — the sidecar has one, and module-uo takes
// exactly that route for the UO bridge. This module polls a cursor instead, and
// the reason is not laziness about latency.
//
// Core runs on Node 20, where a global `WebSocket` is still behind a flag, so a
// socket means taking `ws` as a runtime dependency — and this module's release
// asserts that it has none (D5: everything it needs arrives on `ctx`, and the
// bundle ships no `node_modules`). That is a cost worth paying for latency, but
// the deciding argument is the other one: **a socket needs a cursor anyway.**
// Whatever a feed misses while a module is restarting has to be caught up from
// somewhere, and the catch-up path is the one that must be right. A socket on
// top of a cursor is two mechanisms where the second is load-bearing; a cursor
// alone is one mechanism that is exercised every few seconds rather than only
// after an outage nobody planned.
//
// What it costs is seconds of latency on a killfeed. What it buys is that the
// path which recovers from a five-hour outage is the same path that ran a moment
// ago.
//
// ── The ordering the whole thing rests on ─────────────────────────────────
//
// **The cursor advances after the batch is written, never before.** A crash
// between the two re-reads events already counted, which inflates a total; a
// crash the other way round loses them silently and for ever. Neither is good and
// they are not equally bad — one is visible and bounded, the other is invisible
// and permanent — so the code is arranged to fail in the visible direction.
const core = require('./core')
const clans = require('./model/clans/clans.model')
const configDb = require('./model/config/config.db')
const configModel = require('./model/config/config.model')
const db = require('./model/events/events.db')
const engagement = require('./engagement/emit')
const eventWorld = require('./eventWorld')
const links = require('./model/links/links.model')
const npcs = require('./model/npcs/npcs.model')
const npcsDb = require('./model/npcs/npcs.db')
const permissionsDb = require('./model/permissions/permissions.db')
const sidecar = require('./sidecarClient')
const log = core.logger('ingest')
/** How many events to ask for at once. */
const BATCH = 200
/**
* How many batches one tick will drain before letting the loop breathe.
*
* A module that has been down for a day has thousands of events waiting, and
* draining them in one unbounded loop would hold the tick — and a pool
* connection — for as long as that takes. Bounded, it catches up over several
* ticks and the site stays responsive while it does.
*/
const MAX_BATCHES_PER_TICK = 10
/**
* Applies one feed item.
*
* Every frame is stored raw, and only some of them move a counter. That split is
* deliberate: the raw row is what an admin reads and what a later phase can
* re-derive from, and the counters are what a leaderboard sums. A kind this
* build has never heard of still lands in `rust_events` — it costs nothing and
* the alternative is losing the one copy of an event the next version will know
* how to read.
*/
async function apply(serverId, item, server = null) {
const frame = (item && item.frame) || {}
const kind = item.kind || frame.kind
const wipeId = frame.wipeId || null
// A wipe exists because something mentioned it. There is no "a wipe started"
// call and there must not be one: the website is not there when a wipe happens.
await db.touchWipe(serverId, wipeId, frame.saveCreatedAt || null)
await db.insertEvent({
serverId,
wipeId,
kind,
t: Number(frame.t) || item.t || Date.now(),
steamId: frame.steamId || null,
raw: frame,
})
// What core's engagement engine is told (PLAN.md §25). BEFORE the frame is
// applied, because applying a disband deletes the roster the notification is
// for. Never throws, and does not hold the cursor on core: `onEvent` resolves
// who a frame is about and hands it over, and delivery is core's own time.
if (server) await engagement.onEvent(server, item)
const at = { serverId, wipeId, steamId: frame.steamId }
switch (kind) {
case 'player.connected':
await db.touchPlayer(frame.steamId, frame.name || null)
break
case 'player.disconnected': {
await db.touchPlayer(frame.steamId, frame.name || null)
// `sessionSec` is ABSENT when the plugin never saw the connect — a player
// already on the server when it loaded. Absent is not zero: adding a zero
// would be recording a session of no length, which is a different claim
// from recording no session, and it is the one that quietly under-reports
// playtime for ever.
const seconds = Number(frame.sessionSec)
await db.addStats(at, {
sessions: Number.isFinite(seconds) ? 1 : 0,
playtimeSec: Number.isFinite(seconds) && seconds > 0 ? seconds : 0,
})
break
}
case 'player.death': {
await db.touchPlayer(frame.steamId, frame.name || null)
// A suicide is a death AND a suicide, not one instead of the other: the
// deaths column is "how many times did this player die", and a leaderboard
// that silently omitted self-inflicted ones would disagree with the
// killfeed sitting next to it on the same page.
await db.addStats(at, { deaths: 1, suicides: frame.attackerType === 'self' ? 1 : 0 })
// Only a real player's kill counts. `npc` and `environment` have no
// attacker to credit, and `self` must not credit the victim with a kill —
// which is the one line here that would look right in review and produce a
// leaderboard topped by whoever died the most.
if (frame.attackerType === 'player' && frame.attackerId) {
await db.touchPlayer(frame.attackerId, frame.attackerName || null)
await db.addStats({ ...at, steamId: frame.attackerId }, { kills: 1 })
}
break
}
case 'player.tally': {
await db.touchPlayer(frame.steamId, frame.name || null)
await db.addStats(at, {
npcKills: Number(frame.npcKills) || 0,
structures: Number(frame.structures) || 0,
})
// A tally is a DELTA since the last flush, which is what makes adding it
// correct. If it ever becomes a running total this loop doubles every
// number in it, slowly, and looks right the whole time.
const gathered = frame.gathered || {}
for (const [resource, amount] of Object.entries(gathered)) {
await db.addGathered(at, resource, Number(amount) || 0)
}
// Protocol 13, the chat-title conditions (PLAN_REDESIGNS §5.1). Deltas
// too, except the two distances, which are this interval's best.
await db.addTitleStats(at, frame)
const weapons = frame.weaponKills && typeof frame.weaponKills === 'object' ? frame.weaponKills : {}
for (const [weapon, kills] of Object.entries(weapons)) {
await db.addWeaponKills(at, weapon, Math.floor(Number(kills) || 0))
}
// RunicNPC's NPCs, by profile name (D247). Credited to the site profile
// that name was last pushed as on this server, so "this profile only"
// can be counted; 0 for a name the site never pushed.
const profiles = frame.npcProfileKills && typeof frame.npcProfileKills === 'object' ? frame.npcProfileKills : {}
for (const [profile, kills] of Object.entries(profiles)) {
const n = Math.floor(Number(kills) || 0)
if (n > 0) await npcsDb.addKills(at, profile, await npcs.siteProfileFor(serverId, profile), n)
}
break
}
case 'player.chat':
case 'player.respawned':
await db.touchPlayer(frame.steamId, frame.name || null)
break
// ── Protocol 3: the one frame that changes something other than a counter ──
//
// `/unlink` in game severs the site's link, and it is the only way out of a
// link on the wrong account: the site REFUSES to move a Steam id another
// website account already holds (D23), so without this a player who linked
// while signed in as the wrong account would need staff.
//
// It arrives here rather than through a route because the plugin has nothing
// to delete — the site is the author of record and the game holds no link —
// so `/unlink` is the game reporting what the player asked for, applied off
// the feed like every other frame.
//
// **The authority is the Steam account itself.** Whoever is connected to the
// game as it is who it is, which is a stronger proof of ownership than the
// site can obtain any other way, so this is not scoped by website user.
case 'account.unlinked':
await db.touchPlayer(frame.steamId, frame.name || null)
await links.unlinkFromGame(frame.steamId)
break
// Stored and counted as a sighting, nothing more. The code is deliberately
// NOT on this frame — it travels through the player — so there is nothing
// here to redeem and no pending state for the site to hold. It exists so an
// operator can see linking being used at all.
case 'account.link.requested':
await db.touchPlayer(frame.steamId, frame.name || null)
break
// ── Protocol 4: somebody changed the permission store, and it was not us ──
//
// The plugin raises this only for writes it did not make itself — its own
// sync suppresses the hooks while it applies (PROTOCOL.md §10.4). What
// arrives here is therefore a hand edit, a console command, or another
// plugin granting something.
//
// **It is a reason to reconcile, not the reconciliation.** This frame cannot
// say whether the change is foreign: only the desired set can, and that
// comparison happens in the sync. So the server is marked dirty and the next
// tick produces the authoritative answer — which means a hook that stops
// firing on a framework upgrade costs latency and nothing else. The audit
// interval finds the same drift within fifteen minutes either way.
case 'perm.drift':
await permissionsDb.markDirty(serverId)
break
// ── Protocol 13: a plugin loaded or unloaded (F8, D184) ─────────────────
//
// A grant for a plugin that was not loaded stays `unresolved` until that
// plugin comes back, and the first walk watched one land thirteen minutes
// late, on the fifteen-minute audit. The frame carries the permissions the
// plugin added or removed, and only a non-empty list is a reason to sync —
// a plugin that registers nothing cannot have changed what a grant resolves
// to. `perm.drift`'s posture: a reason, and the next tick (30 s) is the answer.
case 'plugin.loaded':
case 'plugin.unloaded':
if (Array.isArray(frame.permissions) && frame.permissions.length > 0) {
await permissionsDb.markDirty(serverId)
}
break
// ── Protocol 13: a zone reached its deadline (F13, F14, D170, D183) ──────
//
// Core records the run's resource row as `expired`. Not awaited: it is
// core's bookkeeping, fire-and-forget by contract.
case 'world.expired':
eventWorld.expired(serverId, frame)
break
// ── Protocol 13: how a configuration save's reload ended (F9, D179) ─────
//
// The save was answered before the reload finished and recorded as
// `reloading`; this is the rest of it. Only a row still `reloading` moves,
// so a replayed frame changes nothing, and one that arrives after the page
// gave up on it (`lost`) still lands — the audit row ends up true either way.
case 'config.outcome': {
const outcome = configModel.outcomeOf(frame)
if (outcome) await configDb.settleWrite(serverId, outcome)
break
}
// ── Protocol 6: first-party clans ──────────────────────────────────────
//
// Each one is told to core as it happens (`ctx.teams.publish`) and written
// to the clan's Team feed as a members-only line (D49). Neither is the
// record: the `clans` board the plugin re-sends a few seconds later is what
// the store is rebuilt from, so an event this module never saw costs a
// feed line and nothing else.
//
// No `touchPlayer` here, on purpose: it moves `last_seen`, and a kick is
// done TO somebody who may be offline. `model/clans` notes names without it.
case 'clan.created':
case 'clan.disbanded':
case 'clan.member.added':
case 'clan.member.left':
case 'clan.member.kicked':
await clans.applyEvent(serverId, frame)
break
default:
// Stored, not counted. Moderation frames, the server lifecycle, and
// anything a newer protocol sends that this build does not understand.
break
}
}
/**
* Brings one server's cursor up to date.
*
* Returns the number of events applied, for the log and for the tests.
*/
async function ingestServer(server) {
const cursor = await db.getCursor(server.id)
// A server this module has never ingested starts at the sidecar's CURRENT end,
// not at zero. A module installed today against a sidecar that has been running
// for a month should read what happens next — replaying a fortnight of deaths
// into stats for wipes it never saw is not a catch-up, it is inventing a
// history it was not present for. `/feed` with no `since` asks exactly that
// question, which is why the sidecar answers it that way.
if (!cursor) {
const tail = await sidecar.feedTail(server)
if (!tail.ok || !tail.data) {
// Unreachable. Write nothing: a cursor of 0 written now would replay the
// whole retained history the moment the sidecar came back.
return 0
}
await db.setCursor(server.id, Number(tail.data.lastId) || 0, 0)
log.info('cursor started at the feed tail', { server: server.id, at: tail.data.lastId })
return 0
}
let since = Number(cursor.lastEventId) || 0
let applied = 0
for (let batch = 0; batch < MAX_BATCHES_PER_TICK; batch += 1) {
const res = await sidecar.feed(server, since, BATCH)
if (!res.ok || !res.data) return applied
const items = Array.isArray(res.data.items) ? res.data.items : []
for (const item of items) {
try {
await apply(server.id, item, server)
applied += 1
} catch (err) {
// One malformed event must not wedge a server's cursor for ever. It is
// logged with its id so it can be found, and the cursor moves past it:
// the alternative is an ingest that stops at a single bad row and then
// silently stops being a feed at all.
log.warn('could not apply an event', {
server: server.id,
id: item && item.id,
kind: item && item.kind,
error: err.message,
})
}
}
const lastId = Number(res.data.lastId)
if (Number.isFinite(lastId) && lastId > since) {
// AFTER the batch. See the header.
await db.setCursor(server.id, lastId, items.length)
since = lastId
}
if (!res.data.more) break
}
if (applied > 0) {
log.info('ingested', { server: server.id, events: applied, cursor: since })
// A leader can only change when something was applied. Never throws.
await engagement.checkLeader(server)
}
return applied
}
/**
* Applies the boards: what is true right now, rather than what happened.
*
* `players.online` replaces the presence rows wholesale, because that is what a
* board is. Storing it as history is the mistake the wire's `type` field exists
* to prevent, and it would be a poor return for the sidecar's trouble to make it
* here after it went out of its way not to make it there.
*/
async function applyBoards(serverId, boards) {
const presence = boards && boards['players.online']
if (presence && Array.isArray(presence.players)) {
await db.replacePresence(serverId, presence.players)
}
// Clans only once the game has spoken at all. A sidecar that has never heard
// from its plugin holds no boards, and recording "no clan board" then would
// blame the plugin's protocol for a game server that is simply not up. Left
// alone, the stored board ages past fresh on its own, which is the true answer.
if (boards && boards['server.hello']) {
// Fenced: clans are the one board here that core's Teams depend on, and a
// failure applying them must cost the clans rather than the presence board
// above or the server state the caller writes next.
try {
await clans.applyBoard(serverId, boards.clans)
await clans.reofferActivity(serverId)
} catch (err) {
log.warn('could not apply the clan board', { server: serverId, error: err.message })
}
}
}
module.exports = { apply, applyBoards, ingestServer, BATCH, MAX_BATCHES_PER_TICK }

277
server/mapImages.js Normal file
View File

@@ -0,0 +1,277 @@
// ── The map's picture: noticing a new map and fetching it ─────────────────
//
// R9's first half, as the rig rewrote it (PLAN.md §30.0). The picture is not
// extracted from anything: the game's Rust+ service already holds a JPEG of the
// map in memory, and the plugin hands it over in 512 KiB slices. That changes
// the one rule R9 carried over from the asset bridge, where a fetch was an
// expensive extraction:
//
// **D110 — the site fetches the picture BY ITSELF the first time it sees a map
// it does not have**, because reading the cache costs the game nothing. It is
// triggered off the board poll (`boot.js`): a new boot, wipe, seed or world
// size, or a server with no row at all, is a reason to ask `map.info`, and a
// key or hash that differs from the row is a reason to fetch.
//
// **D109 — a render is never automatic.** A server with no Rust+ cache has no
// picture until an admin presses Render now, which stalls that game for seconds
// and is said so beside the button. The render answers at once and happens on a
// later frame; this file then polls `map.info` until the picture exists and
// fetches it like any other.
//
// Three rules the fetch keeps:
//
// • **One fetch per server at a time**, held here. A second trigger while one
// runs is dropped, and an admin's Fetch again is told one is running.
// • **A fetch that straddles a map change is abandoned whole.** The plugin
// refuses a slice with `stale` when the key or hash moved, and the bytes are
// checked against the hash before anything is written: two maps are never
// spliced, and a half-fetched picture is never stored.
// • **A failure keeps the old row** and retries on a backoff. The page keeps
// drawing the last picture it had, which is still the right map until the
// key says otherwise.
const crypto = require('crypto')
const core = require('./core')
const db = require('./model/map/map.db')
const model = require('./model/map/map.model')
const sidecar = require('./sidecarClient')
const log = core.logger('map')
/** Backoff after a failed fetch: 30 s doubling to 10 minutes. */
const BACKOFF_MIN_MS = 30 * 1000
const BACKOFF_MAX_MS = 10 * 60 * 1000
/** How soon to ask again when the plugin is still hashing, or the world still loading. */
const SOON_MS = 3000
/** How long a render is watched for before this side gives up on it (a 6000 map stalls ~40 s). */
const RENDER_WATCH_MS = 5 * 60 * 1000
const RENDER_POLL_MS = 3000
/** The first protocol whose plugin knows the map verbs. */
const MAP_PROTOCOL = 11
/** The most slices one picture may have: 16 MiB, MEDIUMBLOB's ceiling. */
const MAX_CHUNKS = 32
/**
* Per server: the observation last acted on, whether a fetch is running, and
* when the next try may happen. In memory, deliberately — a restart of the
* website forgets it and asks once more, which costs one `map.info`.
*/
const state = new Map()
function stateOf(serverId) {
if (!state.has(serverId)) {
state.set(serverId, { sig: null, running: null, nextTryAt: 0, failures: 0, rendering: null, lastError: null })
}
return state.get(serverId)
}
/** What about a server makes its map worth asking about again. */
const signature = ({ bootId, wipeId, seed, worldSize }) => [bootId, wipeId, seed, worldSize].map((v) => (v == null ? '' : String(v))).join('|')
/**
* Called by every board poll for a CONNECTED server whose world is ready. Cheap
* when nothing moved: one map lookup and a string compare. When something did,
* it starts a fetch in the background and returns — the poll never waits on a
* picture.
*/
function observe(server, frame, now = Date.now()) {
if (!server || !frame || frame.worldReady === false) return
// The game link has no version handshake: a plugin older than protocol 11
// never answers `map.info`, and asking would cost a full reply timeout a try.
if (!(Number(frame.protocol) >= MAP_PROTOCOL)) return
const s = stateOf(server.id)
const sig = signature(frame)
if (s.running || now < s.nextTryAt) return
if (s.sig === sig) return
run(server, sig).catch((err) => log.warn('map fetch failed', { server: server.id, error: err.message }))
}
/**
* One fetch cycle. Resolves `{ ok, outcome, detail }`, never rejects in normal
* operation; the outcome words are what the admin card shows.
*
* fetched a new picture is stored
* current the stored picture is already this map's
* none the game has no picture; geometry stored so layers can be drawn
* busy another fetch is running (admin only)
* failed something did not answer; the old row is kept
*/
function run(server, sig = null, { force = false } = {}) {
const s = stateOf(server.id)
if (s.running) return Promise.resolve({ ok: false, outcome: 'busy', detail: 'a fetch is already running for this server' })
s.running = (async () => {
try {
const result = await fetchOnce(server, { force })
if (result.retrySoon) {
s.nextTryAt = Date.now() + SOON_MS
return result
}
if (result.ok) {
s.sig = sig
s.failures = 0
s.nextTryAt = 0
s.lastError = null
} else {
s.failures += 1
s.nextTryAt = Date.now() + Math.min(BACKOFF_MAX_MS, BACKOFF_MIN_MS * 2 ** (s.failures - 1))
s.lastError = result.detail || result.outcome
}
return result
} finally {
s.running = null
}
})()
return s.running
}
/** The plugin's refusal, as a sentence, or null when the answer was not one. */
function refusal(res) {
if (!res.ok) return `the sidecar did not answer (${res.status})`
if (res.data && res.data.kind === 'map.error') return res.data.message || res.data.reason || 'refused'
return null
}
async function fetchOnce(server, { force }) {
const info = await sidecar.mapInfo(server)
const why = refusal(info)
if (why) {
// A world still loading is not a failure worth backing off for.
if (info.ok && info.data && info.data.reason === 'not-ready') return { ok: false, retrySoon: true, outcome: 'failed', detail: why }
return { ok: false, outcome: 'failed', detail: why }
}
const data = info.data || {}
if (data.hashing) return { ok: false, retrySoon: true, outcome: 'failed', detail: 'the plugin is still hashing the picture' }
const row = model.derive(server.id, data)
if (!row.mapKey) return { ok: false, outcome: 'failed', detail: 'map.info named no map' }
const stored = await db.getMeta(server.id)
if (row.source === 'none') {
// The same map with a picture already stored keeps it: nothing about the map
// changed, only where a picture would come from now. A different map, or no
// row at all, stores the geometry so the page can draw the layers.
if (stored && stored.mapKey === row.mapKey && stored.sha256) {
await db.putGeometry({ ...row, source: stored.source, width: Number(stored.width), height: Number(stored.height), background: stored.background })
return { ok: true, outcome: 'current', detail: 'the game has no picture now; the stored one is the same map' }
}
await db.putImage(row)
return { ok: true, outcome: 'none', detail: 'the game has no picture of its map; an admin can render one' }
}
if (!force && stored && stored.mapKey === row.mapKey && stored.sha256 === row.sha256) {
if (Number(stored.derivation) !== model.DERIVATION_VERSION || stored.source !== row.source) await db.putGeometry(row)
return { ok: true, outcome: 'current', detail: 'the stored picture is this map' }
}
const chunks = Number(data.chunks)
if (!Number.isInteger(chunks) || chunks < 1 || chunks > MAX_CHUNKS) {
return { ok: false, outcome: 'failed', detail: `the plugin described ${data.chunks} slices` }
}
const parts = []
for (let n = 0; n < chunks; n += 1) {
// eslint-disable-next-line no-await-in-loop
const res = await sidecar.mapChunk(server, { mapKey: row.mapKey, sha256: row.sha256, n })
const no = refusal(res)
if (no) {
// `stale` means the map moved under the fetch: start again soon rather
// than back off, because the next `map.info` describes the new one.
if (res.ok && res.data && res.data.reason === 'stale') return { ok: false, retrySoon: true, outcome: 'failed', detail: no }
return { ok: false, outcome: 'failed', detail: `slice ${n}: ${no}` }
}
if (!res.data || res.data.kind !== 'map.chunk' || Number(res.data.chunk) !== n || typeof res.data.data !== 'string') {
return { ok: false, outcome: 'failed', detail: `slice ${n} was not the slice asked for` }
}
parts.push(Buffer.from(res.data.data, 'base64'))
}
const bytes = Buffer.concat(parts)
const hash = crypto.createHash('sha256').update(bytes).digest('hex')
if (hash !== row.sha256 || (Number(data.bytes) > 0 && bytes.length !== Number(data.bytes))) {
return { ok: false, outcome: 'failed', detail: 'the picture did not match its own hash; nothing was stored' }
}
await db.putImage({ ...row, bytes })
log.info('map picture stored', { server: server.id, mapKey: row.mapKey, source: row.source, bytes: bytes.length })
return { ok: true, outcome: 'fetched', detail: `${bytes.length} bytes from ${row.source}` }
}
/**
* An admin's Render now (D109). Refused here when a render is already being
* watched; the plugin refuses the rest (a picture exists, the world is loading).
* On `accepted` the render is watched in the background: `map.info` is polled
* until its source is `rendered` — through a stall that makes the game answer
* nothing at all for its duration — and then fetched like any picture.
*/
async function render(server, actor) {
const s = stateOf(server.id)
if (s.rendering) return { ok: false, status: 409, message: 'A render is already running for this server.' }
const res = await sidecar.mapRender(server, { actor: actor || null })
const no = refusal(res)
if (no) {
const reason = res.ok && res.data ? res.data.reason : null
return { ok: false, status: reason === 'has-picture' || reason === 'busy' ? 409 : 502, message: no, reason }
}
s.rendering = { startedAt: Date.now() }
watchRender(server).catch((err) => log.warn('render watch failed', { server: server.id, error: err.message }))
return { ok: true, worldSize: res.data && res.data.worldSize, stallSeconds: model.renderStallSeconds(res.data && res.data.worldSize) }
}
async function watchRender(server) {
const s = stateOf(server.id)
const until = Date.now() + RENDER_WATCH_MS
try {
while (Date.now() < until) {
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
const t = setTimeout(resolve, RENDER_POLL_MS)
if (typeof t.unref === 'function') t.unref()
})
// eslint-disable-next-line no-await-in-loop
const info = await sidecar.mapInfo(server)
const data = info.ok && info.data ? info.data : null
if (!data || data.kind !== 'map.info') continue // the game is mid-stall and answering nothing
if (data.rendering) continue
if (data.source === 'none') {
s.lastError = 'the render finished without a picture — see rg.map on the server console'
return
}
// eslint-disable-next-line no-await-in-loop
await run(server, null, { force: false })
return
}
s.lastError = 'the render did not finish within five minutes'
} finally {
s.rendering = null
}
}
/** For the admin card: what this side is doing about each server's picture. */
function statusOf(serverId) {
const s = state.get(serverId)
if (!s) return { fetching: false, rendering: false, lastError: null }
return { fetching: Boolean(s.running), rendering: Boolean(s.rendering), lastError: s.lastError }
}
/** Test seam: forget everything. */
function _reset() {
state.clear()
}
module.exports = { observe, run, render, statusOf, signature, MAX_CHUNKS, _reset }

58
server/mapLive.js Normal file
View File

@@ -0,0 +1,58 @@
// ── What moves on the map, asked for while somebody is looking ────────────
//
// D111: positions are request/reply, never a board. A board would run with
// nobody looking and keep where everybody is at rest in the sidecar's database;
// this asks `map.live` only when a page does, and keeps the answer IN MEMORY for
// five seconds.
//
// **Any number of viewers cost one ask.** Every request inside the window is
// served from the same answer, and a request that arrives while an ask is in
// flight waits for that ask rather than starting a second — so the sidecar sees
// at most one `map.live` per server per window, whoever and however many are
// watching (§30.4 step 7).
//
// The cache holds EVERY layer, unfiltered; each viewer's answer is projected
// from it by `model/map`. That is why it never leaves this process.
const sidecar = require('./sidecarClient')
const model = require('./model/map/map.model')
/** serverId → { at, answer } for the last good answer, and { pending } while one is in flight. */
const cache = new Map()
/**
* One server's live answer, from the cache when it is fresh. Resolves `{ ok,
* data, status }` like every sidecar call; never rejects.
*/
async function live(server, now = Date.now) {
const hit = cache.get(server.id)
if (hit && hit.answer && now() - hit.at < model.LIVE_CACHE_MS) return hit.answer
if (hit && hit.pending) return hit.pending
const pending = (async () => {
const res = await sidecar.mapLive(server)
const refused = res.ok && res.data && res.data.kind === 'map.error'
const answer = res.ok && !refused
? { ok: true, status: 'ok', data: res.data }
: { ok: false, status: refused ? res.data.reason || 'refused' : res.status, data: null }
// A failure is cached for the window too: a game that is down must not be
// asked once per viewer per poll while it stays down.
cache.set(server.id, { at: now(), answer })
return answer
})()
cache.set(server.id, { ...(hit || {}), pending })
try {
return await pending
} finally {
const entry = cache.get(server.id)
if (entry && entry.pending === pending) delete entry.pending
}
}
/** Test seam. */
function _reset() {
cache.clear()
}
module.exports = { live, _reset }

View File

@@ -0,0 +1,298 @@
// ── SQL for first-party clans ─────────────────────────────────────────────
//
// Three tables (see `schema.sql`): the clans a board carried, their members, and
// what this module knows about each server's board. Raw parameterised SQL, as
// everywhere in this module; the model decides what any of it means.
const core = require('../../core')
const CLANS = 'rust_clans'
const MEMBERS = 'rust_clan_members'
const BOARDS = 'rust_clan_boards'
const LINKS = 'rust_account_links'
const PLAYERS = 'rust_players'
const SERVERS = 'rust_servers'
// ── Boards ─────────────────────────────────────────────────────────────────
/** One server's board record, or null when it has never sent one. */
async function getBoard(serverId) {
const rows = await core.query(
`SELECT server_id AS serverId, board_t AS boardT, seen_at AS seenAt, enabled, supported,
truncated, backend, reason, umod_clans AS umodClans, clan_count AS clanCount
FROM ${BOARDS} WHERE server_id = ?`,
[serverId],
)
return rows[0] || null
}
/** Every configured server beside its board record, which may be absent. */
async function listBoards() {
return core.query(
`SELECT s.id AS serverId, s.name AS serverName, s.enabled AS serverEnabled,
b.board_t AS boardT, b.seen_at AS seenAt, b.enabled, b.supported, b.truncated,
b.backend, b.reason, b.umod_clans AS umodClans, b.clan_count AS clanCount
FROM ${SERVERS} s
LEFT JOIN ${BOARDS} b ON b.server_id = s.id
ORDER BY s.sort_order ASC, s.id ASC`,
)
}
/**
* Records what a board said about itself.
*
* `seenAt` is passed only when the board's `t` ADVANCED, and is then the
* website's own now; otherwise the stored one is kept. That is the whole of the
* freshness rule (see `schema.sql`), so it is done in SQL rather than trusted to
* every caller to read-then-write.
*/
async function putBoard({ serverId, boardT, advanced, enabled, supported, truncated, backend, reason, umodClans, clanCount }) {
await core.query(
`INSERT INTO ${BOARDS}
(server_id, board_t, seen_at, enabled, supported, truncated, backend, reason, umod_clans, clan_count, updated_at)
VALUES (?, ?, ${advanced ? 'CURRENT_TIMESTAMP' : 'NULL'}, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
board_t = VALUES(board_t),
seen_at = ${advanced ? 'CURRENT_TIMESTAMP' : 'seen_at'},
enabled = VALUES(enabled), supported = VALUES(supported), truncated = VALUES(truncated),
backend = VALUES(backend), reason = VALUES(reason), umod_clans = VALUES(umod_clans),
clan_count = VALUES(clan_count), updated_at = CURRENT_TIMESTAMP`,
[
serverId,
boardT,
enabled ? 1 : 0,
supported ? 1 : 0,
truncated ? 1 : 0,
backend || null,
reason ? String(reason).slice(0, 255) : null,
umodClans ? 1 : 0,
clanCount || 0,
],
)
}
// ── Clans ──────────────────────────────────────────────────────────────────
/** Every clan this module holds for one server, gone or not. */
async function listClansForServer(serverId) {
return core.query(
`SELECT external_id AS externalId, clan_id AS clanId, created_ms AS createdMs, name,
member_count AS memberCount, gone_at AS goneAt
FROM ${CLANS} WHERE server_id = ?`,
[serverId],
)
}
/**
* Every member of one server's current clans, as the board last stated them,
* for diffing the next board against. The name is the BOARD's, not the player
* table's, because it is compared with the board.
*/
async function listMembersForServer(serverId) {
return core.query(
`SELECT m.external_id AS externalId, m.steam_id AS steamId, m.role_rank AS rank,
m.role_name AS role, m.name
FROM ${MEMBERS} m
JOIN ${CLANS} c ON c.external_id = m.external_id
WHERE c.server_id = ? AND c.gone_at IS NULL`,
[serverId],
)
}
async function upsertClan({ externalId, serverId, clanId, createdMs, name, color, score, memberCount, maxMembers }) {
await core.query(
`INSERT INTO ${CLANS}
(external_id, server_id, clan_id, created_ms, name, color, score, member_count, max_members,
first_seen, updated_at, gone_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, NULL)
ON DUPLICATE KEY UPDATE
name = VALUES(name), color = VALUES(color), score = VALUES(score),
member_count = VALUES(member_count), max_members = VALUES(max_members),
updated_at = CURRENT_TIMESTAMP, gone_at = NULL`,
[externalId, serverId, clanId, createdMs, name, color, score, memberCount, maxMembers],
)
}
/**
* Replaces one clan's members.
*
* Delete then insert, not wrapped in a transaction — the same trade the presence
* board makes (`events.db.replacePresence`): a fraction of a second in which a
* roster read might come back short, against holding a lock on a table that core's
* reconciler and two public routes read.
*/
async function replaceMembers(externalId, members) {
await core.query(`DELETE FROM ${MEMBERS} WHERE external_id = ?`, [externalId])
for (const m of members) {
// eslint-disable-next-line no-await-in-loop
await core.query(
`INSERT INTO ${MEMBERS} (external_id, steam_id, name, role_rank, role_name, joined_ms)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE name = VALUES(name), role_rank = VALUES(role_rank),
role_name = VALUES(role_name), joined_ms = VALUES(joined_ms)`,
[externalId, m.steamId, m.name, m.rank, m.role, m.joinedMs],
)
}
}
/** Marks clans gone. Their members are removed with them; a gone clan has no roster. */
async function markGone(externalIds) {
if (!externalIds.length) return
const marks = externalIds.map(() => '?').join(', ')
await core.query(
`UPDATE ${CLANS} SET gone_at = CURRENT_TIMESTAMP WHERE external_id IN (${marks}) AND gone_at IS NULL`,
externalIds,
)
await core.query(`DELETE FROM ${MEMBERS} WHERE external_id IN (${marks})`, externalIds)
}
/** One clan by its Team identity, with its server's name, or null. */
async function findClan(externalId) {
const rows = await core.query(
`SELECT c.external_id AS externalId, c.server_id AS serverId, s.name AS serverName,
c.clan_id AS clanId, c.created_ms AS createdMs, c.name, c.color, c.score,
c.member_count AS memberCount, c.max_members AS maxMembers,
c.first_seen AS firstSeen, c.updated_at AS updatedAt, c.gone_at AS goneAt
FROM ${CLANS} c
JOIN ${SERVERS} s ON s.id = c.server_id
WHERE c.external_id = ?`,
[externalId],
)
return rows[0] || null
}
/**
* The newest clan this module holds under a game id on one server, or null.
*
* The fallback for the one event that can arrive without a creation time
* (`clan.member.added`, when the plugin could not read the clan back). Newest,
* because an id that the game has re-used belongs to the clan that re-used it.
*/
async function findByGameId(serverId, clanId) {
const rows = await core.query(
`SELECT external_id AS externalId, name
FROM ${CLANS} WHERE server_id = ? AND clan_id = ?
ORDER BY created_ms DESC LIMIT 1`,
[serverId, clanId],
)
return rows[0] || null
}
/** Every clan still on a board, for core's `getTeams`. */
async function listActiveClans() {
return core.query(
`SELECT c.external_id AS externalId, c.server_id AS serverId, s.name AS serverName, c.clan_id AS clanId,
c.name, c.color, c.score, c.member_count AS memberCount
FROM ${CLANS} c
JOIN ${SERVERS} s ON s.id = c.server_id
WHERE c.gone_at IS NULL
ORDER BY c.server_id ASC, c.score DESC, c.name ASC`,
)
}
/** One server's clans still on its board, for the public Clans tab. Best first. */
async function listPublicForServer(serverId) {
return core.query(
`SELECT external_id AS externalId, name, color, score, member_count AS memberCount,
max_members AS maxMembers
FROM ${CLANS}
WHERE server_id = ? AND gone_at IS NULL
ORDER BY score DESC, name ASC`,
[serverId],
)
}
/**
* One clan's roster, with the website account behind each member when there is
* one and whether they are on the clan's server right now.
*
* Three joins, all of this module's own tables: the link (a Steam id to a user),
* the player table (the newest name the game has sent for them) and the presence
* board. Presence is joined on the CLAN's server — a member on another server of
* the fleet is not online here.
*/
async function listMembers(externalId) {
return core.query(
`SELECT m.steam_id AS steamId, COALESCE(p.name, m.name) AS name, m.role_rank AS rank,
m.role_name AS role, m.joined_ms AS joinedMs, l.user_id AS userId,
(pr.steam_id IS NOT NULL) AS online
FROM ${MEMBERS} m
JOIN ${CLANS} c ON c.external_id = m.external_id
LEFT JOIN ${LINKS} l ON l.steam_id = m.steam_id
LEFT JOIN ${PLAYERS} p ON p.steam_id = m.steam_id
LEFT JOIN rust_presence pr ON pr.server_id = c.server_id AND pr.steam_id = m.steam_id
WHERE m.external_id = ?
ORDER BY (m.role_rank IS NULL) ASC, m.role_rank ASC, name ASC`,
[externalId],
)
}
/** Whether a website user holds a linked Steam account that is a member of this clan. */
async function userIsMember(externalId, userId) {
const rows = await core.query(
`SELECT 1 AS yes
FROM ${MEMBERS} m
JOIN ${LINKS} l ON l.steam_id = m.steam_id
WHERE m.external_id = ? AND l.user_id = ?
LIMIT 1`,
[externalId, userId],
)
return rows.length > 0
}
/**
* Recent clan events for one server, oldest first, for re-offering their feed
* items to core until the Team they name exists (see `model/clans`).
*/
async function recentClanEvents(serverId, sinceMs) {
return core.query(
`SELECT id, kind, t, raw
FROM rust_events
WHERE server_id = ? AND kind LIKE 'clan.%' AND t >= ?
ORDER BY t ASC, id ASC
LIMIT 200`,
[serverId, sinceMs],
)
}
/**
* Notes a player's name WITHOUT touching `last_seen`.
*
* `events.db.touchPlayer` also moves `last_seen`, which is right for a frame that
* says a player was on and wrong for a clan frame: a kick is done TO somebody who
* may be offline, and a leaderboard's "last seen" would then read as a presence
* signal for a player who never connected (PLAN.md §23).
*
* A player this module has never heard of still gets a on the new row,
* because the column is NOT NULL; what matters is that an existing row's is left
* alone, and every surface that reads it is behind the presence gate anyway.
*/
async function rememberName(steamId, name) {
if (!steamId) return
await core.query(
`INSERT INTO ${PLAYERS} (steam_id, name, first_seen, last_seen)
VALUES (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE name = COALESCE(VALUES(name), name)`,
[steamId, name || null],
)
}
module.exports = {
getBoard,
listBoards,
putBoard,
listClansForServer,
listMembersForServer,
upsertClan,
replaceMembers,
markGone,
findClan,
findByGameId,
listActiveClans,
listPublicForServer,
listMembers,
userIsMember,
recentClanEvents,
rememberName,
}

View File

@@ -0,0 +1,574 @@
// ── First-party clans: the board, the events, and who may see a roster ────
//
// Rust's OWN clan system, which this module turns into core's Teams (R5,
// PLAN.md §24). Three jobs, one file, because all three have to agree on what a
// clan's identity is:
//
// applyBoard a `clans` snapshot → the store, plus what changed
// applyEvent a `clan.*` event → core (publish) and the Team feed
// canSeeRoster D48's audience, for core's `projectRoster` and our own page
//
// ── The identity (D52) ────────────────────────────────────────────────────
//
// `<serverId>:<clanId>:<createdMs>`. The game's clan id alone is not one: its
// database file carries a hard-coded version, so a game update that bumps it
// starts a fresh file and ids restart at 1. Keyed on the id, the new clan #1
// would inherit the old clan #1's Team, forum and history.
//
// ── What a board may conclude, and what it may not ───────────────────────
//
// A board is authoritative for the clans it CARRIES. It is authoritative about
// the clans it does NOT carry only when it is complete: a board truncated at the
// game's 100-clan ceiling (D55), or one with a row this build could not read,
// proves nothing about a clan it leaves out, and marking that clan gone would
// hand core an archive on no evidence.
const crypto = require('node:crypto')
const core = require('../../core')
const db = require('./clans.db')
const visibility = require('../visibility/visibility.model')
const log = core.logger('clans')
/**
* How long a board may go without its `t` advancing and still count as current.
*
* The plugin re-sends it every 60 seconds and this module reads it every 30, so
* three minutes tolerates two missed boards before a server stops vouching for
* its clans.
*/
const FRESH_MS = 3 * 60 * 1000
/**
* How far back a clan event's feed item is offered to core again.
*
* Core writes an item only for a Team it already holds, and a clan founded a
* moment ago is not one yet: its Team appears on core's next reconcile, which is
* debounced by up to 30 seconds. So the "founded" line — the first line of every
* clan's feed — would always be dropped if it were offered once. It is offered
* on every board refresh for this long instead, and core's dedupe key makes every
* offer after the first that lands a no-op.
*/
const REOFFER_MS = 10 * 60 * 1000
/** Team kinds core's `publish` takes, by the clan event that produces them. */
const PUBLISH = Object.freeze({
'clan.created': 'team.created',
'clan.disbanded': 'team.disbanded',
'clan.member.added': 'team.member.added',
'clan.member.left': 'team.member.removed',
'clan.member.kicked': 'team.member.removed',
})
/**
* The feed items D49 allows: membership, and nothing else. Every one is
* members-only. A disband is not here — it was not one of the four the org lead
* chose, and the Team it would be written to is about to be archived anyway.
*/
const ACTIVITY = Object.freeze({
'clan.created': 'rust.clan.founded',
'clan.member.added': 'rust.clan.joined',
'clan.member.left': 'rust.clan.left',
'clan.member.kicked': 'rust.clan.removed',
})
const CLAN_KINDS = Object.freeze(Object.keys(PUBLISH))
const STEAM_ID = /^\d{1,32}$/
const COLOR = /^#[0-9a-f]{6}$/i
/** The Team identity (D52). */
function externalIdOf(serverId, clanId, createdMs) {
return `${serverId}:${clanId}:${createdMs}`
}
const text = (value, max) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null)
const int = (value) => (Number.isInteger(Number(value)) && value !== null && value !== '' ? Number(value) : null)
/**
* One board row as this module stores it, or null when it cannot be read.
*
* A member whose Steam id is not a Steam id is dropped rather than failing the
* clan: the roster is still true about everybody else. A clan with no id, no
* creation time or no name fails as a whole, because it has no identity to
* store it under.
*/
function normaliseClan(serverId, raw) {
if (!raw || typeof raw !== 'object') return null
const clanId = int(raw.clanId)
const createdMs = int(raw.createdMs)
const name = text(raw.name, 191)
if (clanId == null || createdMs == null || createdMs <= 0 || !name) return null
const members = []
for (const m of Array.isArray(raw.members) ? raw.members : []) {
const steamId = m && typeof m.steamId === 'string' && STEAM_ID.test(m.steamId) ? m.steamId : null
if (!steamId) continue
members.push({
steamId,
name: text(m.name, 191),
rank: int(m.rank),
role: text(m.role, 64),
joinedMs: int(m.joinedMs),
})
}
return {
externalId: externalIdOf(serverId, clanId, createdMs),
serverId,
clanId,
createdMs,
name,
color: typeof raw.color === 'string' && COLOR.test(raw.color) ? raw.color.toLowerCase() : null,
score: int(raw.score) || 0,
maxMembers: int(raw.maxMembers),
memberCount: members.length,
members,
}
}
/** A member signature, so an unchanged roster is not rewritten every minute. */
const signature = (members) =>
members
.map((m) => `${m.steamId}|${m.rank == null ? '' : m.rank}|${m.role || ''}|${m.name || ''}`)
.sort()
.join('\n')
const leadersOf = (members) => new Set(members.filter((m) => Number(m.rank) === 1).map((m) => m.steamId))
/**
* Tells core something, and never lets core's answer become this module's
* problem. Both calls are fire-and-forget by contract; the catch is for a core
* that throws synchronously all the same.
*/
function publish(event) {
try {
Promise.resolve(core.teams.publish(event)).catch((err) => {
log.warn('teams publish failed', { kind: event.kind, externalId: event.externalId, error: err.message })
})
} catch (err) {
log.warn('teams publish threw', { kind: event.kind, externalId: event.externalId, error: err.message })
}
}
function requestReconcile(reason) {
try {
core.teams.reconcile({ reason })
} catch (err) {
log.warn('teams reconcile request threw', { reason, error: err.message })
}
}
function pushActivity(items) {
if (!items.length) return
try {
Promise.resolve(core.teams.pushActivity(items)).catch((err) => {
log.warn('teams activity push failed', { items: items.length, error: err.message })
})
} catch (err) {
log.warn('teams activity push threw', { items: items.length, error: err.message })
}
}
// ── The board ──────────────────────────────────────────────────────────────
/**
* Applies one server's `clans` board.
*
* `board` is undefined when the sidecar holds none — a plugin older than
* protocol 6, or one that has not connected since it was upgraded. That is
* recorded as unsupported, and the clans already stored are left exactly as they
* are: a missing board is the absence of an answer, not an answer of absence.
*
* Returns what happened, for the log and the tests.
*/
async function applyBoard(serverId, board) {
if (!board || typeof board !== 'object') {
await db.putBoard({
serverId,
boardT: null,
advanced: false,
enabled: true,
supported: false,
truncated: false,
backend: null,
reason: "this server has not sent a clan board; its plugin may predate protocol 6",
umodClans: false,
clanCount: 0,
})
return { applied: false, reason: 'no board' }
}
const previous = await db.getBoard(serverId)
const boardT = Number(board.t)
const known = previous && previous.boardT != null ? Number(previous.boardT) : null
const advanced = Number.isFinite(boardT) && (known == null || boardT > known)
const supported = board.supported === true
const raw = supported && Array.isArray(board.clans) ? board.clans : null
const clans = []
let unreadable = 0
for (const row of raw || []) {
const clan = normaliseClan(serverId, row)
if (clan) clans.push(clan)
else unreadable += 1
}
// A row this build could not read is treated like the ceiling: the board no
// longer vouches for what it leaves out.
const truncated = board.truncated === true || unreadable > 0
await db.putBoard({
serverId,
boardT: Number.isFinite(boardT) ? boardT : null,
advanced,
enabled: board.enabled !== false,
supported,
truncated,
backend: text(board.backend, 64),
reason: supported ? null : text(board.reason, 255) || 'the plugin could not read this server\'s clans',
umodClans: board.umodClans === true,
clanCount: clans.length,
})
if (unreadable) log.warn('clan board carried rows this build could not read', { server: serverId, unreadable })
// A board whose `t` has not moved is the one already applied. Re-applying it
// would rewrite every roster every 30 seconds to say what it already says.
if (!advanced || !raw) return { applied: false, reason: advanced ? 'unsupported' : 'unchanged' }
const [before, beforeMembers] = await Promise.all([
db.listClansForServer(serverId),
db.listMembersForServer(serverId),
])
const wasActive = new Map(before.filter((c) => !c.goneAt).map((c) => [c.externalId, c]))
const rosterBefore = new Map()
for (const m of beforeMembers) {
if (!rosterBefore.has(m.externalId)) rosterBefore.set(m.externalId, [])
rosterBefore.get(m.externalId).push(m)
}
let created = 0
let rosterChanged = 0
const leaderEvents = []
for (const clan of clans) {
// eslint-disable-next-line no-await-in-loop
await db.upsertClan(clan)
const old = rosterBefore.get(clan.externalId) || []
if (!wasActive.has(clan.externalId)) created += 1
if (signature(old) !== signature(clan.members)) {
// eslint-disable-next-line no-await-in-loop
await db.replaceMembers(clan.externalId, clan.members)
rosterChanged += 1
}
// Leadership is only ever learned here (D54): the game raises no hook when
// somebody is promoted. Published only for a clan that was already on the
// previous board — a brand-new clan's leaders reach core with the Team.
if (wasActive.has(clan.externalId)) {
const was = leadersOf(old)
const now = leadersOf(clan.members)
for (const key of now) if (!was.has(key)) leaderEvents.push({ kind: 'team.leader.added', externalId: clan.externalId, memberKey: key })
for (const key of was) if (!now.has(key)) leaderEvents.push({ kind: 'team.leader.removed', externalId: clan.externalId, memberKey: key })
}
}
// Only a complete board may say a clan is gone.
const onBoard = new Set(clans.map((c) => c.externalId))
const gone = truncated ? [] : [...wasActive.keys()].filter((id) => !onBoard.has(id))
await db.markGone(gone)
for (const event of leaderEvents) publish(event)
if (created || gone.length || rosterChanged) {
requestReconcile('rust clans board changed')
}
if (created || gone.length || rosterChanged || leaderEvents.length) {
log.info('clan board applied', {
server: serverId, clans: clans.length, created, gone: gone.length, rosterChanged,
leaderChanges: leaderEvents.length, truncated,
})
}
return { applied: true, clans: clans.length, created, gone: gone.length, rosterChanged, leaderChanges: leaderEvents.length }
}
// ── The events ─────────────────────────────────────────────────────────────
const nameOr = (name) => name || 'A player'
/** The feed line for one clan event, as core stores it verbatim. */
function summaryOf(kind, frame) {
switch (kind) {
case 'clan.created':
return `${nameOr(frame.name)} founded the clan.`
case 'clan.member.added':
return `${nameOr(frame.name)} joined the clan.`
case 'clan.member.left':
return `${nameOr(frame.name)} left the clan.`
case 'clan.member.kicked':
return frame.byName
? `${nameOr(frame.name)} was removed from the clan by ${frame.byName}.`
: `${nameOr(frame.name)} was removed from the clan.`
default:
return null
}
}
/**
* A key core can dedupe on, from the frame's own content.
*
* Content rather than this module's event row id, so that the same frame read
* twice — a cursor replayed after a crash, or the re-offer below — is the same
* item. **Hashed, because core clamps a dedupe key to 40 characters**, and a
* readable key long enough to be unique (server, clan, creation time, kind,
* player, instant) would be cut short into collisions without a word.
*/
function dedupeKeyOf(serverId, kind, frame) {
const parts = [serverId, frame.clanId, frame.createdMs, kind, frame.steamId || '', frame.t]
return crypto.createHash('sha1').update(parts.join('|')).digest('hex')
}
/** One clan event as a Team feed item, or null when D49 does not allow it. */
function activityItem(serverId, externalId, kind, frame) {
const itemKind = ACTIVITY[kind]
const summary = itemKind && summaryOf(kind, frame)
if (!summary) return null
const t = Number(frame.t)
return {
externalId,
kind: itemKind,
summary,
occurredAt: Number.isFinite(t) ? t : Date.now(),
visibility: 'members',
actorMemberKey: kind === 'clan.member.kicked' ? frame.bySteamId || null : frame.steamId || null,
payload: { serverId, steamId: frame.steamId || null },
dedupeKey: dedupeKeyOf(serverId, kind, frame),
}
}
/** The Team identity a clan event names, or null when it cannot be worked out. */
async function resolveExternalId(serverId, frame) {
const clanId = int(frame.clanId)
const createdMs = int(frame.createdMs)
if (clanId == null) return null
if (createdMs != null && createdMs > 0) return externalIdOf(serverId, clanId, createdMs)
// `clan.member.added` can arrive without a creation time when the plugin could
// not read the clan back. Matched on the game id, newest first.
const known = await db.findByGameId(serverId, clanId)
return known ? known.externalId : null
}
/**
* Applies one `clan.*` event: tells core, and writes the Team feed.
*
* Called from ingest, after the raw frame is stored. The board that follows
* every one of these (the plugin re-sends it a few seconds later) is what the
* store is rebuilt from; this only makes the change visible sooner and records
* the line for the feed.
*/
async function applyEvent(serverId, frame) {
const kind = frame && frame.kind
if (!PUBLISH[kind]) return { applied: false }
if (frame.steamId) await db.rememberName(frame.steamId, text(frame.name, 191))
if (frame.bySteamId) await db.rememberName(frame.bySteamId, text(frame.byName, 191))
const externalId = await resolveExternalId(serverId, frame)
if (!externalId) {
log.info('clan event names a clan this module has never seen', { server: serverId, kind, clanId: frame.clanId })
return { applied: false }
}
// The game said it: this clan is gone. Recorded here as well as by the next
// board, because a board truncated at the ceiling would never say so.
if (kind === 'clan.disbanded') await db.markGone([externalId])
const event = { kind: PUBLISH[kind], externalId }
if (event.kind.startsWith('team.member.')) {
if (!frame.steamId) return { applied: false }
event.memberKey = String(frame.steamId)
}
publish(event)
const item = activityItem(serverId, externalId, kind, frame)
if (item) pushActivity([item])
return { applied: true, externalId }
}
/**
* Offers the last few minutes of one server's clan feed items to core again.
*
* See `REOFFER_MS`. Called after each board refresh; idempotent by construction.
*/
async function reofferActivity(serverId, now = Date.now()) {
const rows = await db.recentClanEvents(serverId, now - REOFFER_MS)
const items = []
for (const row of rows) {
let frame
try {
frame = typeof row.raw === 'string' ? JSON.parse(row.raw) : row.raw
} catch (err) {
continue
}
if (!frame || !ACTIVITY[frame.kind]) continue
// eslint-disable-next-line no-await-in-loop
const externalId = await resolveExternalId(serverId, frame)
const item = externalId && activityItem(serverId, externalId, frame.kind, frame)
if (item) items.push(item)
}
pushActivity(items)
return items.length
}
// ── Who may see a roster (D48) ─────────────────────────────────────────────
/**
* May this viewer see this clan's roster?
*
* `viewer` is `{ userId, role }` or null — the shape core hands `projectRoster`,
* so core's roster and this module's page decide it with one function.
*
* The viewer's standing is re-read from the `users` row, never taken from what
* the caller says, for the same reason the presence gate does it: a moderator
* demoted this morning, or an account banned, must lose the roster on the next
* request. Everything that cannot be answered answers no.
*/
async function canSeeRoster(viewer, externalId) {
const audience = await visibility.clanRosterAudience()
if (audience === 'public') return true
if (!viewer || viewer.userId == null) return false
const user = await core.users.getById(viewer.userId)
if (!user || (user.status && user.status !== 'active')) return false
if (audience === 'signed_in') return true
if (user.role === 'admin' || user.role === 'moderator') return true
return db.userIsMember(externalId, user.id)
}
// ── The public reads ───────────────────────────────────────────────────────
const shapeBoard = (board, now = Date.now()) => {
if (!board || board.supported == null) {
return { supported: false, fresh: false, truncated: false, enabled: true, reason: 'this server has not sent a clan board yet' }
}
const seenAt = board.seenAt ? new Date(board.seenAt).getTime() : null
return {
supported: Boolean(board.supported),
enabled: Boolean(board.enabled),
truncated: Boolean(board.truncated),
fresh: Boolean(board.supported) && seenAt != null && now - seenAt < FRESH_MS,
reason: board.reason || null,
}
}
/** The Clans tab (D58): every clan on one server's board, best first. Public. */
async function listForServer(serverId, now = Date.now()) {
const [clans, board] = await Promise.all([db.listPublicForServer(serverId), db.getBoard(serverId)])
return {
clans: clans.map((c) => ({
externalId: c.externalId,
name: c.name,
color: c.color || null,
score: Number(c.score) || 0,
memberCount: Number(c.memberCount) || 0,
maxMembers: c.maxMembers == null ? null : Number(c.maxMembers),
})),
board: shapeBoard(board, now),
}
}
/**
* One clan, and its roster if the viewer may see it.
*
* The roster carries no Steam id and no website account id — the same two fields
* core withholds from every public roster. `online` is inside the audience by
* construction (D48): a viewer who may not see the roster sees no names at all.
*/
async function getForViewer(externalId, viewer) {
const clan = await db.findClan(externalId)
if (!clan) return null
const allowed = await canSeeRoster(viewer, externalId)
const audience = await visibility.clanRosterAudience()
const members = allowed && !clan.goneAt ? await db.listMembers(externalId) : []
return {
clan: {
externalId: clan.externalId,
name: clan.name,
color: clan.color || null,
score: Number(clan.score) || 0,
memberCount: Number(clan.memberCount) || 0,
maxMembers: clan.maxMembers == null ? null : Number(clan.maxMembers),
serverId: clan.serverId,
serverName: clan.serverName,
founded: Number(clan.createdMs) || null,
gone: Boolean(clan.goneAt),
},
roster: {
visible: allowed,
audience,
members: members.map((m) => ({
name: m.name || null,
role: m.role || null,
leader: Number(m.rank) === 1,
online: Boolean(Number(m.online)),
joined: m.joinedMs == null ? null : Number(m.joinedMs),
})),
},
}
}
/**
* Every configured server's clan board as the admin page shows it: whether it is
* current, whether it is at the ceiling (D55), why it cannot be read, and
* whether the uMod Clans plugin is loaded there (D47) — whose clans are a
* separate system and never Teams.
*/
async function boardsForAdmin(now = Date.now()) {
const rows = await db.listBoards()
return rows.map((row) => ({
id: row.serverId,
name: row.serverName,
...shapeBoard(row.supported == null ? null : row, now),
clans: Number(row.clanCount) || 0,
umodClans: Boolean(row.umodClans),
}))
}
module.exports = {
FRESH_MS,
boardsForAdmin,
REOFFER_MS,
CLAN_KINDS,
externalIdOf,
normaliseClan,
applyBoard,
applyEvent,
resolveExternalId,
reofferActivity,
activityItem,
dedupeKeyOf,
canSeeRoster,
shapeBoard,
listForServer,
getForViewer,
}

View File

@@ -0,0 +1,202 @@
// ── module-rust's Team provider ────────────────────────────────────────────
//
// The questions core asks this module about Teams (MODULE_API.md
// `api.registerTeamProvider`, TEAMS.md §2.3). A first-party Rust clan is a Team
// (R5); this file is the whole of the translation, and `model/clans` is where
// the clans themselves are kept.
//
// ── The envelope is the contract ──────────────────────────────────────────
//
// Every method answers `{ ok, ... }` and `{ ok: false, reason }` is an ordinary
// answer. Core reads it as "keep what you have" — staleness, never emptiness —
// and there is no shape a failure can take that core reads as "zero Teams". An
// empty array is the one thing this file must never say while it does not know.
//
// ── Many servers, one answer (D53) ─────────────────────────────────────────
//
// `module-uo` has one shard and one socket, so "is the board current" has one
// answer. This module has a fleet, and the answer is per server. `getTeams` is
// therefore:
//
// • `complete: true` only when EVERY configured server's board is fresh,
// supported and untruncated — then core may archive a
// Team that is missing;
// • `complete: false` when at least one is current and some are not — core
// adds and updates, and removes nothing. One server being
// off for a patch must never archive its clans;
// • a refusal when none is current.
//
// A clan is only ever as current as its own server's board, so the roster
// methods ask about that server alone.
const core = require('../../core')
const db = require('./clans.db')
const clans = require('./clans.model')
const servers = require('../servers/servers.model')
const log = core.logger('teams')
const refuse = (reason) => ({ ok: false, reason })
/** Is this board record current? The rule `model/clans` states, applied to one row. */
function isFresh(board, now = Date.now()) {
return clans.shapeBoard(board, now).fresh
}
/**
* `getTeams()` — every clan on every server's board.
*
* `meta` carries the server and the clan's colour and score, opaquely: core
* stores and shows it and never branches on it.
*/
async function getTeams(now = Date.now()) {
try {
const configured = await servers.listForPolling()
if (!configured.length) return refuse('no Rust servers are configured')
const boards = await db.listBoards()
const byServer = new Map(boards.map((b) => [b.serverId, b]))
const fresh = []
const behind = []
for (const server of configured) {
const board = byServer.get(server.id)
if (isFresh(board, now)) fresh.push(server.id)
else behind.push(server.id)
}
if (!fresh.length) {
return refuse(`no server has sent a current clan board (${behind.join(', ')})`)
}
// Complete only when nothing is behind, and nothing is at the ceiling. A
// server that is configured but switched off in this module is "behind" by
// construction — its board is never read — which is the conservative answer:
// switching a server off is not a statement that its clans are gone.
const truncated = fresh.filter((id) => byServer.get(id).truncated)
const complete = behind.length === 0 && truncated.length === 0
const rows = await db.listActiveClans()
const known = new Set(configured.map((s) => s.id))
return {
ok: true,
complete,
teams: rows
.filter((row) => known.has(row.serverId))
.map((row) => ({
externalId: row.externalId,
name: row.name,
abbr: null,
meta: {
server: row.serverName || row.serverId,
serverId: row.serverId,
color: row.color || null,
score: Number(row.score) || 0,
},
})),
}
} catch (err) {
log.warn('getTeams failed', { error: err.message })
return refuse(`clans unreadable: ${err.message}`)
}
}
/** A clan and whether its server's board vouches for it right now, or a refusal. */
async function currentClan(externalId, now) {
const clan = await db.findClan(externalId)
if (!clan) return { refusal: refuse(`clan ${externalId} is not on any board`) }
if (clan.goneAt) return { refusal: refuse(`clan ${externalId} has left its server's board`) }
const board = await db.getBoard(clan.serverId)
if (!isFresh(board, now)) {
return { refusal: refuse(`server ${clan.serverId} has not sent a current clan board`) }
}
return { clan }
}
/**
* `getTeamMembers(externalId)` — one clan's roster.
*
* **A clan with no roster rows is refused, not reported empty**, unless the board
* said it has none. A clan always has at least its leader, so an empty roster
* beside a non-zero count is a read that happened between two writes, and
* reporting it would tell core every member left.
*/
async function getTeamMembers(externalId, now = Date.now()) {
try {
const { clan, refusal } = await currentClan(externalId, now)
if (refusal) return refusal
const rows = await db.listMembers(externalId)
if (!rows.length && Number(clan.memberCount) > 0) {
return refuse(`roster for clan ${externalId} is not stored yet (board says ${clan.memberCount} members)`)
}
return {
ok: true,
complete: true,
members: rows.map((row) => ({
memberKey: row.steamId,
displayName: row.name || null,
rankLabel: row.role || null,
// Rank 1 is leader and several may hold it. A NULL rank — a role id the
// board could not match — is not a leader: "not known" must never read
// as "leads this clan".
leader: Number(row.rank) === 1,
online: Boolean(Number(row.online)),
userId: Number.isInteger(Number(row.userId)) && Number(row.userId) > 0 ? Number(row.userId) : null,
})),
}
} catch (err) {
log.warn('getTeamMembers failed', { externalId, error: err.message })
return refuse(`roster unreadable: ${err.message}`)
}
}
/** `getTeamLeaders(externalId)` — everyone at rank 1, which may be several. */
async function getTeamLeaders(externalId, now = Date.now()) {
try {
const { refusal } = await currentClan(externalId, now)
if (refusal) return refusal
const rows = await db.listMembers(externalId)
return { ok: true, leaders: rows.filter((row) => Number(row.rank) === 1).map((row) => row.steamId) }
} catch (err) {
log.warn('getTeamLeaders failed', { externalId, error: err.message })
return refuse(`leadership unreadable: ${err.message}`)
}
}
/**
* Which roster rows a viewer may see (D48, MODULE_API 1.6.0).
*
* The one provider method core calls on a REQUEST path, and the one that fails
* CLOSED: core serves an empty roster when this refuses, because for a
* visibility question "keep what you have" would mean publishing the roster to
* whoever asked. So every path that cannot reach a confident answer refuses.
*
* All or nothing, and that is the model rather than a shortcut: the audience is
* a property of the ROSTER, not of a member. There is no setting in which some
* of a clan's members are visible and others are not.
*/
async function projectRoster(externalId, members, viewer) {
try {
const allowed = await clans.canSeeRoster(viewer, externalId)
if (!allowed) return { ok: true, members: [] }
return { ok: true, members: (members || []).map((m) => m.member_key).filter(Boolean) }
} catch (err) {
log.warn('projectRoster could not resolve the audience; withholding the roster', {
externalId, error: err.message,
})
return refuse(`the roster audience could not be resolved: ${err.message}`)
}
}
// Where core should point a link at a clan (MODULE_API 1.6.0, TEAMS.md §6.4).
// Core substitutes `{externalId}` and nothing else, which is why the page is not
// nested under its server (D56): the server is inside the id already.
const pageUrlTemplate = '/rust/clans/{externalId}'
module.exports = { getTeams, getTeamMembers, getTeamLeaders, projectRoster, pageUrlTemplate, isFresh }

View File

@@ -0,0 +1,145 @@
// ── The SQL half of the configuration audit ───────────────────────────────
//
// One table, two questions: record what a save did, and show an operator what
// has been done to a server lately.
//
// Nothing here talks to a game. The game half is `sidecarClient`, and the two
// are deliberately not mixed: this file is what remains true after the plugin
// has been reloaded, rolled back, or lost.
const core = require('../../core')
/**
* Records one save attempt — including the ones that never reached a file.
*
* A refusal is written for the same reason a success is: an operator asking why
* a setting is not what they set has to be able to see that somebody tried and
* was told no, and a table that only holds successes answers that question with
* silence.
*/
async function recordWrite(row) {
const result = await core.query(
`INSERT INTO rust_config_writes
(server_id, path, plugin, reload_target, tier, user_id, outcome, reloaded,
changes, version_before, version_after, detail, write_id, settle_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? SECOND))`,
[
row.serverId,
row.path,
row.plugin || null,
row.reloadTarget || null,
row.tier || 'form',
row.userId || null,
row.outcome,
row.reloaded ? 1 : 0,
row.changes ? JSON.stringify(row.changes) : null,
row.versionBefore || null,
row.versionAfter || null,
row.detail ? String(row.detail).slice(0, 500) : null,
row.writeId || null,
// Seconds from now, on the database's clock — the one `lost` is read against.
// NULL for a write nothing is waiting on, and DATE_ADD of NULL is NULL.
row.settleSeconds != null ? Number(row.settleSeconds) : null,
],
)
return result && result.insertId != null ? Number(result.insertId) : null
}
/**
* Settles a `reloading` write from the plugin's `config.outcome` (protocol 13).
*
* Found by the plugin's `writeId`, scoped to the server that sent it — a write
* id is only unique within one plugin. Only a row still `reloading` moves, so a
* replayed frame settles nothing twice. A row whose `settle_by` has passed is
* still `reloading` in the table (it reads as `lost`), so a late outcome still
* lands. Returns whether a row moved.
*/
async function settleWrite(serverId, outcome) {
const result = await core.query(
`UPDATE rust_config_writes
SET outcome = ?, reloaded = ?, restored = ?, version_after = ?, detail = ?,
log_tail = ?, settled_at = NOW()
WHERE server_id = ? AND write_id = ? AND outcome = 'reloading'`,
[
outcome.outcome,
outcome.reloaded ? 1 : 0,
outcome.restored == null ? null : outcome.restored ? 1 : 0,
outcome.versionAfter || null,
outcome.detail ? String(outcome.detail).slice(0, 500) : null,
outcome.log || null,
serverId,
outcome.writeId,
],
)
return Number((result && result.affectedRows) || 0) > 0
}
/** One write, by its row id, for the page that is waiting on it. */
async function getWrite(serverId, id) {
const rows = await core.query(
`${SELECT_WRITE}
WHERE server_id = ? AND id = ?`,
[serverId, id],
)
return rows[0] ? shapeWrite(rows[0]) : null
}
/**
* The recent history for one server, newest first.
*
* `changes` comes back parsed, and a row whose JSON will not parse comes back
* with `null` rather than throwing — a corrupt audit row must not be able to
* break the page that displays the rest of them.
*/
async function recentWrites(serverId, limit = 50) {
const rows = await core.query(
`${SELECT_WRITE}
WHERE server_id = ?
ORDER BY id DESC
LIMIT ?`,
[serverId, Math.max(1, Math.min(Number(limit) || 50, 200))],
)
return rows.map(shapeWrite)
}
// `lost` is decided by the database's clock, in the same statement that reads
// the row, so it cannot disagree with `settle_by`, which that clock also wrote.
const SELECT_WRITE = `SELECT id, server_id AS serverId, path, plugin, reload_target AS reloadTarget, tier,
user_id AS userId, outcome, reloaded, restored, changes,
version_before AS versionBefore, version_after AS versionAfter, detail,
log_tail AS log, write_id AS writeId, settled_at AS settledAt, created_at AS createdAt,
(outcome = 'reloading' AND settle_by IS NOT NULL AND settle_by < NOW()) AS lost
FROM rust_config_writes`
/**
* A row as the page reads it. A write still `reloading` past its `settle_by`
* reads as `lost`: the plugin was reloaded or the link dropped before it could
* say, and the files are whatever a re-read shows.
*/
function shapeWrite(row) {
const { lost, ...rest } = row
return {
...rest,
outcome: Number(lost) ? 'lost' : row.outcome,
reloaded: Boolean(row.reloaded),
restored: row.restored == null ? null : Boolean(row.restored),
changes: parseChanges(row.changes),
}
}
function parseChanges(raw) {
if (!raw) return null
try {
return JSON.parse(raw)
} catch {
return null
}
}
module.exports = { recordWrite, settleWrite, getWrite, recentWrites, parseChanges, shapeWrite }

View File

@@ -0,0 +1,279 @@
// ── The logic half of configuration-from-the-site ─────────────────────────
//
// Everything here is about the difference between what a game host reports and
// what an admin should be shown. Three jobs:
//
// 1. **Group a flat file list by plugin**, because one plugin can own several
// files and a form that lists 40 paths is not a settings screen.
// 2. **Say which file is ours, and which keys inside it are locked** (D38). The
// plugin names itself in the catalogue rather than us matching a filename,
// so renaming the file cannot quietly unlock the three keys that would cut
// the link or split a server's history.
// 3. **Decide nothing about paths.** The only process that can say whether a
// path resolves inside a configuration directory is the one holding the
// directory. This file checks SHAPE, so an obviously malformed request is
// refused before it costs a round trip — never as a substitute for the real
// check on the host.
const configEdit = require('../../configEdit')
/**
* Keys in the bridge plugin's own config that the website may not change (D38).
*
* `Host` and `Port` are the link this edit is travelling over, and `ServerId` is
* how every row this module has ever stored is keyed — changing it does not
* rename a server, it strands its history and starts a new one under a name
* nobody chose deliberately. All three are editable on the host, by a person
* who is standing on it.
*/
const LOCKED_KEYS = ['Host', 'Port', 'ServerId']
/** What a locked field says for itself, on the screen and in a refusal. */
const LOCKED_REASON = {
host: 'the website reaches this server through this address',
port: 'the website reaches this server through this port',
serverid: 'every row this site holds for this server is keyed to this id',
}
/**
* A path shaped like something the host could plausibly have listed.
*
* Deliberately narrow and deliberately **not** the security boundary: no `..`,
* nothing absolute, no drive letter, forward slashes, and it ends in `.json`.
*/
const PATH_SHAPE = /^(?!.*\.\.)(?!\/)[A-Za-z0-9 _.\-()[\]]+(?:\/[A-Za-z0-9 _.\-()[\]]+)*\.json$/
function isPlausiblePath(path) {
return typeof path === 'string' && path.length > 0 && path.length <= 255 && PATH_SHAPE.test(path)
}
/**
* Shapes the plugin's catalogue into the screen's shape: plugins, each with its
* files, each file saying whether it can be edited and why not.
*
* A file whose guessed plugin is not loaded is kept and **marked**, not dropped.
* An operator whose config for an unloaded plugin vanished from the page would
* conclude the bridge cannot see it, which is a different and much more alarming
* problem than the true one.
*/
function shapeCatalogue(catalogue) {
if (!catalogue || typeof catalogue !== 'object') return null
const loaded = Array.isArray(catalogue.plugins) ? catalogue.plugins : []
const byName = new Map(loaded.map((p) => [String(p.name).toLowerCase(), p]))
const self = catalogue.self ? String(catalogue.self) : null
const groups = new Map()
for (const file of Array.isArray(catalogue.files) ? catalogue.files : []) {
const plugin = String(file.plugin || 'unknown')
const key = plugin.toLowerCase()
if (!groups.has(key)) {
const match = byName.get(key)
groups.set(key, {
plugin,
loaded: Boolean(match),
title: match ? match.title : null,
version: match ? match.version : null,
// The bridge plugin cannot reload itself — the reload would close the
// link carrying the answer — so the screen says so up front rather than
// offering a button that always refuses.
isBridge: self != null && plugin.toLowerCase() === self.toLowerCase(),
files: [],
})
}
groups.get(key).files.push({
path: String(file.path),
bytes: Number(file.bytes) || 0,
modified: file.modified ? Number(file.modified) : null,
editable: file.editable !== false,
...(file.reason ? { reason: String(file.reason) } : {}),
})
}
return {
root: catalogue.root ? String(catalogue.root) : null,
self,
truncated: Boolean(catalogue.truncated),
limits: catalogue.limits || null,
plugins: [...groups.values()].sort((a, b) => a.plugin.localeCompare(b.plugin)),
loaded: loaded
.map((p) => ({ name: String(p.name), title: p.title || null, version: p.version || null }))
.sort((a, b) => a.name.localeCompare(b.name)),
}
}
/** Whether this file is the bridge's own config, by the name the plugin gave. */
function isBridgeConfig(path, self) {
if (!self) return false
const plugin = String(path).includes('/') ? String(path).split('/')[0] : String(path).replace(/\.json$/i, '')
return plugin.toLowerCase() === String(self).toLowerCase()
}
/** The locked keys for a file: three of them in our own config, none anywhere else. */
function lockedKeysFor(path, self) {
return isBridgeConfig(path, self) ? LOCKED_KEYS : []
}
/**
* Turns one file the host sent into what the form renders.
*
* The text is passed through untouched. What is added is the READING of it: the
* field list, which fields are locked, and which hold something a browser should
* mask by default.
*/
function shapeFile(file, { self = null, maxDepth = 6 } = {}) {
if (!file || typeof file.text !== 'string') return null
const locked = lockedKeysFor(file.path, self)
let fields = null
let parseError = null
try {
fields = configEdit.describe(configEdit.scan(file.text), { maxDepth, locked })
} catch (err) {
// A config already broken on disk still opens — in the raw tier, which is
// the only thing that can fix it. A page that refused to show a broken file
// would send somebody to SSH for the one job this feature exists to do.
parseError = err.message
}
return {
path: String(file.path),
plugin: file.plugin ? String(file.plugin) : null,
version: String(file.version),
bytes: Number(file.bytes) || 0,
modified: file.modified ? Number(file.modified) : null,
text: file.text,
fields,
parseError,
locked: locked.map((key) => ({ key, reason: LOCKED_REASON[key.toLowerCase()] || null })),
isBridge: isBridgeConfig(file.path, self),
}
}
/**
* Which locked keys differ between two versions of a document.
*
* The form refuses a locked field by pointer, but the **raw tier submits a whole
* document**, and a document can change `Port` without anything resembling an
* edit to a field. So the raw tier is checked the only way it can be: by
* comparing the literals before and after.
*
* A file that will not parse is not a way around this — an unparseable document
* is refused before it gets here.
*/
function lockedChanges(before, after, locked) {
if (!locked || locked.length === 0) return []
let a
let b
try {
a = configEdit.scan(before)
b = configEdit.scan(after)
} catch {
// Nothing can be compared, so nothing is cleared. The caller refuses.
return locked.slice()
}
const literal = (root, key) => {
if (root.type !== 'object') return null
const node = root.children.find((c) => String(c.key).toLowerCase() === key.toLowerCase())
return node ? JSON.stringify(node.value) + ':' + (node.raw || '') : null
}
return locked.filter((key) => literal(a, key) !== literal(b, key))
}
/** Every change a report says landed, as one line per file. */
function summariseReport(report) {
if (!report || typeof report !== 'object') return null
const files = Array.isArray(report.files) ? report.files : []
return {
ok: report.ok !== false,
reloaded: Boolean(report.reloaded),
rolledBack: Boolean(report.rolledBack),
// Protocol 13: the files are written and the reload has not finished. The
// outcome follows as a `config.outcome` frame naming `writeId`.
pending: Boolean(report.pending),
writeId: report.writeId ? String(report.writeId) : null,
ceilingMs: Number(report.ceilingMs) > 0 ? Number(report.ceilingMs) : null,
restored: typeof report.restored === 'boolean' ? report.restored : null,
reason: report.reason ? String(report.reason) : null,
// The plugin only reads this on the failure path, and it is the difference
// between "your change was undone" and "your change was undone BECAUSE line
// 14 is not valid for that field".
log: report.log ? String(report.log).slice(-4000) : null,
files: files.map((f) => ({
path: String(f.path),
version: f.version ? String(f.version) : null,
bytes: f.bytes != null ? Number(f.bytes) : null,
// Both frameworks merge missing defaults on load and save the file back,
// so the file after a successful reload is regularly not the file we
// wrote. Saying so keeps an operator from reading it as our bug.
rewritten: Boolean(f.rewritten),
})),
}
}
/**
* How long a pending write may go unanswered before it is lost, in seconds.
*
* The plugin waits at most one ceiling for the edit's reload and one more for a
* restore's; ingest reads the feed every few seconds on top. Past both, with a
* margin, nothing is coming — the plugin was reloaded or the link dropped — and
* the page says so instead of spinning. A plugin that sent no ceiling gets the
* one protocol 13 shipped with.
*/
const SETTLE_SLACK_SECONDS = 20
const DEFAULT_CEILING_MS = 30 * 1000
function settleSeconds(ceilingMs) {
const ceiling = Number(ceilingMs) > 0 ? Number(ceilingMs) : DEFAULT_CEILING_MS
return Math.ceil((2 * ceiling) / 1000) + SETTLE_SLACK_SECONDS
}
/**
* A `config.outcome` frame as the row it settles, or null when it names no write.
*
* `applied` covers every case where the edit is on disk — reloaded, or standing
* because the framework never reloaded it (the reason says which). A rollback is
* `rolled-back` whether or not the plugin came back on the old file; `restored`
* says which, and it is the difference between "try again" and "go and look".
*/
function outcomeOf(frame) {
if (!frame || typeof frame !== 'object' || !frame.writeId) return null
const report = summariseReport(frame)
const first = report.files[0]
return {
writeId: String(frame.writeId),
outcome: report.rolledBack ? 'rolled-back' : 'applied',
reloaded: report.reloaded,
restored: report.rolledBack ? report.restored : null,
versionAfter: first ? first.version : null,
detail: report.reason,
log: report.log,
}
}
module.exports = {
LOCKED_KEYS,
LOCKED_REASON,
PATH_SHAPE,
isPlausiblePath,
shapeCatalogue,
shapeFile,
isBridgeConfig,
lockedKeysFor,
lockedChanges,
summariseReport,
outcomeOf,
settleSeconds,
}

View File

@@ -0,0 +1,397 @@
// ── SQL for the read path ─────────────────────────────────────────────────
//
// Writes come from one caller (`server/ingest.js`) and reads from the routers.
// They live together because they are the same tables and the invariants are
// easier to keep true when the UPDATE and the SELECT are on the same screen.
//
// Raw parameterised SQL through `core.query`, no ORM. Placeholders always —
// except for one place where a list of kinds is expanded into placeholders, and
// that expansion is checked in `events.model.js` before it ever reaches here.
const core = require('../../core')
const EVENTS = 'rust_events'
const STATS = 'rust_player_wipe_stats'
const GATHER = 'rust_gather_totals'
const WEAPONS = 'rust_weapon_kills'
const PLAYERS = 'rust_players'
const WIPES = 'rust_wipes'
const PRESENCE = 'rust_presence'
const CURSOR = 'rust_ingest_cursor'
// ── The cursor ────────────────────────────────────────────────────────────
async function getCursor(serverId) {
const rows = await core.query(
`SELECT server_id AS serverId, last_event_id AS lastEventId, events_seen AS eventsSeen
FROM ${CURSOR} WHERE server_id = ?`,
[serverId],
)
return rows[0] || null
}
/**
* Moves a server's cursor forward, counting what it passed.
*
* **Called only after the batch it describes has been written.** The whole
* correctness of the ingest is in that ordering: if this ran first, a crash
* between the two would skip events for ever, silently, with no way to notice.
* Running it last means a crash re-reads events it has already counted at worst
* — see `ingest.js` for what makes that survivable.
*/
async function setCursor(serverId, lastEventId, seen = 0) {
await core.query(
`INSERT INTO ${CURSOR} (server_id, last_event_id, events_seen, updated_at)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
last_event_id = VALUES(last_event_id),
events_seen = events_seen + VALUES(events_seen),
updated_at = CURRENT_TIMESTAMP`,
[serverId, lastEventId, seen],
)
}
// ── Writes ────────────────────────────────────────────────────────────────
async function insertEvent({ serverId, wipeId, kind, t, steamId, raw }) {
await core.query(
`INSERT INTO ${EVENTS} (server_id, wipe_id, kind, t, steam_id, raw)
VALUES (?, ?, ?, ?, ?, ?)`,
[serverId, wipeId || null, kind, t, steamId || null, JSON.stringify(raw)],
)
}
/**
* Notes that a wipe exists, from any frame that mentions it.
*
* There is no "a wipe started" call, because the website is not there when one
* does — a wipe happens to a game server that was restarted while nobody was
* watching. A wipe is therefore created by being mentioned, and `last_seen`
* moves every time it is mentioned again.
*/
async function touchWipe(serverId, wipeId, saveCreatedAt = null) {
if (!wipeId) return
await core.query(
`INSERT INTO ${WIPES} (server_id, wipe_id, save_created_at, first_seen, last_seen)
VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
last_seen = CURRENT_TIMESTAMP,
save_created_at = COALESCE(VALUES(save_created_at), save_created_at)`,
[serverId, wipeId, saveCreatedAt],
)
}
/**
* Notes that a player exists and what they were last called.
*
* `name` is COALESCEd rather than overwritten so that a frame which carries no
* name — a ban by id, a tally — cannot blank out the name every other frame
* supplied.
*/
async function touchPlayer(steamId, name = null) {
if (!steamId) return
await core.query(
`INSERT INTO ${PLAYERS} (steam_id, name, first_seen, last_seen)
VALUES (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
name = COALESCE(VALUES(name), name),
last_seen = CURRENT_TIMESTAMP`,
[steamId, name],
)
}
/**
* Adds to one player's counters for one wipe.
*
* Every column is a running total that only rises within a wipe, so this is an
* upsert that ADDS rather than sets. `deltas` names only what moved; a `+ 0` on
* everything else is what keeps the caller from having to read the row first.
*/
async function addStats({ serverId, wipeId, steamId }, deltas = {}) {
if (!serverId || !steamId) return
const cols = ['kills', 'deaths', 'suicides', 'npc_kills', 'structures', 'sessions', 'playtime_sec']
const values = {
kills: deltas.kills || 0,
deaths: deltas.deaths || 0,
suicides: deltas.suicides || 0,
npc_kills: deltas.npcKills || 0,
structures: deltas.structures || 0,
sessions: deltas.sessions || 0,
playtime_sec: deltas.playtimeSec || 0,
}
await core.query(
`INSERT INTO ${STATS} (server_id, wipe_id, steam_id, ${cols.join(', ')}, last_seen)
VALUES (?, ?, ?, ${cols.map(() => '?').join(', ')}, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
${cols.map((c) => `${c} = ${c} + VALUES(${c})`).join(',\n ')},
last_seen = CURRENT_TIMESTAMP`,
[serverId, wipeId || '', steamId, ...cols.map((c) => values[c])],
)
}
/**
* The tally's counts for the chat-title conditions (PLAN_REDESIGNS §5.1): the
* wire field each is, and the column it adds to. All sums.
*/
const TITLE_SUMS = {
animalKills: 'animal_kills',
headshots: 'headshots',
apcKills: 'apc_kills',
heliKills: 'heli_kills',
built: 'built',
repaired: 'repaired',
healed: 'healed',
rockets: 'rockets',
explosives: 'explosives',
missions: 'missions',
}
/** The two *best* fields and their columns: the longest single kill, never a sum. */
const TITLE_BESTS = { bestPvpM: 'best_pvp_m', bestPveM: 'best_pve_m' }
/** Item categories the plugin sends under `crafted`, and the column each counts in. */
const CRAFTED = { attire: 'crafted_attire', weapon: 'crafted_weapons' }
/**
* Adds one tally's title counts to the player's row for the wipe. A sum adds;
* a best is GREATEST of the stored and the sent, because a tally carries its
* interval's maximum and two maxima added are not a distance. Nothing is
* written when the tally carried none of them, so an older plugin's frame
* costs no statement.
*/
async function addTitleStats({ serverId, wipeId, steamId }, frame = {}) {
if (!serverId || !steamId) return
const sums = {}
for (const [field, col] of Object.entries(TITLE_SUMS)) sums[col] = Math.max(0, Math.floor(Number(frame[field]) || 0))
const crafted = frame.crafted && typeof frame.crafted === 'object' ? frame.crafted : {}
for (const [category, col] of Object.entries(CRAFTED)) sums[col] = Math.max(0, Math.floor(Number(crafted[category]) || 0))
const bests = {}
for (const [field, col] of Object.entries(TITLE_BESTS)) {
const m = Number(frame[field])
bests[col] = Number.isFinite(m) && m > 0 ? Math.min(Math.round(m * 10) / 10, 999999.9) : 0
}
if (![...Object.values(sums), ...Object.values(bests)].some((v) => v > 0)) return
const cols = [...Object.keys(sums), ...Object.keys(bests)]
await core.query(
`INSERT INTO ${STATS} (server_id, wipe_id, steam_id, ${cols.join(', ')}, last_seen)
VALUES (?, ?, ?, ${cols.map(() => '?').join(', ')}, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
${Object.keys(sums).map((c) => `${c} = ${c} + VALUES(${c})`).join(',\n ')},
${Object.keys(bests).map((c) => `${c} = GREATEST(${c}, VALUES(${c}))`).join(',\n ')},
last_seen = CURRENT_TIMESTAMP`,
[serverId, wipeId || '', steamId, ...Object.values(sums), ...Object.values(bests)],
)
}
/** One weapon's credited kills (§5.3), added as a delta like a gathered resource. */
async function addWeaponKills({ serverId, wipeId, steamId }, weapon, kills) {
if (!serverId || !steamId || !weapon || !(kills > 0)) return
await core.query(
`INSERT INTO ${WEAPONS} (server_id, wipe_id, steam_id, weapon, kills)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE kills = kills + VALUES(kills)`,
[serverId, wipeId || '', steamId, String(weapon).slice(0, 64), kills],
)
}
async function addGathered({ serverId, wipeId, steamId }, resource, amount) {
if (!serverId || !steamId || !resource || !(amount > 0)) return
await core.query(
`INSERT INTO ${GATHER} (server_id, wipe_id, steam_id, resource, amount)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE amount = amount + VALUES(amount)`,
[serverId, wipeId || '', steamId, resource, amount],
)
}
/**
* Replaces a server's presence rows with exactly what the board said.
*
* Two statements, delete then insert, because a board is a REPLACEMENT: a player
* who left between two boards has to disappear, and an upsert alone would leave
* them online for ever. It is not wrapped in a transaction on purpose — the
* window between the two is a fraction of a second of a page possibly showing an
* empty player list, against holding a lock on a table two routes read.
*/
async function replacePresence(serverId, players = []) {
await core.query(`DELETE FROM ${PRESENCE} WHERE server_id = ?`, [serverId])
for (const p of players) {
if (!p || !p.steamId) continue
await core.query(
`INSERT INTO ${PRESENCE} (server_id, steam_id, name, sleeping, connected_at, updated_at)
VALUES (?, ?, ?, ?, ${p.connectedAt ? 'FROM_UNIXTIME(? / 1000)' : 'NULL'}, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
name = VALUES(name), sleeping = VALUES(sleeping), updated_at = CURRENT_TIMESTAMP`,
p.connectedAt
? [serverId, p.steamId, p.name || null, p.sleeping ? 1 : 0, p.connectedAt]
: [serverId, p.steamId, p.name || null, p.sleeping ? 1 : 0],
)
}
}
/** Deletes raw events older than `days`. Totals are never touched — that is the point of them. */
async function pruneEvents(days) {
if (!(days > 0)) return 0
const res = await core.query(
`DELETE FROM ${EVENTS} WHERE created_at < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? DAY)`,
[days],
)
return (res && res.affectedRows) || 0
}
// ── Reads ─────────────────────────────────────────────────────────────────
/**
* Recent events, newest first, restricted to `kinds`.
*
* **`kinds` is never optional.** A default of "all kinds" is one forgotten
* argument away from publishing an IP address, so the caller is made to say it
* every time; `events.model.js` builds the list from the catalogue's allowlist
* and an empty list answers with no rows rather than with everything.
*/
async function recentEvents({ serverId, kinds, wipeId = null, limit = 50 }) {
if (!Array.isArray(kinds) || kinds.length === 0) return []
const holes = kinds.map(() => '?').join(', ')
const params = [serverId, ...kinds]
let sql = `SELECT id, server_id AS serverId, wipe_id AS wipeId, kind, t, steam_id AS steamId, raw
FROM ${EVENTS}
WHERE server_id = ? AND kind IN (${holes})`
if (wipeId) {
sql += ' AND wipe_id = ?'
params.push(wipeId)
}
sql += ' ORDER BY id DESC LIMIT ?'
params.push(limit)
return core.query(sql, params)
}
/**
* The leaderboard for one wipe, or across every wipe when `wipeId` is null.
*
* All-time is a SUM over the per-wipe rows rather than a separate set of
* counters, which is what makes it impossible for the two to disagree — there
* is only ever one number, added up differently.
*/
async function leaderboard({ serverId, wipeId = null, sort = 'kills', limit = 25 }) {
const column = { kills: 'kills', deaths: 'deaths', npcKills: 'npc_kills', playtime: 'playtime_sec' }[sort] || 'kills'
const params = [serverId]
let where = 's.server_id = ?'
if (wipeId) {
where += ' AND s.wipe_id = ?'
params.push(wipeId)
}
params.push(limit)
return core.query(
`SELECT s.steam_id AS steamId,
p.name AS name,
SUM(s.kills) AS kills,
SUM(s.deaths) AS deaths,
SUM(s.npc_kills) AS npcKills,
SUM(s.structures) AS structures,
SUM(s.playtime_sec) AS playtimeSec,
MAX(s.last_seen) AS lastSeen
FROM ${STATS} s
LEFT JOIN ${PLAYERS} p ON p.steam_id = s.steam_id
WHERE ${where}
GROUP BY s.steam_id, p.name
ORDER BY SUM(s.${column}) DESC, MAX(s.last_seen) DESC
LIMIT ?`,
params,
)
}
async function listWipes(serverId) {
return core.query(
`SELECT wipe_id AS wipeId, save_created_at AS saveCreatedAt,
first_seen AS firstSeen, last_seen AS lastSeen
FROM ${WIPES}
WHERE server_id = ?
ORDER BY wipe_id DESC`,
[serverId],
)
}
async function presenceFor(serverId) {
return core.query(
`SELECT steam_id AS steamId, name, sleeping, connected_at AS connectedAt
FROM ${PRESENCE}
WHERE server_id = ?
ORDER BY name ASC`,
[serverId],
)
}
/**
* Login attempts in `[from, to]` that no approval answered (D64).
*
* An attempt is answered by a `player.approved` for the same Steam id on the
* same server stamped from `slackMs` before it to `windowMs` after it. The
* slack is clock grain: both frames come off one game thread, and an approval
* stamped a millisecond "early" is still the answer.
*
* Grouped on (steam id, t) because a cursor replayed after a crash can store the
* same attempt twice, and one attempt is one denial however often it was
* written down.
*/
async function unapprovedLogins({ serverId, from, to, windowMs, slackMs }) {
return core.query(
`SELECT a.steam_id AS steamId, a.t AS t,
MAX(JSON_UNQUOTE(JSON_EXTRACT(a.raw, '$.name'))) AS name
FROM ${EVENTS} a
WHERE a.server_id = ? AND a.kind = 'player.login.attempt'
AND a.steam_id IS NOT NULL AND a.t BETWEEN ? AND ?
AND NOT EXISTS (
SELECT 1 FROM ${EVENTS} b
WHERE b.server_id = a.server_id AND b.kind = 'player.approved'
AND b.steam_id = a.steam_id
AND b.t BETWEEN a.t - ? AND a.t + ?
)
GROUP BY a.steam_id, a.t
ORDER BY a.t ASC
LIMIT 200`,
[serverId, from, to, slackMs, windowMs],
)
}
module.exports = {
getCursor,
setCursor,
insertEvent,
touchWipe,
touchPlayer,
addStats,
addGathered,
addTitleStats,
addWeaponKills,
replacePresence,
pruneEvents,
recentEvents,
leaderboard,
listWipes,
presenceFor,
unapprovedLogins,
}

View File

@@ -0,0 +1,166 @@
// ── The read path's logic ─────────────────────────────────────────────────
//
// Everything that decides WHAT a caller gets, separated from the SQL that
// fetches it, so this file can be tested with no database and `events.db.js` has
// no branching to test.
//
// The decision that matters here is not a business rule, it is a boundary: what
// a signed-out visitor may see. Protocol 2 carries IP addresses and player
// reports, and the only thing standing between them and a public page is
// `catalogue.js`'s allowlist and the fact that **every read on this file takes an
// explicit viewer**. There is no default, because a default is what a caller
// gets when they forget — and the safe value is never the one that is easier to
// type.
const catalogue = require('../../catalogue')
const db = require('./events.db')
/** Hard ceiling on a page, whatever a caller asks for. */
const MAX_LIMIT = 200
function boundedLimit(requested, fallback = 50) {
const n = Number(requested)
if (!Number.isFinite(n) || n <= 0) return fallback
return Math.min(Math.trunc(n), MAX_LIMIT)
}
/**
* Parses a `kind` query parameter into a list.
*
* Accepts `?kind=player.death` and `?kind=player.death,player.chat`, and answers
* `null` for anything empty — which means "whatever this viewer may see" rather
* than "nothing", and is then narrowed by the catalogue.
*/
function parseKinds(raw) {
if (!raw) return null
const list = String(raw)
.split(',')
.map((k) => k.trim())
.filter(Boolean)
return list.length > 0 ? list : null
}
/**
* Recent events for one server, already narrowed to what this viewer may see.
*
* **`admin` is a parameter, not a default.** A route that forgets it gets the
* public list, which is the direction it is safe to be wrong in. And a kind the
* caller asked for that they may not see is dropped silently rather than
* refused: naming it in an error would confirm the kind exists, which is a small
* thing to leak and a free one to avoid.
*/
async function recent({ serverId, admin = false, presence = false, kind = null, wipeId = null, limit }) {
const kinds = catalogue.kindsFor({ admin, presence, requested: parseKinds(kind) })
// Every requested kind was refused. Answering with an empty list is right —
// the events they asked for are, as far as they are concerned, not there.
if (kinds.length === 0) return []
const rows = await db.recentEvents({
serverId,
kinds,
wipeId,
limit: boundedLimit(limit),
})
return rows.map(shape)
}
/**
* One stored row as an API object.
*
* `raw` comes back from the database as text and is parsed here rather than in
* the db layer, because a row whose JSON will not parse is a reporting problem
* and not a query problem: it answers with the envelope it does know and an
* empty body, instead of failing a whole page over one bad row.
*/
function shape(row) {
let frame = {}
try {
frame = typeof row.raw === 'string' ? JSON.parse(row.raw) : row.raw || {}
} catch {
frame = {}
}
return {
id: Number(row.id),
kind: row.kind,
t: Number(row.t),
wipeId: row.wipeId || null,
steamId: row.steamId || null,
frame,
}
}
/**
* The leaderboard for a server, per wipe or all-time.
*
* All-time is the same rows summed differently rather than a second set of
* counters, so the two can never disagree — which is the whole reason R12's
* "per-wipe detail plus all-time rollups" is one table and not two.
*/
async function leaderboard({ serverId, wipeId = null, sort = 'kills', limit, presence = false }) {
const rows = await db.leaderboard({
serverId,
wipeId,
sort,
limit: boundedLimit(limit, 25),
})
return rows.map((r) => ({
steamId: r.steamId,
name: r.name || null,
kills: Number(r.kills) || 0,
deaths: Number(r.deaths) || 0,
npcKills: Number(r.npcKills) || 0,
structures: Number(r.structures) || 0,
playtimeSec: Number(r.playtimeSec) || 0,
// Withheld below the presence audience. A tally refreshes it every minute a
// player is on, so a `lastSeen` of forty seconds ago is the Online tab by
// another name. The ORDER still uses it as a tie-break — that says who was
// on more recently, never whether anybody is on now.
...(presence ? { lastSeen: r.lastSeen || null } : {}),
}))
}
/**
* Every wipe this server has had, newest first.
*
* The list is what makes the per-wipe view navigable, and it is also the proof
* R12 asks for: a wipe that ended is still here, with its stats still attached.
*/
async function wipes(serverId) {
const rows = await db.listWipes(serverId)
return rows.map((r) => ({
wipeId: r.wipeId,
saveCreatedAt: r.saveCreatedAt || null,
firstSeen: r.firstSeen,
lastSeen: r.lastSeen,
}))
}
/**
* Who is on the server right now.
*
* Read from the presence board rather than counted from connect and disconnect
* events: the board is re-sent on every bridge connect and every minute, so it
* is right even after this module has missed something. Counting transitions
* instead would drift, and drift in exactly the direction people notice —
* players who never left.
*/
async function online(serverId) {
const rows = await db.presenceFor(serverId)
return rows.map((r) => ({
steamId: r.steamId,
name: r.name || null,
sleeping: Boolean(r.sleeping),
connectedAt: r.connectedAt || null,
}))
}
module.exports = { recent, leaderboard, wipes, online, parseKinds, boundedLimit, MAX_LIMIT }

View File

@@ -0,0 +1,198 @@
// ── SQL, and nothing else ─────────────────────────────────────────────────
//
// The `.db.js` half of the pair (see `servers.db.js` for why the split earns its
// keep). Raw parameterised SQL through `core.query`, placeholders always.
const core = require('../../core')
const LINKS = 'rust_account_links'
const PLAYERS = 'rust_players'
const STATS = 'rust_player_wipe_stats'
const EVENTS = 'rust_events'
/**
* The link for one Steam id, or undefined.
*
* Joins core's `users` for the username, because every caller that asks "who
* owns this?" wants a name rather than an integer — and the one caller that
* refuses a re-link has to be able to say *whose* it is.
*/
async function getBySteamId(steamId) {
const rows = await core.query(
`SELECT l.steam_id AS steamId, l.user_id AS userId, l.name, l.server_id AS serverId,
l.linked_at AS linkedAt, u.username
FROM ${LINKS} l
JOIN users u ON u.id = l.user_id
WHERE l.steam_id = ?`,
[steamId],
)
return rows[0]
}
/**
* Every Steam account one website user holds, newest first.
*
* **It joins `rust_players` for the name the game last saw**, and that is not a
* convenience. The name on the LINK is what the player was called at the moment
* they linked, which is a Rust name and changes on a whim — so a player who has
* renamed since sees a name they no longer use, on the one page of the site that
* is about who they are. The admin panel already preferred the newer one; this
* is the same rule applied where the person themselves is reading.
*
* A LEFT JOIN, because a player can link an account and never play on it.
*/
async function listForUser(userId) {
return core.query(
`SELECT l.steam_id AS steamId, l.user_id AS userId, l.name, l.server_id AS serverId,
l.linked_at AS linkedAt, p.name AS playerName
FROM ${LINKS} l
LEFT JOIN ${PLAYERS} p ON p.steam_id = l.steam_id
WHERE l.user_id = ?
ORDER BY l.linked_at DESC`,
[userId],
)
}
/**
* Record a link.
*
* **A plain INSERT, never an upsert**, and that is the whole of D23 expressed in
* SQL. `ON DUPLICATE KEY UPDATE` here would silently move a Steam id from one
* website account to another — which, once phase 7 makes a link a privilege path
* and phase 13 makes it an entitlement, is an account takeover performed by
* typing a six-character code. The duplicate-key error is the refusal, and the
* controller turns it into a sentence.
*/
async function insert({ steamId, userId, name, serverId }) {
await core.query(
`INSERT INTO ${LINKS} (steam_id, user_id, name, server_id)
VALUES (?, ?, ?, ?)`,
[steamId, userId, name || null, serverId || null],
)
}
/**
* Remove a link the caller owns.
*
* Scoped by `user_id` in the statement rather than checked before it: a delete
* that reads, decides, then writes has a gap between the read and the write, and
* this way the ownership test and the deletion are the same operation. Answers
* how many rows went, so a caller can tell "removed" from "was not yours".
*/
async function removeOwned(steamId, userId) {
const result = await core.query(
`DELETE FROM ${LINKS} WHERE steam_id = ? AND user_id = ?`,
[steamId, userId],
)
return Number(result && result.affectedRows) || 0
}
/**
* Remove a link whoever holds it — the in-game `/unlink` path, and the staff
* unlink on the `admin.users.detail` panel (D25).
*
* Unscoped by user on purpose: neither caller is the link's owner and both have
* already established their authority another way. In game the authority is the
* Steam account itself — whoever is connected as it is who it is; on the admin
* panel it is the tier gate. Which is why the admin caller writes an
* `activity.log` entry naming the operator and this does not: it cannot tell the
* two apart, and a log line that guessed would be worse than none.
*/
async function removeBySteamId(steamId) {
const result = await core.query(`DELETE FROM ${LINKS} WHERE steam_id = ?`, [steamId])
return Number(result && result.affectedRows) || 0
}
/**
* Every link one user holds, enriched with what this module knows about that
* player — for the `admin.users.detail` panel.
*
* A LEFT JOIN, because a player can link an account and never play on it. An
* operator looking at that user should see the link, not an empty panel.
*/
async function listForUserWithPlayer(userId) {
return core.query(
`SELECT l.steam_id AS steamId, l.name, l.server_id AS serverId, l.linked_at AS linkedAt,
p.name AS playerName, p.first_seen AS firstSeen, p.last_seen AS lastSeen
FROM ${LINKS} l
LEFT JOIN ${PLAYERS} p ON p.steam_id = l.steam_id
WHERE l.user_id = ?
ORDER BY l.linked_at DESC`,
[userId],
)
}
/**
* Per-server all-time totals for one Steam id.
*
* The same rows the public leaderboard sums, grouped by server instead of
* filtered to one — so an operator sees a player across the fleet in one read.
* All-time, deliberately: an admin looking at a user wants their history, not
* this week's.
*/
async function statsForSteamId(steamId) {
return core.query(
`SELECT s.server_id AS serverId, srv.name AS serverName,
SUM(s.kills) AS kills,
SUM(s.deaths) AS deaths,
SUM(s.npc_kills) AS npcKills,
SUM(s.structures) AS structures,
SUM(s.playtime_sec) AS playtimeSec,
MAX(s.last_seen) AS lastSeen,
COUNT(DISTINCT s.wipe_id) AS wipes
FROM ${STATS} s
LEFT JOIN rust_servers srv ON srv.id = s.server_id
WHERE s.steam_id = ?
GROUP BY s.server_id, srv.name
ORDER BY SUM(s.playtime_sec) DESC`,
[steamId],
)
}
/**
* Which of these Steam ids are linked, and to whom.
*
* The one question every notification asks — "who on the website is this
* player?" — asked for a set at once, because a raid names a cupboard's whole
* authorisation list and a clan event a whole roster. An unlinked id is simply
* absent from the answer: there is nobody to tell.
*/
async function userIdsForSteamIds(steamIds) {
if (!steamIds.length) return []
const marks = steamIds.map(() => '?').join(', ')
return core.query(
`SELECT steam_id AS steamId, user_id AS userId FROM ${LINKS} WHERE steam_id IN (${marks})`,
steamIds,
)
}
/**
* The servers that handed out a link code in the last `windowSec` (PLAN_FIXES F5).
*
* Every `/link` in game emits `account.link.requested`, which ingest stores like
* any frame — without the code, which travels through the player. So the site
* cannot know WHICH server minted a code, but it does know which servers minted
* one at all. Read on the database's clock (`created_at`, set at ingest) rather
* than the frame's `t`, which is the game host's clock.
*/
async function recentLinkIssuers(windowSec) {
const rows = await core.query(
`SELECT DISTINCT server_id AS serverId FROM ${EVENTS}
WHERE kind = 'account.link.requested'
AND created_at >= NOW() - INTERVAL ? SECOND`,
[Number(windowSec)],
)
return rows.map((row) => String(row.serverId))
}
module.exports = {
recentLinkIssuers,
getBySteamId,
listForUser,
listForUserWithPlayer,
insert,
removeOwned,
removeBySteamId,
statsForSteamId,
userIdsForSteamIds,
}

View File

@@ -0,0 +1,330 @@
// ── Who owns which Steam account ──────────────────────────────────────────
//
// R1's identity link, site-side. The flow it sits in the middle of:
//
// 1. In game, a player types `/link`. The plugin mints a one-time code, tells
// them privately, and holds it in memory for five minutes.
// 2. On the website, the player types that code. This module asks the sidecar,
// which asks the plugin, which answers with the Steam id the code belongs
// to and drops it.
// 3. This file records the result.
//
// **The site is the author of record and the game holds nothing.** That is the
// one real difference from the UO bridge, which writes a tag onto the game
// account: there is no equivalent per-account store in Rust that survives a wipe,
// and phase 7 needs the site to be authoritative anyway — it pushes permissions
// INTO the game keyed by Steam id. A copy in the game would be a second thing to
// reconcile every wipe, for no question it could answer better.
const core = require('../../core')
const db = require('./links.db')
const engagement = require('../../engagement/emit')
const servers = require('../servers/servers.model')
const serversDb = require('../servers/servers.db')
const sidecar = require('../../sidecarClient')
const log = core.logger('links')
/**
* How far back a code's mint counts (F5): the plugin's five-minute `CodeTtl`,
* plus a minute for a frame that reached this site late — a sidecar that
* reconnected, a cursor catching up. Too wide costs nothing but the old
* "unsure" answer for a little longer; too narrow would call a live code wrong.
*/
const LINK_WINDOW_SEC = 6 * 60
/**
* A link changed, so a clan member's website account changed (D57).
*
* Core resolves a Team member's `userId` from the provider's answer, and that
* answer comes from this table. Without asking, a member who links today is not
* a member of their clan's Team on the site until core's next scheduled sweep —
* fifteen minutes by default — which is exactly when a player tries the clan
* forum for the first time. A request, not a wait: it returns at once and never
* throws into the link flow.
*/
function linksChanged(reason) {
try {
core.teams.reconcile({ reason })
} catch (err) {
log.warn('could not ask core to reconcile Teams after a link change', { reason, error: err.message })
}
}
/** What a link looks like to any caller. Never carries a raw code. */
function shape(row) {
if (!row) return null
return {
steamId: row.steamId,
name: row.name || null,
serverId: row.serverId || null,
linkedAt: row.linkedAt,
}
}
/**
* The Steam accounts one website user holds.
*
* The name is the one the GAME last saw, falling back to the one recorded when
* they linked — the rule the admin panel already used, applied on the page the
* player themselves reads. A browser walk found the two disagreeing: staff saw
* `Wanderer` and the player saw `Wanderer-old`, for the same person on the same
* site.
*/
async function listForUser(userId) {
return (await db.listForUser(userId)).map((row) => ({
...shape(row),
name: row.playerName || row.name || null,
}))
}
/** True when this user holds this Steam id. The ownership gate every player read uses. */
async function owns(steamId, userId) {
const row = await db.getBySteamId(steamId)
return Boolean(row && Number(row.userId) === Number(userId))
}
/**
* Redeem a code against one server, and record the link.
*
* Answers a discriminated result rather than throwing, because every outcome
* here is a sentence somebody has to read:
*
* `{ ok: true, link }` — linked
* `{ ok: false, reason: 'rejected' }`— the game says that code is not good
* `{ ok: false, reason: 'taken', username }` — someone else holds that Steam id
* `{ ok: false, reason: 'offline' }` — the game or its sidecar did not answer
*
* **`rejected` deliberately collapses "unknown" and "expired".** The plugin
* distinguishes them and an operator reading its log can too; a stranger typing
* codes must not learn which of the two they hit, because that is the difference
* between "keep guessing" and "guess faster".
*/
async function confirmOne({ server, code, userId }) {
const result = await sidecar.confirmLink(server, code)
// The transport failed: the sidecar is unreachable, the game is not connected,
// or the reply never came. None of those is a verdict on the code, so the
// player is told to try again rather than that their code is wrong.
if (!result.ok) {
log.warn('link confirm did not reach the game', { server: server.id, status: result.status })
return { ok: false, reason: 'offline' }
}
const frame = result.data || {}
// The plugin's own refusal. `frame.reason` is `unknown`, `expired` or
// `malformed`; it is logged and not surfaced (see the doc above).
if (frame.kind !== 'link.ok' || !frame.steamId) {
log.info('link code refused', { server: server.id, reason: frame.reason || frame.kind || 'unknown' })
return { ok: false, reason: 'rejected' }
}
const steamId = String(frame.steamId)
const held = await db.getBySteamId(steamId)
// D23: refuse, and say whose it is. A move would transfer every permission and
// entitlement phases 7 and 13 hang off this link, on a code anybody in game
// could have run — and the player's way out is `/unlink` in game, which they
// can reach from the machine they are sitting at.
if (held) {
if (Number(held.userId) === Number(userId)) {
// Already theirs. Not an error: a player who pressed the button twice, or
// one whose code was confirmed on a request that then timed out.
return { ok: true, link: shape(held), already: true }
}
return { ok: false, reason: 'taken', username: held.username }
}
try {
await db.insert({
steamId,
userId,
name: frame.name || null,
serverId: server.id,
})
} catch (err) {
// The race the PRIMARY KEY exists for: two confirmations of the same Steam
// id, interleaved between the check above and this write. The key refuses the
// second and it becomes the same refusal, rather than a 500.
if (err && (err.code === 'ER_DUP_ENTRY' || err.errno === 1062)) {
const now = await db.getBySteamId(steamId)
if (now && Number(now.userId) === Number(userId)) {
return { ok: true, link: shape(now), already: true }
}
return { ok: false, reason: 'taken', username: now && now.username }
}
throw err
}
const link = shape(await db.getBySteamId(steamId))
log.info('steam account linked', { steamId, userId, server: server.id })
linksChanged('rust account linked')
// Only a NEW link is news. The `already` path above is somebody pressing the
// button twice, and telling them twice would make the notice meaningless for
// the one case it exists for: a link they did not make.
engagement.linked({ userId, steamId, name: frame.name })
return { ok: true, link }
}
/**
* Redeem a code against the fleet (D24).
*
* **A code is minted by ONE server and the player types six characters into a
* browser**, so the site cannot know which server it came from — nothing in the
* code says, and asking the player to pick would make a wrong guess
* indistinguishable from a wrong code, which is the one refusal that must not be
* ambiguous. So every enabled server is asked in turn and the first `link.ok`
* wins. The others answer `unknown` and nothing happens there: a code is only
* spent at the server that actually holds it.
*
* The loop stops early on `taken`, because that is a verdict about the Steam id
* rather than about this server — asking the rest of the fleet would produce the
* same answer more slowly.
*
* **"Every reachable server refused" is not the same answer as "a server was
* unreachable"**, and collapsing them is how a player who linked on the one
* server that is down gets told their code is wrong. `unsure` is that case, and
* the sentence it earns says to try again rather than to run `/link` again.
*/
async function redeem({ code, userId }) {
const fleet = await servers.listForPolling()
if (fleet.length === 0) return { ok: false, reason: 'no-servers' }
// **Who could hold this code** (PLAN_FIXES F5). The first walk, with five of
// seven servers down, answered a spent code and a made-up `ZZZZZZ` alike with
// "one of the servers could not be reached — your code is still good", and
// would have for as long as any server stayed down. A code lives five minutes
// on the server that minted it, and every mint is an `account.link.requested`
// this site has stored — so only a server that minted one recently can hold it,
// and only one of THOSE being unreachable is a reason to be unsure.
const recent = new Set(await db.recentLinkIssuers(LINK_WINDOW_SEC))
const issuers = fleet.filter((server) => recent.has(String(server.id)))
const others = fleet.filter((server) => !recent.has(String(server.id)))
// **In parallel** (F6). One at a time, the walk's redeem waited about four
// seconds on each dead server in turn — twenty-one in all, the successful link
// included, because the rig sorted last. The issuers first, since the code is
// almost always on one of them; the rest only when none of them had it, which
// covers a code typed in the few seconds before its frame was ingested. Asking
// a server that does not hold the code costs nothing: it answers `unknown`, and
// a code is only ever spent where it was minted.
const asked = await Promise.all(issuers.map((server) => confirmOne({ server, code, userId })))
const settled = asked.find((result) => result.ok || result.reason === 'taken')
if (settled) return settled
// **Not the ones this site already knows are down** (F6, option b of the step-2
// walk). In parallel is not enough on its own: while any server is down, a code
// no issuer holds — every made-up one — still waited out that server's whole
// timeout, twelve seconds on both rigs. A server the poll has seen go down cannot
// answer, and it is not an issuer, so it cannot hold the code: it counts as
// `offline` without the wait. A server with no state yet is asked.
const down = await knownDown()
const reachable = others.filter((server) => !down.has(String(server.id)))
const rest = [
...(await Promise.all(reachable.map((server) => confirmOne({ server, code, userId })))),
...others.filter((server) => down.has(String(server.id))).map(() => ({ ok: false, reason: 'offline' })),
]
const late = rest.find((result) => result.ok || result.reason === 'taken')
if (late) return late
const every = [...asked, ...rest]
if (every.every((result) => result.reason === 'offline')) return { ok: false, reason: 'offline' }
if (asked.some((result) => result.reason === 'offline')) return { ok: false, reason: 'unsure' }
return { ok: false, reason: 'rejected' }
}
/**
* The servers the board poll last saw without a connected game, by id. A failed
* read is an empty set — everybody is asked, which is slow and never wrong.
*/
async function knownDown() {
try {
const states = await serversDb.listState()
return new Set(states.filter((state) => !Number(state.online)).map((state) => String(state.serverId)))
} catch (err) {
log.warn('could not read server state for the link fleet', { error: err.message })
return new Set()
}
}
/** Remove a link the caller owns. False when they did not hold it. */
async function unlinkOwned(steamId, userId) {
const removed = (await db.removeOwned(steamId, userId)) > 0
if (removed) linksChanged('rust account unlinked')
return removed
}
/**
* Remove a link whoever holds it.
*
* Two callers, both of which have already established their authority and
* neither of which is the link's owner: ingest applying an in-game `/unlink`
* (the authority is the Steam account — whoever is connected as it is who it
* is), and a staff unlink from the `admin.users.detail` panel (D25).
*
* It logs nothing about who asked, because the two callers record that
* differently: the admin one writes an `activity.log` entry naming the operator,
* and the game one has no operator to name.
*/
async function unlinkAnyOwner(steamId) {
const removed = (await db.removeBySteamId(steamId)) > 0
if (removed) linksChanged('rust account unlinked')
return removed
}
/**
* Remove a link because the player asked in game.
*
* Called from ingest, off an `account.unlinked` event.
*/
async function unlinkFromGame(steamId) {
const removed = await unlinkAnyOwner(steamId)
if (removed) log.info('steam account unlinked in game', { steamId })
return removed
}
/** The admin panel's read: every link this user holds, with per-server totals. */
async function forAdmin(userId) {
const links = await db.listForUserWithPlayer(userId)
return Promise.all(
links.map(async (row) => ({
steamId: row.steamId,
// The name on the LINK is what they were called when they linked; the one
// on `rust_players` is what the game last saw. They differ the moment
// somebody renames, and the newer one is the useful one to show.
name: row.playerName || row.name || null,
linkedName: row.name || null,
serverId: row.serverId || null,
linkedAt: row.linkedAt,
firstSeen: row.firstSeen || null,
lastSeen: row.lastSeen || null,
servers: (await db.statsForSteamId(row.steamId)).map((s) => ({
serverId: s.serverId,
serverName: s.serverName || s.serverId,
kills: Number(s.kills) || 0,
deaths: Number(s.deaths) || 0,
npcKills: Number(s.npcKills) || 0,
structures: Number(s.structures) || 0,
playtimeSec: Number(s.playtimeSec) || 0,
wipes: Number(s.wipes) || 0,
lastSeen: s.lastSeen || null,
})),
})),
)
}
module.exports = {
shape,
listForUser,
owns,
confirmOne,
redeem,
unlinkOwned,
unlinkAnyOwner,
unlinkFromGame,
forAdmin,
}

147
server/model/map/map.db.js Normal file
View File

@@ -0,0 +1,147 @@
// ── SQL for the map ───────────────────────────────────────────────────────
//
// Three things: the picture each server's map is drawn on (`rust_map_images`),
// the per-server overrides of the map's switches (`rust_map_overrides`), and the
// two reads the own-and-mates view needs — which Steam accounts a website user
// holds, and who shares a clan with them on one server.
//
// Nothing here stores a POSITION. Where people are is asked for while somebody
// is looking and kept in memory for seconds (D111, `mapLive.js`).
const core = require('../../core')
const IMAGES = 'rust_map_images'
const OVERRIDES = 'rust_map_overrides'
const LINKS = 'rust_account_links'
const CLANS = 'rust_clans'
const MEMBERS = 'rust_clan_members'
/** The columns every read but the picture's own wants — everything except the bytes. */
const META = `server_id AS serverId, map_key AS mapKey, sha256, source, width, height,
ocean_margin AS oceanMargin, world_size AS worldSize, grid_cells AS gridCells,
grid_cell_size AS gridCellSize, background, derivation, monuments,
OCTET_LENGTH(bytes) AS byteCount, fetched_at AS fetchedAt`
/** One server's picture row without the bytes, or undefined. */
async function getMeta(serverId) {
const rows = await core.query(`SELECT ${META} FROM ${IMAGES} WHERE server_id = ?`, [serverId])
return rows[0]
}
/** Every server's picture row without the bytes, for the admin card. */
async function listMeta() {
return core.query(`SELECT ${META} FROM ${IMAGES}`)
}
/**
* The picture itself, but only if it is still the one named. A URL carries the
* hash it was minted for, and a picture replaced since must not be served under
* it: the response is cached as immutable.
*/
async function getBytes(serverId, sha256) {
const rows = await core.query(
`SELECT bytes FROM ${IMAGES} WHERE server_id = ? AND sha256 = ? AND bytes IS NOT NULL`,
[serverId, sha256],
)
return rows[0] ? rows[0].bytes : null
}
/**
* Replace one server's row whole, in ONE statement. A new map's picture and its
* geometry arrive together or not at all; a reader never sees the new bytes
* under the old monuments.
*/
async function putImage(row) {
await core.query(
`REPLACE INTO ${IMAGES}
(server_id, map_key, sha256, source, width, height, ocean_margin, world_size,
grid_cells, grid_cell_size, background, derivation, monuments, bytes, fetched_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
[
row.serverId, row.mapKey, row.sha256 || null, row.source, row.width, row.height, row.oceanMargin,
row.worldSize, row.gridCells, row.gridCellSize, row.background || null, row.derivation,
JSON.stringify(row.monuments || []), row.bytes || null,
],
)
}
/**
* Re-derive a row's geometry and monuments without touching its picture — the
* `DERIVATION_VERSION` path, and a map whose picture is unchanged but whose
* source moved (a render replaced by the Rust+ cache of the same bytes).
*/
async function putGeometry(row) {
await core.query(
`UPDATE ${IMAGES}
SET source = ?, width = ?, height = ?, ocean_margin = ?, world_size = ?, grid_cells = ?,
grid_cell_size = ?, background = ?, derivation = ?, monuments = ?
WHERE server_id = ? AND map_key = ?`,
[
row.source, row.width, row.height, row.oceanMargin, row.worldSize, row.gridCells, row.gridCellSize,
row.background || null, row.derivation, JSON.stringify(row.monuments || []), row.serverId, row.mapKey,
],
)
}
/** Every override for one server, as `{ setting: value }` rows. */
async function getOverrides(serverId) {
return core.query(`SELECT setting, value FROM ${OVERRIDES} WHERE server_id = ?`, [serverId])
}
/** Every override in the fleet, for the admin card. */
async function listOverrides() {
return core.query(`SELECT server_id AS serverId, setting, value FROM ${OVERRIDES}`)
}
/** Set (a word) or clear (`null`) one server's override of one switch. */
async function setOverride(serverId, setting, value, userId = null) {
if (value === null) {
await core.query(`DELETE FROM ${OVERRIDES} WHERE server_id = ? AND setting = ?`, [serverId, setting])
return
}
await core.query(
`INSERT INTO ${OVERRIDES} (server_id, setting, value, updated_by, updated_at)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE value = VALUES(value), updated_by = VALUES(updated_by),
updated_at = CURRENT_TIMESTAMP`,
[serverId, setting, value, userId],
)
}
/** Every Steam id one website user has linked. A link reaches every server (D28). */
async function steamIdsForUser(userId) {
const rows = await core.query(`SELECT steam_id AS steamId FROM ${LINKS} WHERE user_id = ?`, [userId])
return rows.map((r) => String(r.steamId))
}
/**
* Every Steam id sharing a first-party clan with any of `steamIds` on ONE
* server (D115, D117) — the viewer's own accounts included, since they are
* members too. A clan the board no longer carries (`gone_at`) is nobody's clan.
*/
async function clanMatesOn(serverId, steamIds) {
if (!steamIds.length) return []
const rows = await core.query(
`SELECT DISTINCT m2.steam_id AS steamId
FROM ${MEMBERS} m1
JOIN ${CLANS} c ON c.external_id = m1.external_id
JOIN ${MEMBERS} m2 ON m2.external_id = m1.external_id
WHERE c.server_id = ? AND c.gone_at IS NULL
AND m1.steam_id IN (${steamIds.map(() => '?').join(', ')})`,
[serverId, ...steamIds],
)
return rows.map((r) => String(r.steamId))
}
module.exports = {
getMeta,
listMeta,
getBytes,
putImage,
putGeometry,
getOverrides,
listOverrides,
setOverride,
steamIdsForUser,
clanMatesOn,
}

View File

@@ -0,0 +1,598 @@
// ── The map: who may see which layer, and what a viewer is sent ───────────
//
// R9's security boundary, and the reason this file exists apart from the
// picture machinery in `mapImages.js`: **public player positions in Rust locate
// players, and base positions are where they sleep.** So every layer has its own
// audience (D112), a fleet default with a per-server override (D114), and a
// viewer is SENT only the layers they may see — a hidden layer is absent from the
// answer, never present and hidden by the page (§30.2).
//
// ── The four layers ───────────────────────────────────────────────────────
//
// world monuments, and the world's own events: cargo, the patrol
// helicopter, the Chinook, Bradley, supply drops, locked crates
// events what this site's events placed: zones, crates, NPCs (phase 13a)
// players who is on the server and where, and the sleepers
// bases tool cupboards and player vending machines, as positions only
//
// Defaults: the first two public, the last two staff. The audiences are the
// presence rungs (`staff` · `signed_in` · `public`) and follow its asymmetric
// fallbacks: an unknown stored word narrows to staff, an unknown viewer is
// public (`model/visibility`).
//
// ── Two rules that make the players layer safe to widen ───────────────────
//
// **D113 — it can never show more than presence does.** Its effective audience
// is the NARROWER of the layer's switch and the server's presence audience. An
// operator who opens the map to the public while the roll call stays staff has
// opened nothing: a name on a map says who is online as surely as a list does.
//
// **D115/D117 — own dot and clan mates.** A linked viewer sees their own
// position (their sleeper too, §30.5) and their ONLINE first-party clan mates on
// that server, whatever the players layer says — and only a linked member of the
// same clan sees them. It is gated by its own switch (D118, default on) and by
// nothing else: widening the roster widens who sees the member LIST, never where
// the members are.
const core = require('../../core')
const db = require('./map.db')
const visibility = require('../visibility/visibility.model')
const visibilityDb = require('../visibility/visibility.db')
const log = core.logger('map')
const LAYERS = Object.freeze(['world', 'events', 'players', 'bases'])
const DEFAULTS = Object.freeze({ world: 'public', events: 'public', players: 'staff', bases: 'staff' })
/** D118: on, because it shows a member nothing the game does not already show them. */
const DEFAULT_MATES = true
const MATES_KEY = 'map.mates'
const layerKey = (layer) => `map.layer.${layer}.audience`
/** Every override setting name a server may carry, besides the marker switches below. */
const SETTINGS = Object.freeze([...LAYERS.map(layerKey), MATES_KEY])
// ── Which monuments are drawn (PLAN_REDESIGNS §4, D196) ───────────────────
//
// A switch per monument LABEL, because that is what staff read and it groups the
// variants: 31 substations of four prefabs are one "Substation". It is clutter
// control, not a security boundary — the world layer's audience still decides
// whether a viewer gets monuments at all — but a hidden label is still left out
// of the answer rather than sent and hidden, like every other map rule.
//
// The minor labels below start OFF. **Every other label is on**, so a monument
// Facepunch adds next month appears rather than disappears. One row per label in
// `rust_settings` (the fleet) and `rust_map_overrides` (a server), `on` or `off`.
// Labels match case-insensitively: the game says "jungle swamp" for one prefab.
const MARKER_PREFIX = 'map.marker.'
/** Both setting columns are VARCHAR(64); a longer label cannot carry a switch. */
const MARKER_KEY_MAX = 64 - MARKER_PREFIX.length
/**
* The labels off unless an admin turns them on, spelled as the game labels
* them: all were read from the Carbon rig's 6000 map, seed 981448696, which has
* every one (2026-09-29). The game writes "Jungle ruin" there and "Jungle Ruin"
* on a 3000 map; the key is lower case, so both match.
*/
const MINOR_LABELS = Object.freeze([
'Substation',
'Underground Cave',
'Train Tunnel',
'Water Well',
'Wild Swamp',
'Jungle Swamp',
'Ice Lake',
'Jungle Ruin',
'Fishing Village',
'Large Barn',
'Abandoned Supermarket',
"Oxum's Gas Station",
'Mining Outpost',
'Ranch',
// D213: found on the 6000 map, hidden at the org lead's word.
'Canyon B',
'Canyon C',
'Lake A',
'Oasis A',
'Oasis C',
'Mountain',
'Train Tunnel Link',
'Abandoned Cabins',
])
/** A label as its switch's key: trimmed, single-spaced, lower case. */
const markerKey = (label) => String(label == null ? '' : label).trim().replace(/\s+/g, ' ').toLowerCase()
const MINOR = new Set(MINOR_LABELS.map(markerKey))
/** Whether a label is drawn when nobody has said: off for the minor list, on for everything else. */
const markerDefault = (key) => !MINOR.has(key)
/** A stored word as a boolean, or undefined for a word that is neither — which then follows the default. */
function markerWord(value) {
if (value === 'on') return true
if (value === 'off') return false
return undefined
}
/**
* Whether one label is drawn, given the explicit switches that apply (a
* server's over the fleet's, already merged). **Pure.**
*/
function markerShown(markers, label) {
const key = markerKey(label)
return markers && Object.prototype.hasOwnProperty.call(markers, key) ? markers[key] : markerDefault(key)
}
/** The monuments a viewer is sent: those whose label is drawn on this server. **Pure.** */
function filterMonuments(monuments, markers) {
return (monuments || []).filter((m) => markerShown(markers, m.label || m.kind))
}
/**
* The labels on one stored map, each once, with how many markers carry it and
* the spelling to show (a capitalised one where the game uses both).
*/
function markerLabels(monuments) {
const byKey = new Map()
for (const m of monuments || []) {
const label = String(m.label || m.kind || '').trim().replace(/\s+/g, ' ')
const key = markerKey(label)
if (!key) continue
const seen = byKey.get(key)
if (!seen) byKey.set(key, { key, label, count: 1 })
else {
seen.count += 1
if (seen.label === seen.label.toLowerCase() && label !== label.toLowerCase()) seen.label = label
}
}
return [...byKey.values()].sort((a, b) => a.label.localeCompare(b.label))
}
/**
* `DERIVATION_VERSION` (R9): how a row's geometry is worked out from what the
* plugin said. A stored row with an older number is re-derived from a fresh
* `map.info`, without fetching the picture again.
*
* 1 — width/height from the picture itself (or, with no picture, the Rust+
* cache's geometry: half scale plus the ocean margin); the grid from the
* game's own `MapHelper` (D119); the margin in PIXELS, unscaled.
*/
const DERIVATION_VERSION = 1
/** The Rust+ cache's scale, used only to size a map that has no picture yet. */
const CACHE_SCALE = 0.5
/** How often the page asks for positions while visible, and how long the module keeps an answer. */
const POLL_MS = 10000
const LIVE_CACHE_MS = 5000
/**
* What a render costs, measured on the rig (§30.0): 8.5 s for a 3000 map at
* half scale, a 2500 × 2500 picture. The work is per pixel, so the estimate for
* another size scales with its area.
*/
const RENDER_MEASURED = Object.freeze({ worldSize: 3000, seconds: 8.5 })
function renderStallSeconds(worldSize, margin = 500) {
const side = (ws) => ws * CACHE_SCALE + 2 * margin
const size = Number(worldSize) > 0 ? Number(worldSize) : RENDER_MEASURED.worldSize
const ratio = (side(size) * side(size)) / (side(RENDER_MEASURED.worldSize) ** 2)
return Math.max(1, Math.round(RENDER_MEASURED.seconds * ratio))
}
/** A stored mates word as a boolean. Anything but `on` is off: an unknown word narrows. */
const matesOn = (value) => value === 'on'
/** The narrower of two audiences: the one fewer people satisfy. */
function narrower(a, b) {
const ra = visibility.AUDIENCES.indexOf(visibility.normalise(a))
const rb = visibility.AUDIENCES.indexOf(visibility.normalise(b))
return visibility.AUDIENCES[Math.max(ra, rb)]
}
/** The fleet defaults, as stored, with the built-in defaults where nothing is. */
async function fleet() {
const stored = await Promise.all([
...LAYERS.map((l) => visibilityDb.getSetting(layerKey(l))),
visibilityDb.getSetting(MATES_KEY),
visibilityDb.listSettings(MARKER_PREFIX),
])
const out = {}
LAYERS.forEach((layer, i) => {
out[layer] = stored[i] == null ? DEFAULTS[layer] : visibility.normalise(stored[i])
})
const mates = stored[LAYERS.length]
out.mates = mates == null ? DEFAULT_MATES : matesOn(mates)
out.markers = markersFrom(stored[LAYERS.length + 1] || [])
return out
}
/** Marker rows as `{ substation: true, … }`, only for the labels somebody switched. */
function markersFrom(rows) {
const out = {}
for (const { setting, value } of rows) {
if (!String(setting).startsWith(MARKER_PREFIX)) continue
const shown = markerWord(value)
if (shown !== undefined) out[String(setting).slice(MARKER_PREFIX.length)] = shown
}
return out
}
/** Overrides rows as `{ world: 'staff', mates: false, markers: { … }, … }`, only for what is set. */
function overridesFrom(rows) {
const out = { markers: markersFrom(rows) }
for (const { setting, value } of rows) {
if (setting === MATES_KEY) out.mates = matesOn(value)
else {
const layer = LAYERS.find((l) => layerKey(l) === setting)
if (layer) out[layer] = visibility.normalise(value)
}
}
return out
}
/** A server's overrides over the fleet, the marker switches merged label by label. */
function over(base, overrides) {
return { ...base, ...overrides, markers: { ...base.markers, ...overrides.markers } }
}
/** What applies to one server: its overrides over the fleet. */
async function forServer(serverId) {
const [base, rows] = await Promise.all([fleet(), db.getOverrides(serverId)])
return over(base, overridesFrom(rows))
}
/**
* Everything the public routes need to decide what one viewer gets on one
* server's map. Throws nothing: a setting that cannot be read hides every layer
* but the picture, which is the direction a map must fail in.
*/
async function access(req, serverId) {
try {
const [viewer, settings, presence] = await Promise.all([
visibility.viewer(req),
forServer(serverId),
visibility.presenceFor(serverId),
])
const layers = {}
for (const layer of LAYERS) {
const audience = layer === 'players' ? narrower(settings.players, presence) : settings[layer]
layers[layer] = { visible: visibility.meets(viewer.level, audience), audience }
}
// Why the players layer is narrower than its own switch, when it is (D113):
// the page says "limited by who may see who is online" rather than nothing.
if (layers.players.audience !== visibility.normalise(settings.players)) layers.players.cappedByPresence = true
let steamIds = []
if (settings.mates && viewer.userId != null) steamIds = await db.steamIdsForUser(viewer.userId)
const mates = {
on: settings.mates,
linked: steamIds.length > 0,
visible: settings.mates && steamIds.length > 0,
}
return { level: viewer.level, userId: viewer.userId, layers, mates, steamIds, markers: settings.markers }
} catch (err) {
log.warn('could not resolve map visibility; showing the picture only', { server: serverId, error: err.message })
const layers = {}
for (const layer of LAYERS) layers[layer] = { visible: false, audience: 'staff' }
return { level: 'public', userId: null, layers, mates: { on: false, linked: false, visible: false }, steamIds: [], markers: {} }
}
}
/**
* The positions a viewer who is entitled to own-and-mates may see: their own
* accounts (online or asleep) and their ONLINE clan mates on this server. Empty
* for anybody else. Asked only when there is a live answer to filter.
*/
async function mateIdsFor(serverId, acc) {
if (!acc.mates.visible || !acc.steamIds.length) return { own: new Set(), mates: new Set() }
const own = new Set(acc.steamIds)
const clan = await db.clanMatesOn(serverId, acc.steamIds)
return { own, mates: new Set(clan.filter((id) => !own.has(id))) }
}
/**
* One live answer, cut down to what one viewer may see. **Pure**, and the
* security boundary in one function: a layer the viewer may not see is not in
* the result at all — not an empty array, not a flag — so there is nothing on
* the wire for a page to forget to hide.
*
* `mates` is the viewer's own dots and their online clan mates' (D115). It is
* the ONLY place a player position can appear below the players layer, and it
* never carries anybody outside the viewer's clan.
*/
function project(live, acc, ids = { own: new Set(), mates: new Set() }) {
const out = { mapKey: live.mapKey || null, t: live.t || null }
if (acc.layers.world.visible) out.world = Array.isArray(live.world) ? live.world : []
if (acc.layers.events.visible) out.events = Array.isArray(live.events) ? live.events : []
if (acc.layers.players.visible) {
out.players = Array.isArray(live.players) ? live.players : []
if (live.playersTruncated) out.playersTruncated = true
}
if (acc.layers.bases.visible) {
out.bases = Array.isArray(live.bases) ? live.bases : []
if (live.basesTruncated) out.basesTruncated = true
}
if (acc.mates.visible) {
const players = Array.isArray(live.players) ? live.players : []
out.mates = players
.filter((p) => ids.own.has(String(p.steamId)) || (ids.mates.has(String(p.steamId)) && p.online === true))
.map((p) => ({
steamId: String(p.steamId),
name: p.name,
x: p.x,
z: p.z,
sleeping: Boolean(p.sleeping),
online: p.online === true,
self: ids.own.has(String(p.steamId)),
}))
}
return out
}
/**
* A stored row as the geometry the page draws with. The picture's own size is
* the truth when there is one; without one the Rust+ cache's geometry stands in,
* so a server that has no picture yet draws its layers in the same frame a
* picture would later fill.
*/
function geometryOf(row) {
if (!row) return null
return {
worldSize: Number(row.worldSize),
oceanMargin: Number(row.oceanMargin),
width: Number(row.width),
height: Number(row.height),
gridCells: Number(row.gridCells),
gridCellSize: Number(row.gridCellSize),
background: row.background || null,
}
}
/**
* `map.info` as the row it becomes (without bytes). **Pure** — the one place
* `DERIVATION_VERSION` is applied.
*/
function derive(serverId, info) {
const worldSize = Number(info.worldSize) || 0
const oceanMargin = Number(info.oceanMargin) || 0
const hasPicture = info.source !== 'none' && Number(info.width) > 0 && Number(info.height) > 0
const side = Math.round(worldSize * CACHE_SCALE + 2 * oceanMargin)
return {
serverId,
mapKey: String(info.mapKey || ''),
sha256: hasPicture && info.sha256 ? String(info.sha256).toLowerCase() : null,
source: hasPicture ? String(info.source) : 'none',
width: hasPicture ? Number(info.width) : side,
height: hasPicture ? Number(info.height) : side,
oceanMargin,
worldSize,
gridCells: Number(info.gridCells) || 1,
gridCellSize: Number(info.gridCellSize) || worldSize,
background: typeof info.background === 'string' && /^#[0-9a-f]{6}$/i.test(info.background) ? info.background : null,
derivation: DERIVATION_VERSION,
monuments: Array.isArray(info.monuments)
? info.monuments
.filter((m) => m && Number.isFinite(Number(m.x)) && Number.isFinite(Number(m.z)))
.map((m) => ({
value: String(m.value || ''),
kind: String(m.kind || ''),
label: String(m.label || m.kind || ''),
grid: m.grid ? String(m.grid) : null,
x: Number(m.x),
z: Number(m.z),
}))
: [],
}
}
/** Parse the stored monuments, never throwing: a row that will not parse draws none. */
function monumentsOf(row) {
if (!row || !row.monuments) return []
try {
const parsed = typeof row.monuments === 'string' ? JSON.parse(row.monuments) : row.monuments
return Array.isArray(parsed) ? parsed : []
} catch (err) {
return []
}
}
// ── Admin ────────────────────────────────────────────────────────────────
/** The Map card's switches: the fleet, and each server's overrides and effective values. */
async function describeSwitches(servers) {
const [base, rows] = await Promise.all([fleet(), db.listOverrides()])
const byServer = new Map()
for (const row of rows) {
if (!byServer.has(row.serverId)) byServer.set(row.serverId, [])
byServer.get(row.serverId).push(row)
}
return {
layers: [...LAYERS],
defaults: { ...DEFAULTS, mates: DEFAULT_MATES },
// D196: the labels that start off. Every label not listed here starts on.
minorLabels: [...MINOR_LABELS],
fleet: base,
servers: servers.map((s) => {
const overrides = overridesFrom(byServer.get(s.id) || [])
const full = {}
for (const key of [...LAYERS, 'mates']) full[key] = key in overrides ? overrides[key] : null
full.markers = overrides.markers
return { id: s.id, overrides: full, effective: over(base, overrides) }
}),
}
}
/**
* The Map card's write, validated whole before anything is written, like the
* rest of the visibility page.
*
* { fleet: { world: 'public', …, mates: true },
* servers: { <id>: { players: 'signed_in', mates: null, … } } }
*
* `null` clears an override. Resolves `{ ok, changed }` or `{ ok: false,
* status, message }`. `dryRun` validates and writes nothing, so a caller saving
* several things in one request can refuse the whole request up front.
*/
async function update({ fleet: fleetIn, servers } = {}, actor = null, serverExists = async () => true, { dryRun = false } = {}) {
const fleetChanges = []
const serverChanges = []
const fleetMarkers = []
const serverMarkers = []
// `markers` is `{ <label key>: true | false | null }` (D196). `null` clears:
// on a server it follows the fleet again, on the fleet the built-in list.
const checkMarkers = (markers, where) => {
if (!markers || typeof markers !== 'object' || Array.isArray(markers)) {
return { problem: `The marker switches${where} must be an object of label: on or off.` }
}
const out = []
for (const [key, value] of Object.entries(markers)) {
if (!key || markerKey(key) !== key) {
return { problem: `"${key}" is not a marker label key${where}: keys are the label in lower case, single-spaced.` }
}
if (key.length > MARKER_KEY_MAX) {
return { problem: `The label "${key}"${where} is longer than ${MARKER_KEY_MAX} characters, so it cannot carry a switch.` }
}
if (value !== null && typeof value !== 'boolean') {
return { problem: `The "${key}" markers are shown or hidden${where}, not "${value}".` }
}
out.push([key, value])
}
return { out }
}
const check = (key, value, where, allowNull) => {
if (value === null && allowNull) return null
if (key === 'mates') {
if (typeof value !== 'boolean') return `The own-and-mates view is on or off${where}, not "${value}".`
return null
}
if (!LAYERS.includes(key)) return `"${key}" is not a map layer. The layers are: ${LAYERS.join(', ')}, and mates.`
if (!visibility.isAudience(value)) {
return `"${value}" is not an audience for the ${key} layer${where}. Choose one of: ${visibility.AUDIENCES.join(', ')}.`
}
return null
}
for (const [key, value] of Object.entries(fleetIn || {})) {
if (key === 'markers') {
const { problem, out } = checkMarkers(value, '')
if (problem) return { ok: false, status: 400, message: problem }
fleetMarkers.push(...out)
continue
}
const problem = check(key, value, '', false)
if (problem) return { ok: false, status: 400, message: problem }
fleetChanges.push([key, value])
}
for (const [id, settings] of Object.entries(servers || {})) {
if (!settings || typeof settings !== 'object') {
return { ok: false, status: 400, message: `Server ${id}'s map switches must be an object.` }
}
// eslint-disable-next-line no-await-in-loop
if (!(await serverExists(id))) return { ok: false, status: 404, message: `There is no server called ${id}.` }
for (const [key, value] of Object.entries(settings)) {
if (key === 'markers') {
const { problem, out } = checkMarkers(value, ` on server ${id}`)
if (problem) return { ok: false, status: 400, message: problem }
for (const [label, shown] of out) serverMarkers.push([id, label, shown])
continue
}
const problem = check(key, value, ` on server ${id}`, true)
if (problem) return { ok: false, status: 400, message: problem }
serverChanges.push([id, key, value])
}
}
if (dryRun) return { ok: true, changed: {} }
const userId = actor && actor.id != null ? actor.id : null
const settingOf = (key) => (key === 'mates' ? MATES_KEY : layerKey(key))
const wordOf = (key, value) => (key === 'mates' ? (value ? 'on' : 'off') : value)
for (const [key, value] of fleetChanges) {
// eslint-disable-next-line no-await-in-loop
await visibilityDb.setSetting(settingOf(key), wordOf(key, value), userId)
}
for (const [id, key, value] of serverChanges) {
// eslint-disable-next-line no-await-in-loop
await db.setOverride(id, settingOf(key), value === null ? null : wordOf(key, value), userId)
}
const markerWordOf = (shown) => (shown ? 'on' : 'off')
for (const [key, shown] of fleetMarkers) {
// eslint-disable-next-line no-await-in-loop
if (shown === null) await visibilityDb.clearSetting(MARKER_PREFIX + key)
// eslint-disable-next-line no-await-in-loop
else await visibilityDb.setSetting(MARKER_PREFIX + key, markerWordOf(shown), userId)
}
for (const [id, key, shown] of serverMarkers) {
// eslint-disable-next-line no-await-in-loop
await db.setOverride(id, MARKER_PREFIX + key, shown === null ? null : markerWordOf(shown), userId)
}
const changed = {}
if (fleetChanges.length) changed.fleet = Object.fromEntries(fleetChanges)
if (fleetMarkers.length) {
changed.fleet = { ...(changed.fleet || {}), markers: Object.fromEntries(fleetMarkers.map(([k, v]) => [k, v === null ? 'default' : v])) }
}
if (serverChanges.length || serverMarkers.length) {
changed.servers = {}
for (const [id, key, value] of serverChanges) {
changed.servers[id] = { ...(changed.servers[id] || {}), [key]: value === null ? 'inherit' : value }
}
for (const [id, key, shown] of serverMarkers) {
const entry = changed.servers[id] || {}
changed.servers[id] = { ...entry, markers: { ...(entry.markers || {}), [key]: shown === null ? 'inherit' : shown } }
}
}
return { ok: true, changed }
}
module.exports = {
LAYERS,
DEFAULTS,
DEFAULT_MATES,
MATES_KEY,
SETTINGS,
MARKER_PREFIX,
MARKER_KEY_MAX,
MINOR_LABELS,
DERIVATION_VERSION,
POLL_MS,
LIVE_CACHE_MS,
RENDER_MEASURED,
layerKey,
markerKey,
markerShown,
filterMonuments,
markerLabels,
renderStallSeconds,
narrower,
fleet,
forServer,
access,
mateIdsFor,
project,
geometryOf,
derive,
monumentsOf,
describeSwitches,
update,
}

View File

@@ -0,0 +1,277 @@
// ── A RunicNPC profile, checked here as RunicNPC checks it (D238) ───────────
//
// The site authors profiles and pushes them to each server's RunicNPC, which
// checks them again and refuses what it cannot use (docs/runicnpc/API.md). The
// site checks first so an admin reads the reason on the form, not in a push
// report minutes later. The rules below are RunicNPC's `ValidateProfile`, in
// the same order and with the same sentences, less the one only the server can
// answer: whether it has each kit. That one is checked against the kit list
// each server last reported (`npcs.model.js`).
//
// Pure functions: no database, no sidecar.
/** RunicNPC's rule for a profile, placement or route name. */
const NAME_RULE = /^[a-z0-9_-]{1,40}$/
/** A plain scientist prefab, as RunicNPC resolves one (`scientistnpc_*`). */
const PREFAB_RULE = /^scientistnpc_[a-z0-9_]{1,40}$/
/** The prefabs the form offers; RunicNPC accepts any plain `scientistnpc_*`. */
const PREFABS = ['scientistnpc_roam', 'scientistnpc_heavy', 'scientistnpc_patrol', 'scientistnpc_roamtethered', 'scientistnpc_full_any']
const ROLES = ['roamer', 'sentry', 'guard']
/** Rust's own two factions (D254). Neither can be a profile's faction. */
const BUILT_IN_FACTIONS = ['scientists', 'animals']
const RELATIONS = ['hostile', 'neutral', 'allied']
/** D259, D264, D267. */
const TURRETS = ['default', 'ignore', 'always']
/** D260: the kit's extras a profile may opt into, each used up (D265). */
const KIT_USES = ['heal', 'grenades', 'melee', 'rockets', 'flamethrower']
const RELATIONS_MAX = 40
const FACTION_PAIRS_MAX = 400
/** D247: how a profile's kills are counted. `server` is the default. */
const KILLS_SCOPES = ['server', 'name', 'profile']
const NAMES_MAX = 20
const DISPLAY_NAME_MAX = 32
const KITS_MAX = 20
const THRESHOLDS_MAX = 10
/** RunicNPC's defaults (API.md, D238), so a form may leave a value out. */
function defaults() {
return {
names: [],
kits: [],
prefab: 'scientistnpc_roam',
role: 'roamer',
movement: { mode: 'wander', radius: 20 },
health: 150,
damageDealt: 1,
damageTaken: { head: 1, body: 1, legs: 1 },
aimCone: 2,
ranges: { sense: 30, loseTarget: 40, chase: 40, attack: 30 },
visionCone: -0.8,
sleepDistance: 160,
healthThresholds: [],
// Stage 5 (D254–D261, D271). None of them makes a profile fight anything but players (D255).
faction: null,
relations: {},
alertRadius: 40,
turrets: 'default',
hurtByPlayers: true,
hurtsPlayers: true,
kitUse: { heal: false, grenades: false, melee: false, rockets: false, flamethrower: false },
}
}
/** A faction name, one of Rust's two, or (where a profile names it) `profile:<name>`. */
function isFactionKey(key, profileAllowed) {
const k = String(key === undefined || key === null ? '' : key)
if (BUILT_IN_FACTIONS.includes(k) || NAME_RULE.test(k)) return true
return profileAllowed && k.startsWith('profile:') && NAME_RULE.test(k.slice(8))
}
function pairKey(a, b) {
return a < b ? `${a}|${b}` : `${b}|${a}`
}
/**
* The faction table (D254), one row per pair, both ways (D268), checked as
* RunicNPC's `ValidateFactions` checks it, with its sentences. `{ ok, value }`
* with the rows sorted, or `{ ok: false, error }`.
*/
function checkFactions(input) {
if (!Array.isArray(input)) return { ok: false, error: 'factions: a list of { a, b, relation }' }
if (input.length > FACTION_PAIRS_MAX) return { ok: false, error: `factions: at most ${FACTION_PAIRS_MAX} pairs` }
const seen = new Set()
const rows = []
for (let i = 0; i < input.length; i++) {
const f = input[i] || {}
const a = String(f.a === undefined || f.a === null ? '' : f.a).trim()
const b = String(f.b === undefined || f.b === null ? '' : f.b).trim()
const relation = String(f.relation === undefined || f.relation === null ? 'neutral' : f.relation)
if (!isFactionKey(a, false) || !isFactionKey(b, false)) {
return { ok: false, error: `factions[${i}]: a and b are faction names (1–40 of a-z, 0-9, _ and -), scientists or animals` }
}
if (a === b) return { ok: false, error: `factions[${i}]: a faction is always allied to itself` }
if (BUILT_IN_FACTIONS.includes(a) && BUILT_IN_FACTIONS.includes(b)) {
return { ok: false, error: `factions[${i}]: both are Rust's own, and RunicNPC does not change how Rust's NPCs treat each other` }
}
if (!RELATIONS.includes(relation)) return { ok: false, error: `factions[${i}]: '${relation}' is not hostile, neutral or allied` }
const key = pairKey(a, b)
if (seen.has(key)) return { ok: false, error: `factions[${i}]: ${a} and ${b} are given twice (one row is both ways, D268)` }
seen.add(key)
rows.push(a < b ? { a, b, relation } : { a: b, b: a, relation })
}
rows.sort((x, y) => x.a.localeCompare(y.a) || x.b.localeCompare(y.b))
return { ok: true, value: rows }
}
function num(value) {
if (value === null || value === undefined || value === '') return NaN
const n = Number(value)
return Number.isFinite(n) ? n : NaN
}
/** `wander`, `monument` or `route:<name>` (D233). */
function parseMode(mode) {
const text = String(mode === undefined || mode === null ? '' : mode).trim()
if (text === 'wander' || text === 'monument') return { kind: text }
const m = /^route:([a-z0-9_-]{1,40})$/.exec(text)
return m ? { kind: 'route', route: m[1] } : null
}
/** A movement, checked: `{ ok, value }` or `{ ok: false, error }`. */
function checkMovement(input) {
const m = input || {}
const mode = String(m.mode === undefined || m.mode === null ? '' : m.mode).trim()
const parsed = parseMode(mode)
if (!parsed) return { ok: false, error: `movement.mode: '${mode}' is not wander, monument or route:<name>` }
const radius = m.radius === undefined || m.radius === null || m.radius === '' ? (parsed.kind === 'wander' ? 20 : 0) : num(m.radius)
if (Number.isNaN(radius) || radius < 0) return { ok: false, error: 'movement.radius: a number of metres' }
if (parsed.kind === 'wander' && !(radius > 0)) return { ok: false, error: "movement.radius: a wanderer's radius must be above 0" }
return { ok: true, value: { mode, radius } }
}
/**
* Checks a profile's body as the admin form sends it, merged over RunicNPC's
* defaults. Resolves `{ ok: true, value }` with the body RunicNPC will read, or
* `{ ok: false, error }` with RunicNPC's own sentence for the first problem.
*/
function checkBody(input) {
const b = { ...defaults(), ...(input || {}) }
const names = Array.isArray(b.names) ? b.names.map((n) => String(n === null || n === undefined ? '' : n).trim()) : null
if (!names || names.length === 0 || names.some((n) => !n)) return { ok: false, error: 'names: give at least one, and no blank ones' }
if (names.length > NAMES_MAX) return { ok: false, error: `names: at most ${NAMES_MAX}` }
if (names.some((n) => n.length > DISPLAY_NAME_MAX)) return { ok: false, error: `names: each at most ${DISPLAY_NAME_MAX} characters` }
const kits = Array.isArray(b.kits) ? [...new Set(b.kits.map((k) => String(k === null || k === undefined ? '' : k).trim()).filter(Boolean))] : null
if (!kits || kits.length === 0) return { ok: false, error: 'kits: give at least one; Kits is how an NPC is equipped (D217)' }
if (kits.length > KITS_MAX) return { ok: false, error: `kits: at most ${KITS_MAX}` }
const prefab = String(b.prefab || '').trim()
if (!PREFAB_RULE.test(prefab)) return { ok: false, error: `prefab: '${prefab}' is not one of Rust's scientist prefabs (scientistnpc_*)` }
if (!ROLES.includes(b.role)) return { ok: false, error: `role: '${b.role}' is not roamer, sentry or guard` }
const movement = checkMovement(b.movement)
if (!movement.ok) return movement
const health = num(b.health)
if (!(health > 0)) return { ok: false, error: 'health: must be above 0' }
const damageDealt = num(b.damageDealt)
if (Number.isNaN(damageDealt) || damageDealt < 0) return { ok: false, error: 'damageDealt: must not be negative' }
const taken = b.damageTaken || {}
const damageTaken = { head: num(taken.head), body: num(taken.body), legs: num(taken.legs) }
if (Object.values(damageTaken).some((v) => Number.isNaN(v) || v < 0)) return { ok: false, error: 'damageTaken: head, body and legs must not be negative' }
const aimCone = num(b.aimCone)
if (Number.isNaN(aimCone) || aimCone < 0) return { ok: false, error: 'aimCone: must not be negative' }
const r = b.ranges || {}
const ranges = { sense: num(r.sense), loseTarget: num(r.loseTarget), chase: num(r.chase), attack: num(r.attack) }
if (!(ranges.sense > 0) || !(ranges.attack > 0) || !(ranges.loseTarget >= ranges.sense) || !(ranges.chase >= 0)) {
return { ok: false, error: 'ranges: sense and attack above 0, loseTarget at least sense, chase not negative' }
}
const visionCone = num(b.visionCone)
if (!(visionCone >= -1 && visionCone <= 1)) return { ok: false, error: 'visionCone: between -1 and 1' }
const sleepDistance = num(b.sleepDistance)
if (!(sleepDistance >= 0)) return { ok: false, error: 'sleepDistance: 0 (never sleeps) or more' }
const thresholds = Array.isArray(b.healthThresholds) ? b.healthThresholds.map(num) : null
if (!thresholds || thresholds.some((t) => !(t > 0 && t < 1))) return { ok: false, error: 'healthThresholds: fractions between 0 and 1' }
if (thresholds.length > THRESHOLDS_MAX) return { ok: false, error: `healthThresholds: at most ${THRESHOLDS_MAX}` }
// ---- stage 5, in RunicNPC's order and words ----
const faction = b.faction === undefined || b.faction === null || String(b.faction).trim() === '' ? null : String(b.faction).trim()
if (faction !== null && (!NAME_RULE.test(faction) || BUILT_IN_FACTIONS.includes(faction))) {
return { ok: false, error: `faction: '${faction}' must be 1–40 of a-z, 0-9, _ and -, and not scientists or animals (Rust's own)` }
}
const rel = b.relations === undefined || b.relations === null ? {} : b.relations
if (typeof rel !== 'object' || Array.isArray(rel)) return { ok: false, error: 'relations: an object, even an empty one' }
const relations = {}
for (const [key, value] of Object.entries(rel)) {
if (!isFactionKey(key, true)) return { ok: false, error: `relations: '${key}' is not a faction, scientists, animals or profile:<name>` }
if (!RELATIONS.includes(value)) return { ok: false, error: `relations.${key}: '${value}' is not hostile, neutral or allied` }
relations[key] = value
}
if (Object.keys(relations).length > RELATIONS_MAX) return { ok: false, error: `relations: at most ${RELATIONS_MAX}` }
const alertRadius = num(b.alertRadius)
if (!(alertRadius >= 0)) return { ok: false, error: 'alertRadius: 0 (off) or more' }
if (!TURRETS.includes(b.turrets)) return { ok: false, error: `turrets: '${b.turrets}' is not default, ignore or always` }
if (typeof b.hurtByPlayers !== 'boolean' || typeof b.hurtsPlayers !== 'boolean') return { ok: false, error: 'hurtByPlayers and hurtsPlayers: true or false' }
const kit = b.kitUse === undefined || b.kitUse === null ? {} : b.kitUse
if (typeof kit !== 'object' || Array.isArray(kit)) return { ok: false, error: 'kitUse: an object, even an empty one' }
const kitUse = {}
for (const k of KIT_USES) kitUse[k] = kit[k] === true
return {
ok: true,
value: {
names,
kits,
prefab,
role: b.role,
movement: movement.value,
health,
damageDealt,
damageTaken,
aimCone,
ranges,
visionCone,
sleepDistance,
healthThresholds: [...new Set(thresholds)].sort((x, y) => y - x),
faction,
relations,
alertRadius,
turrets: b.turrets,
hurtByPlayers: b.hurtByPlayers,
hurtsPlayers: b.hurtsPlayers,
kitUse,
},
}
}
/**
* A profile read from a server's own RunicNPC (D244), made into a body this
* module will save. Whatever RunicNPC holds is kept as it is; only a shape this
* module could not push back is refused, with the reason.
*/
function fromServer(name, body) {
if (!NAME_RULE.test(String(name || ''))) return { ok: false, error: `'${name}' is not a profile name RunicNPC could hold` }
return checkBody(body || {})
}
/** A player-facing label for a profile: its first NPC name, else its own name. */
function labelOf(profile) {
const names = profile && profile.body && Array.isArray(profile.body.names) ? profile.body.names : []
return names[0] || (profile && profile.name) || ''
}
module.exports = {
NAME_RULE,
PREFAB_RULE,
PREFABS,
ROLES,
BUILT_IN_FACTIONS,
RELATIONS,
TURRETS,
KIT_USES,
isFactionKey,
checkFactions,
KILLS_SCOPES,
defaults,
parseMode,
checkMovement,
checkBody,
fromServer,
labelOf,
}

View File

@@ -0,0 +1,334 @@
// ── SQL for RunicNPC profiles, their push, and per-profile kills ───────────
//
// Profiles are this module's own (runicnpc PLAN.md stage 4). Placements are
// NOT stored here: they live on each server (D222), and the site reads and
// edits them through the bridge. What each server said about RunicNPC is read
// out of the state row's stored hello (`raw`), so the pages work while a server
// is off.
const core = require('../../core')
const PROFILES = 'rust_npc_profiles'
const PROFILE_SERVERS = 'rust_npc_profile_servers'
const SYNC = 'rust_npc_sync'
const KILLS = 'rust_npc_kills'
const FACTIONS = 'rust_npc_factions'
const SERVERS = 'rust_servers'
const STATE = 'rust_server_state'
const PLAYERS = 'rust_players'
/** The driver hands JSON_EXTRACT and TEXT back as strings. A bad value is no value. */
function json(value, fallback) {
if (value === null || value === undefined) return fallback
if (typeof value !== 'string') return value
try {
return JSON.parse(value)
} catch {
return fallback
}
}
function shape(row, serverIds) {
return {
id: Number(row.id),
name: row.name,
body: json(row.body, {}),
allServers: Boolean(row.allServers),
servers: serverIds,
killsScope: row.killsScope || 'server',
adoptedFrom: row.adoptedFrom || null,
replaced: Boolean(row.replaced),
updatedAt: row.updatedAt ? new Date(row.updatedAt).toISOString() : null,
}
}
const COLUMNS = `id, name, body, all_servers AS allServers, kills_scope AS killsScope,
adopted_from AS adoptedFrom, replaced, updated_at AS updatedAt`
/** Every profile, with the servers each names, by name. */
async function listProfiles() {
const [rows, links] = await Promise.all([
core.query(`SELECT ${COLUMNS} FROM ${PROFILES} ORDER BY name ASC, id ASC`),
core.query(`SELECT profile_id AS profileId, server_id AS serverId FROM ${PROFILE_SERVERS} ORDER BY server_id ASC`),
])
const by = new Map()
for (const l of links) {
const id = Number(l.profileId)
if (!by.has(id)) by.set(id, [])
by.get(id).push(l.serverId)
}
return rows.map((r) => shape(r, by.get(Number(r.id)) || []))
}
async function getProfile(id) {
const rows = await core.query(`SELECT ${COLUMNS} FROM ${PROFILES} WHERE id = ?`, [id])
if (!rows[0]) return null
const links = await core.query(`SELECT server_id AS serverId FROM ${PROFILE_SERVERS} WHERE profile_id = ? ORDER BY server_id ASC`, [id])
return shape(rows[0], links.map((l) => l.serverId))
}
/**
* Writes one profile and replaces its server list. The model has checked the
* servers and the name first, so nothing below has anything left to refuse.
*/
async function saveProfile({ id = null, name, body, allServers, servers, killsScope, adoptedFrom = null, replaced = false }, userId = null) {
let profileId = id
const args = [name, JSON.stringify(body), allServers ? 1 : 0, killsScope, replaced ? 1 : 0]
if (profileId) {
await core.query(
`UPDATE ${PROFILES} SET name = ?, body = ?, all_servers = ?, kills_scope = ?, replaced = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
[...args, profileId],
)
await core.query(`DELETE FROM ${PROFILE_SERVERS} WHERE profile_id = ?`, [profileId])
} else {
const res = await core.query(
`INSERT INTO ${PROFILES} (name, body, all_servers, kills_scope, replaced, adopted_from, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)`,
[...args, adoptedFrom, userId],
)
profileId = Number(res.insertId)
}
if (!allServers && servers.length > 0) {
await core.query(
`INSERT INTO ${PROFILE_SERVERS} (profile_id, server_id) VALUES ${servers.map(() => '(?, ?)').join(', ')}`,
servers.flatMap((serverId) => [profileId, serverId]),
)
}
return profileId
}
async function deleteProfile(id) {
await core.query(`DELETE FROM ${PROFILES} WHERE id = ?`, [id])
}
/**
* Each configured server, in the operator's order, with what its last status
* said about RunicNPC (`{ loaded, version, api }`, null for a server that never
* said) and about its connection.
*/
async function listNpcServers() {
const rows = await core.query(
`SELECT s.id, s.name, s.enabled, st.online, st.boot_id AS bootId,
JSON_EXTRACT(st.raw, '$.integrations.runicNpc') AS runicNpc,
JSON_EXTRACT(st.raw, '$.worldReady') AS worldReady
FROM ${SERVERS} s
LEFT JOIN ${STATE} st ON st.server_id = s.id
ORDER BY s.sort_order ASC, s.id ASC`,
)
return rows.map((r) => {
const npc = json(r.runicNpc, null)
const ready = json(r.worldReady, null)
return {
id: r.id,
name: r.name,
enabled: Boolean(r.enabled),
online: r.online === null || r.online === undefined ? null : Boolean(Number(r.online)),
bootId: r.bootId || null,
worldReady: ready === null ? null : Boolean(ready),
runicNpc: npc && typeof npc === 'object' ? { loaded: Boolean(npc.loaded), version: npc.version || null, api: Number(npc.api) || 0 } : null,
}
})
}
// ── The push's record ───────────────────────────────────────────────────────
function syncShape(r) {
return {
serverId: r.serverId,
adoptedAt: r.adoptedAt ? new Date(r.adoptedAt).toISOString() : null,
state: r.state,
syncedHash: r.syncedHash || null,
bootId: r.bootId || null,
pushed: json(r.pushed, {}),
refused: json(r.refused, {}),
error: r.error || null,
lastAttemptAt: r.lastAttemptAt ? new Date(r.lastAttemptAt).toISOString() : null,
syncedAt: r.syncedAt ? new Date(r.syncedAt).toISOString() : null,
}
}
const SYNC_COLUMNS = `server_id AS serverId, adopted_at AS adoptedAt, state, synced_hash AS syncedHash, boot_id AS bootId,
pushed, refused, error, last_attempt_at AS lastAttemptAt, synced_at AS syncedAt`
async function listSync() {
return (await core.query(`SELECT ${SYNC_COLUMNS} FROM ${SYNC}`)).map(syncShape)
}
async function getSync(serverId) {
const rows = await core.query(`SELECT ${SYNC_COLUMNS} FROM ${SYNC} WHERE server_id = ?`, [serverId])
return rows[0] ? syncShape(rows[0]) : null
}
/** Records that a server's own profiles were read and imported (D244). Once. */
async function markAdopted(serverId) {
await core.query(
`INSERT INTO ${SYNC} (server_id, adopted_at) VALUES (?, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE adopted_at = COALESCE(adopted_at, CURRENT_TIMESTAMP)`,
[serverId],
)
}
/** One push's outcome. A failure keeps the last good hash and map, so a retry is still a change. */
async function putSync(serverId, { state, syncedHash = null, bootId = null, pushed = null, refused = null, error = null }) {
const ok = state === 'ok'
await core.query(
`INSERT INTO ${SYNC} (server_id, state, synced_hash, boot_id, pushed, refused, error, last_attempt_at, synced_at)
VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ${ok ? 'CURRENT_TIMESTAMP' : 'NULL'})
ON DUPLICATE KEY UPDATE state = VALUES(state),
synced_hash = ${ok ? 'VALUES(synced_hash)' : 'synced_hash'},
boot_id = ${ok ? 'VALUES(boot_id)' : 'boot_id'},
pushed = ${ok ? 'VALUES(pushed)' : 'pushed'},
refused = ${ok ? 'VALUES(refused)' : 'refused'},
error = VALUES(error),
last_attempt_at = CURRENT_TIMESTAMP,
synced_at = ${ok ? 'CURRENT_TIMESTAMP' : 'synced_at'}`,
[serverId, state, syncedHash, bootId, pushed ? JSON.stringify(pushed) : null, refused ? JSON.stringify(refused) : null, error ? String(error).slice(0, 191) : null],
)
}
/** Asks for a push on the next tick, after an admin's edit. */
async function markDirty(serverIds = null) {
if (Array.isArray(serverIds) && serverIds.length === 0) return
if (serverIds) {
await core.query(`UPDATE ${SYNC} SET synced_hash = NULL WHERE server_id IN (${serverIds.map(() => '?').join(', ')})`, serverIds)
} else {
await core.query(`UPDATE ${SYNC} SET synced_hash = NULL`)
}
}
// ── The faction table (stage 5, D254) ─────────────────────────────────────
/** Every pair, `a` before `b`, sorted. */
async function listFactions() {
return (await core.query(`SELECT a, b, relation FROM ${FACTIONS} ORDER BY a ASC, b ASC`)).map((r) => ({ a: r.a, b: r.b, relation: r.relation }))
}
/** Replaces the whole table, in one transaction; the caller has checked it (`checkFactions`). */
async function replaceFactions(rows) {
const conn = await core.pool.getConnection()
try {
await conn.beginTransaction()
await conn.query(`DELETE FROM ${FACTIONS}`)
for (const r of rows) await conn.query(`INSERT INTO ${FACTIONS} (a, b, relation) VALUES (?, ?, ?)`, [r.a, r.b, r.relation])
await conn.commit()
} catch (err) {
await conn.rollback().catch(() => {})
throw err
} finally {
conn.release()
}
}
// ── Kills (D247) ────────────────────────────────────────────────────────────
async function addKills({ serverId, wipeId, steamId }, profile, siteProfileId, kills) {
if (!serverId || !steamId || !profile || !(kills > 0)) return
await core.query(
`INSERT INTO ${KILLS} (server_id, wipe_id, steam_id, profile, site_profile_id, kills)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE kills = kills + VALUES(kills)`,
[serverId, wipeId || '', steamId, String(profile).slice(0, 40), Number(siteProfileId) || 0, kills],
)
}
/**
* The WHERE clause for one profile's kills, by its scope (D247), and the page's
* wipe:
*
* `server` that name, on the server being looked at
* `name` that name, on every server
* `profile` that site profile, on every server it was pushed to
*
* `wipe`: a wipe id limits the server being looked at to that wipe; for a scope
* that reaches other servers, their CURRENT wipe is counted when the page shows
* this server's current wipe, and only this server's rows otherwise (another
* server's past wipes are not this page's). `null` is all time.
*/
function scopeWhere({ scope, name, siteProfileId, serverId, wipeId = null, currentWipe = false }) {
const where = []
const args = []
if (scope === 'profile') {
where.push('k.site_profile_id = ?')
args.push(siteProfileId)
} else {
where.push('k.profile = ?')
args.push(name)
}
if (scope === 'server') {
where.push('k.server_id = ?')
args.push(serverId)
if (wipeId !== null) {
where.push('k.wipe_id = ?')
args.push(wipeId)
}
} else if (wipeId !== null) {
if (currentWipe) {
where.push(`k.wipe_id = (SELECT COALESCE(st.wipe_id, '') FROM ${STATE} st WHERE st.server_id = k.server_id)`)
} else {
where.push('k.server_id = ? AND k.wipe_id = ?')
args.push(serverId, wipeId)
}
}
return { sql: where.join(' AND '), args }
}
/** One profile's ranking, most kills first, ties by Steam id as every other board. */
async function ranking(scope, limit = 50) {
const w = scopeWhere(scope)
return (await core.query(
`SELECT k.steam_id AS steamId, p.name, SUM(k.kills) AS kills
FROM ${KILLS} k
LEFT JOIN ${PLAYERS} p ON p.steam_id = k.steam_id
WHERE ${w.sql}
GROUP BY k.steam_id, p.name
HAVING kills > 0
ORDER BY kills DESC, k.steam_id ASC
LIMIT ?`,
[...w.args, Math.max(1, Math.min(200, Number(limit) || 50))],
)).map((r) => ({ steamId: String(r.steamId), name: r.name || null, value: Number(r.kills) || 0 }))
}
/** One player's kills by profile name on one server, for the wipe (or all time). */
async function playerKills({ serverId, steamId, wipeId = null }) {
return (await core.query(
`SELECT profile, SUM(kills) AS kills
FROM ${KILLS}
WHERE server_id = ? AND steam_id = ? ${wipeId !== null ? 'AND wipe_id = ?' : ''}
GROUP BY profile
ORDER BY kills DESC, profile ASC`,
wipeId !== null ? [serverId, steamId, wipeId] : [serverId, steamId],
)).map((r) => ({ profile: r.profile, kills: Number(r.kills) || 0 }))
}
/** A player's kills by server and profile name, current wipes, for their own account page. */
async function ownKills(steamIds) {
if (!steamIds || steamIds.length === 0) return []
return (await core.query(
`SELECT k.server_id AS serverId, k.profile, SUM(k.kills) AS kills
FROM ${KILLS} k
JOIN ${STATE} st ON st.server_id = k.server_id AND k.wipe_id = COALESCE(st.wipe_id, '')
WHERE k.steam_id IN (${steamIds.map(() => '?').join(', ')})
GROUP BY k.server_id, k.profile
ORDER BY k.server_id ASC, kills DESC`,
steamIds,
)).map((r) => ({ serverId: r.serverId, profile: r.profile, kills: Number(r.kills) || 0 }))
}
module.exports = {
listProfiles,
getProfile,
saveProfile,
deleteProfile,
listNpcServers,
listSync,
getSync,
markAdopted,
putSync,
markDirty,
listFactions,
replaceFactions,
addKills,
scopeWhere,
ranking,
playerKills,
ownKills,
}

View File

@@ -0,0 +1,509 @@
// ── RunicNPC profiles and placements (docs/runicnpc/PLAN.md stage 4) ───────
//
// Profiles are the site's: authored here, for one server, several, or the
// fleet (the zone-presets shape, D210), and pushed to each server's RunicNPC,
// which is then managed by this site (D221). Before the first push to a server
// its own profiles are read and adopted (D244); one whose name a site profile
// already has there is kept as "replaced" (D251).
//
// Placements are the SERVER's (D222). This model reads and edits them through
// the bridge and keeps no copy: a server that is off has no placements to show,
// and says so.
const crypto = require('node:crypto')
const client = require('../../sidecarClient')
const servers = require('../servers/servers.model')
const serversDb = require('../servers/servers.db')
const db = require('./npcs.db')
const shape = require('./npcProfile')
/** The RunicNPC API the bridge's `npc.*` commands need: 3 for placements (D249), 4 for the faction table and an event's orders (stage 5). */
const API_NEEDED = 4
class NpcError extends Error {
constructor(message, status = 400) {
super(message)
this.status = status
}
}
function covers(profile, serverId) {
return profile.allServers || profile.servers.includes(serverId)
}
/** Profiles that are pushed: every one not kept aside as replaced (D251). */
function active(profiles) {
return profiles.filter((p) => !p.replaced)
}
/** Whether a server can take `npc.*` commands, from what it last said. */
function npcReady(server) {
return Boolean(server && server.runicNpc && server.runicNpc.loaded && server.runicNpc.api >= API_NEEDED)
}
/** Why a server cannot, in words, or null. */
function npcAbsence(server) {
if (!server) return 'no such server'
if (!server.runicNpc) return 'it has not said whether it has RunicNPC (a bridge older than protocol 13, or never reached)'
if (!server.runicNpc.loaded) return 'RunicNPC is not loaded on it'
if (server.runicNpc.api < API_NEEDED) return `its RunicNPC ${server.runicNpc.version || ''} answers API ${server.runicNpc.api}, and the site needs ${API_NEEDED}`.replace(' ', ' ')
return null
}
// ── What a server is sent ───────────────────────────────────────────────────
/**
* The profiles one server is pushed, as RunicNPC reads them, and the name → site
* profile id map a kill is credited through (D247). Sorted, so an unchanged set
* hashes the same on every tick. The faction table (stage 5, D254) is the
* site's one table, sent to every server with its profiles and hashed with them,
* so an edit to it is pushed like an edit to a profile.
*/
function desiredFor(serverId, profiles, factions = []) {
const set = {}
const map = {}
for (const p of active(profiles).filter((x) => covers(x, serverId)).sort((a, b) => a.name.localeCompare(b.name) || a.id - b.id)) {
if (set[p.name]) continue
set[p.name] = p.body
map[p.name] = p.id
}
const rows = (factions || []).map((f) => ({ a: f.a, b: f.b, relation: f.relation }))
const hash = crypto
.createHash('sha256')
.update(JSON.stringify([Object.keys(set).sort().map((n) => [n, set[n]]), rows]))
.digest('hex')
return { profiles: set, factions: rows, map, hash }
}
// ── Adoption (D244, D251) ───────────────────────────────────────────────────
/**
* Imports a server's own profiles as profiles for that server alone, before the
* site first pushes there, so nothing on it changes. Where a site profile of the
* same name already covers it, the site's wins (D251): the server's own is kept,
* marked replaced, for an admin to restore. Returns what it did, per name.
*/
async function adopt(serverId, theirs, userId = null) {
const existing = await db.listProfiles()
const done = []
for (const [name, body] of Object.entries(theirs || {}).sort(([a], [b]) => a.localeCompare(b))) {
if (!shape.NAME_RULE.test(name)) {
done.push({ name, outcome: 'skipped', reason: 'not a name RunicNPC could hold' })
continue
}
const checked = shape.checkBody(body || {})
// Kept whole even when this module would refuse it on its form: adoption
// changes nothing on the server, and RunicNPC already said whether it uses it.
const kept = checked.ok ? checked.value : { ...shape.defaults(), ...(body || {}) }
const clash = active(existing).find((p) => p.name === name && covers(p, serverId))
await db.saveProfile(
{ name, body: kept, allServers: false, servers: [serverId], killsScope: 'server', adoptedFrom: serverId, replaced: Boolean(clash) },
userId,
)
done.push({ name, outcome: clash ? 'replaced' : 'adopted', ...(clash ? { by: clash.id } : {}) })
}
await db.markAdopted(serverId)
return done
}
/**
* A standalone server's own faction table, adopted with its profiles (D244):
* each pair the site's table does not already set is added, and where the site
* sets a pair the site wins (D251). Returns the pairs added.
*/
async function adoptFactions(theirs) {
const checked = shape.checkFactions(Array.isArray(theirs) ? theirs : [])
if (!checked.ok || checked.value.length === 0) return []
const mine = await db.listFactions()
const have = new Set(mine.map((f) => `${f.a}|${f.b}`))
const added = checked.value.filter((f) => !have.has(`${f.a}|${f.b}`))
if (added.length) await db.replaceFactions(shape.checkFactions([...mine, ...added]).value)
return added
}
// ── The faction table (stage 5, D254, D268) ─────────────────────────────────
async function getFactions() {
return db.listFactions()
}
/** Replaces the site's faction table, checked as RunicNPC checks it, and pushes it to every server. */
async function setFactions(input) {
const checked = shape.checkFactions(input)
if (!checked.ok) throw new NpcError(checked.error)
await db.replaceFactions(checked.value)
await db.markDirty(null)
return db.listFactions()
}
// ── The admin page ──────────────────────────────────────────────────────────
async function describe() {
const [list, profiles, sync, factions] = await Promise.all([db.listNpcServers(), db.listProfiles(), db.listSync(), db.listFactions()])
const syncBy = new Map(sync.map((s) => [s.serverId, s]))
return {
servers: list.map((s) => {
const row = syncBy.get(s.id) || null
return {
...s,
ready: npcReady(s),
absence: npcAbsence(s),
sync: row && { state: row.state, adoptedAt: row.adoptedAt, syncedAt: row.syncedAt, refused: row.refused, error: row.error },
}
}),
profiles: profiles.map((p) => ({ ...p, label: shape.labelOf(p) })),
prefabs: shape.PREFABS,
killsScopes: shape.KILLS_SCOPES,
defaults: shape.defaults(),
// Stage 5: the faction table, the factions the profiles name, and what the form offers.
factions,
factionNames: [...new Set(profiles.map((p) => p.body && p.body.faction).filter(Boolean))].sort(),
builtInFactions: shape.BUILT_IN_FACTIONS,
roles: shape.ROLES,
turrets: shape.TURRETS,
kitUses: shape.KIT_USES,
}
}
/**
* The kits each covered server that answers has; a server that does not answer
* is left to RunicNPC, which refuses a missing kit when the profile is pushed.
*/
async function checkKits(kits, covered) {
for (const s of covered) {
if (!s.enabled) continue
const row = await serversDb.getServer(s.id)
if (!row) continue
const result = await client.kits(servers.withToken(row))
const data = result.ok ? result.data || {} : null
if (!data || data.kind !== 'kits.list') continue
const have = new Set((data.kits || []).map((k) => String(k && k.name).toLowerCase()))
const missing = kits.find((k) => !have.has(k.toLowerCase()))
if (missing) throw new NpcError(`kits: ${s.name || s.id} has no kit '${missing}'`)
}
}
async function validate(input, id = null) {
const name = String((input && input.name) || '').trim()
if (!shape.NAME_RULE.test(name)) throw new NpcError('name: 1 to 40 of a-z, 0-9, _ and -, as RunicNPC names a profile')
const allServers = input.allServers === true
const requested = Array.isArray(input.servers) ? [...new Set(input.servers.map(String))] : []
if (!allServers && requested.length === 0) throw new NpcError('a profile is for at least one server, or for every server')
const killsScope = input.killsScope === undefined || input.killsScope === null || input.killsScope === '' ? 'server' : String(input.killsScope)
if (!shape.KILLS_SCOPES.includes(killsScope)) throw new NpcError(`killsScope: ${shape.KILLS_SCOPES.join(', ')}`)
const list = await db.listNpcServers()
const byId = new Map(list.map((s) => [s.id, s]))
for (const s of requested) {
if (!byId.has(s)) throw new NpcError(`no server "${s}"`, 404)
}
const checked = shape.checkBody(input.body)
if (!checked.ok) throw new NpcError(checked.error)
const mine = { allServers, servers: requested }
const others = active(await db.listProfiles()).filter((p) => p.id !== id && p.name === name)
for (const other of others) {
if (allServers && other.allServers) throw new NpcError(`a profile called "${name}" is already on every server`, 409)
const shared = list.find((s) => covers(mine, s.id) && covers(other, s.id))
if (shared) throw new NpcError(`a profile called "${name}" is already on ${shared.name || shared.id}`, 409)
}
const covered = allServers ? list : requested.map((s) => byId.get(s))
await checkKits(checked.value.kits, covered)
return { name, body: checked.value, allServers, servers: allServers ? [] : requested, killsScope }
}
/** The servers whose pushed set a change to this profile moves. */
function reach(profile) {
return profile.allServers ? null : profile.servers
}
async function create(input, userId = null) {
const clean = await validate(input)
const id = await db.saveProfile(clean, userId)
await db.markDirty(clean.allServers ? null : clean.servers)
return db.getProfile(id)
}
async function update(id, input) {
const existing = await db.getProfile(id)
if (!existing) throw new NpcError('no such profile', 404)
if (existing.replaced) throw new NpcError('this profile is kept aside as replaced (D251): restore it before editing it', 409)
const clean = await validate(input, existing.id)
await db.saveProfile({ ...clean, id: existing.id })
const before = reach(existing)
const after = clean.allServers ? null : clean.servers
await db.markDirty(before === null || after === null ? null : [...new Set([...before, ...after])])
return db.getProfile(existing.id)
}
/**
* Deletes a profile. Its placements on each server wait, and spawn again if a
* profile of that name returns (D237).
*/
async function remove(id) {
const existing = await db.getProfile(id)
if (!existing) throw new NpcError('no such profile', 404)
await db.deleteProfile(existing.id)
if (!existing.replaced) await db.markDirty(reach(existing))
return true
}
/**
* Brings a replaced profile back into use on its server (D251), when no site
* profile of its name covers that server any more.
*/
async function restore(id) {
const existing = await db.getProfile(id)
if (!existing) throw new NpcError('no such profile', 404)
if (!existing.replaced) throw new NpcError('this profile is in use already')
const clash = active(await db.listProfiles()).find((p) => p.name === existing.name && existing.servers.some((s) => covers(p, s)))
if (clash) {
const names = new Map((await db.listNpcServers()).map((srv) => [srv.id, srv.name || srv.id]))
const where = existing.servers.map((id) => names.get(id) || id).join(', ')
throw new NpcError(`the site's profile "${clash.name}" is on ${where}: change its servers or delete it first`, 409)
}
await db.saveProfile({ ...existing, replaced: false })
await db.markDirty(existing.servers)
return db.getProfile(existing.id)
}
// ── Placements, through the bridge (D245, D246) ─────────────────────────────
/** A refusal from the bridge, as an HTTP status and its own sentence. */
const REFUSALS = {
'runicnpc-missing': 409,
'runicnpc-old': 409,
'not-found': 404,
malformed: 400,
refused: 400,
}
async function reachable(serverId) {
const row = await serversDb.getServer(serverId)
if (!row) throw new NpcError(`no server "${serverId}"`, 404)
if (!row.enabled) throw new NpcError(`the Rust server "${row.name || serverId}" is switched off`, 409)
return servers.withToken(row)
}
function transport(server, result) {
const name = server.name || server.id
if (result.status === 'http-503') return new NpcError(`${name} has no game connected, so its placements cannot be read or changed now`, 503)
if (result.status === 'timeout' || result.status === 'http-504') return new NpcError(`${name} did not answer in time`, 504)
if (result.status === 'protocol-mismatch') return new NpcError(`${name}'s sidecar speaks a different protocol: update the module or the sidecar`, 502)
return new NpcError(`${name} could not be reached (${result.status})`, 502)
}
function answer(server, result, kind) {
if (!result.ok) throw transport(server, result)
const data = result.data || {}
if (data.kind === 'npc.error') throw new NpcError(data.message || data.reason || 'refused', REFUSALS[data.reason] || 400)
if (data.kind !== kind) throw new NpcError(`${server.name || server.id} answered something else (${data.kind || 'nothing'})`, 502)
return data
}
/**
* One server's placements, with its routes (for the movement picker) and the
* cost warning (D227). Each placement: its id, values, how many of its NPCs
* are alive, what it waits for (D237) and its note (D239).
*/
async function listPlacements(serverId) {
const server = await reachable(serverId)
const data = answer(server, await client.npcPlacements(server), 'npc.placements')
return {
placements: (data.placements || []).map((p) => ({
id: p.id,
placement: p.placement || {},
alive: Number(p.alive) || 0,
waiting: p.waiting || null,
note: p.note || null,
lastError: p.lastError || null,
})),
routes: Array.isArray(data.routes) ? data.routes : [],
cost: data.cost || null,
}
}
/** A placement's values from the form (D246): `/rnpc place`'s options, checked as RunicNPC does. */
function placementBody(input, { position }) {
const p = input || {}
const profile = String(p.profile || '').trim()
if (!shape.NAME_RULE.test(profile)) throw new NpcError('profile: a profile name')
const count = p.count === undefined || p.count === null || p.count === '' ? 1 : Number(p.count)
if (!Number.isInteger(count) || count < 1 || count > 50) throw new NpcError('count: a whole number, 1 to 50')
const respawn = p.respawn === undefined || p.respawn === null || p.respawn === '' ? 300 : Number(p.respawn)
if (!Number.isFinite(respawn) || respawn < 1 || respawn > 86400) throw new NpcError('respawn: seconds, 1 to 86400')
const respawnMode = p.respawnMode === undefined || p.respawnMode === null || p.respawnMode === '' ? 'each' : String(p.respawnMode)
if (respawnMode !== 'each' && respawnMode !== 'group') throw new NpcError('respawnMode: each or group')
const yaw = p.yaw === undefined || p.yaw === null || p.yaw === '' ? 0 : Number(p.yaw)
if (!Number.isFinite(yaw)) throw new NpcError('yaw: degrees')
const body = { profile, position, yaw, count, respawn, respawnMode }
if (p.movement && p.movement.mode) {
const m = shape.checkMovement(p.movement)
if (!m.ok) throw new NpcError(m.error)
body.movement = m.value
}
// D272: a ZoneManager zone its NPCs never leave. The server checks that the
// zone exists and holds the spot, and refuses the placement otherwise.
const tether = p.tether === undefined || p.tether === null ? '' : String(p.tether).trim()
if (tether) {
if (!TETHER_RULE.test(tether)) throw new NpcError('tether: a ZoneManager zone id')
body.tether = tether
}
return body
}
/** RunicNPC's rule for a zone id: one plain word. */
const TETHER_RULE = /^[A-Za-z0-9_.:-]{1,64}$/
function point(raw, { withY }) {
const r = raw || {}
const x = Number(r.x)
const z = Number(r.z)
if (!Number.isFinite(x) || !Number.isFinite(z)) throw new NpcError('position: x and z')
if (!withY) return { x, z }
const y = Number(r.y)
if (!Number.isFinite(y)) throw new NpcError('position: x, y and z')
return { x, y, z }
}
/**
* A new placement from a point on the live map (D245): x and z only. The server
* puts it on the ground there, checks it against the navmesh, and names it as in
* game (D246); the answer carries the name, where it landed and the cost warning.
*/
async function addPlacement(serverId, input) {
const server = await reachable(serverId)
const body = placementBody(input, { position: point(input && input.position, { withY: false }) })
const data = answer(server, await client.npcPlacement(server, { op: 'add', placement: body }), 'npc.ok')
return { id: data.id, position: data.position || null, built: Boolean(data.built), cost: data.cost || null }
}
/** New values for a placement. Its spot is kept unless the form sends one whole. */
async function setPlacement(serverId, id, input) {
const server = await reachable(serverId)
const current = (await listPlacements(serverId)).placements.find((p) => p.id === id)
if (!current) throw new NpcError(`there is no placement '${id}' on ${server.name || server.id}`, 404)
const position = input && input.position ? point(input.position, { withY: true }) : current.placement.position
const body = placementBody({ yaw: current.placement.yaw, ...input }, { position })
const data = answer(server, await client.npcPlacement(server, { op: 'set', id, placement: body }), 'npc.ok')
return { id: data.id || id, cost: data.cost || null }
}
async function changePlacement(serverId, op, body) {
const server = await reachable(serverId)
const data = answer(server, await client.npcPlacement(server, { op, ...body }), 'npc.ok')
return data
}
const removePlacement = (serverId, id) => changePlacement(serverId, 'remove', { id })
const renamePlacement = (serverId, id, to) => {
if (!shape.NAME_RULE.test(String(to || ''))) throw new NpcError('to: 1 to 40 of a-z, 0-9, _ and -')
return changePlacement(serverId, 'rename', { id, to })
}
const respawnPlacement = (serverId, id) => changePlacement(serverId, 'respawn', { id })
// ── Events: the "Place NPCs" picker (D243) ─────────────────────────────────
/** A profile's value in the picker: `profile:<name>`, beside Rust's own `npc.*`. */
const PROFILE_PREFIX = 'profile:'
/**
* The site's profiles, first, grouped, for any server that has RunicNPC. A site
* with no such server offers none (D243: Rust's own only until stage 9).
*/
async function optionRows() {
const [profiles, list] = await Promise.all([db.listProfiles(), db.listNpcServers()])
const ready = list.filter(npcReady)
if (ready.length === 0) return []
const seen = new Set()
const rows = []
for (const p of active(profiles)) {
if (!ready.some((s) => covers(p, s.id)) || seen.has(p.name)) continue
seen.add(p.name)
rows.push({ value: `${PROFILE_PREFIX}${p.name}`, label: `${shape.labelOf(p)} (${p.name})`, group: 'NPC profiles' })
}
return rows
}
// ── Kills (D247, D250, D252) ────────────────────────────────────────────────
/** The site profile a name was pushed as on a server, from the last push; 0 for none. */
async function siteProfileFor(serverId, name) {
const sync = await db.getSync(serverId)
return sync && sync.pushed && sync.pushed[name] ? Number(sync.pushed[name]) : 0
}
/** The profiles a server's leaderboard may rank by: those pushed to it, with their labels. */
async function boardProfiles(serverId) {
return active(await db.listProfiles())
.filter((p) => covers(p, serverId))
.map((p) => ({ id: p.id, name: p.name, label: shape.labelOf(p), killsScope: p.killsScope }))
}
/**
* One profile's ranking as seen from one server's page, counted as the profile
* says (D247). `wipeId` null is all time; `currentWipe` says whether it is the
* server's current wipe, which is what reaches other servers' current wipes.
*/
async function ranking({ serverId, profileId, wipeId = null, currentWipe = false, limit = 50 }) {
const profile = await db.getProfile(profileId)
if (!profile || profile.replaced) throw new NpcError('no such profile', 404)
if (!covers(profile, serverId)) throw new NpcError('that profile is not on this server', 404)
const rows = await db.ranking({ scope: profile.killsScope, name: profile.name, siteProfileId: profile.id, serverId, wipeId, currentWipe }, limit)
return { profile: { id: profile.id, name: profile.name, label: shape.labelOf(profile), killsScope: profile.killsScope }, rows }
}
/**
* The titles' standing for a `profilekills` rule (D250): the ranking of the
* profile on the server the rule is for, current wipe, as the profile counts.
*/
async function standing(serverId, profileId, wipeId, limit) {
const profile = await db.getProfile(profileId)
if (!profile || profile.replaced || !covers(profile, serverId)) return []
return db.ranking({ scope: profile.killsScope, name: profile.name, siteProfileId: profile.id, serverId, wipeId: wipeId || '', currentWipe: true }, limit)
}
/** One player's kills by profile on one server's page (D252), labelled where the site knows the profile. */
async function playerKills({ serverId, steamId, wipeId = null }) {
const [rows, profiles] = await Promise.all([db.playerKills({ serverId, steamId, wipeId }), boardProfiles(serverId)])
const byName = new Map(profiles.map((p) => [p.name, p]))
return rows.map((r) => ({ profile: r.profile, label: byName.has(r.profile) ? byName.get(r.profile).label : r.profile, kills: r.kills }))
}
module.exports = {
adoptFactions,
getFactions,
setFactions,
TETHER_RULE,
API_NEEDED,
PROFILE_PREFIX,
NpcError,
covers,
npcReady,
npcAbsence,
desiredFor,
adopt,
describe,
create,
update,
remove,
restore,
listPlacements,
addPlacement,
setPlacement,
removePlacement,
renamePlacement,
respawnPlacement,
optionRows,
siteProfileFor,
boardProfiles,
ranking,
standing,
playerKills,
}

View File

@@ -0,0 +1,175 @@
// ── A group's BetterChat style, and the voice made from one (phase 17) ─────
//
// D138 puts all twelve of BetterChat's group fields on a site-authored group,
// and D140 lets one styled group be the VOICE the module's own lines are said
// in. Both are pure text work, so they live here, without a database or a game:
//
// validateStyle what an operator typed → the twelve values BetterChat's own
// `chat group set` accepts, or one sentence per problem
// voiceFormat a style → the format string `chat.say` carries: BetterChat's
// markup with exactly one `{message}` in it
//
// Every value is TEXT, in the form BetterChat's setter parses — `true`/`false`,
// a decimal integer, a colour — because text is what the plugin compares the
// game's value against when it decides whether somebody edited a field by hand
// (§33.2). Two spellings of one value would be drift that never happened.
/** The longest a format may be (§33.4 reading 7). */
const FORMAT_MAX = 128
/** The longest a group's title may be. BetterChat has no limit; a chat line does. */
const TITLE_MAX = 64
/**
* The twelve fields, by the name BetterChat's API takes, each with its type and
* BetterChat 5.2.15's default. `Title`'s default is the group's own name in
* brackets, so it is worked out in `defaults`.
*/
const FIELDS = [
{ name: 'Priority', type: 'int', min: -9999, max: 9999, default: '0' },
{ name: 'Title', type: 'title', default: null },
{ name: 'TitleColor', type: 'color', default: '#55aaff' },
{ name: 'TitleSize', type: 'size', default: '15' },
{ name: 'TitleHidden', type: 'bool', default: 'false' },
{ name: 'TitleHiddenIfNotPrimary', type: 'bool', default: 'false' },
{ name: 'UsernameColor', type: 'color', default: '#55aaff' },
{ name: 'UsernameSize', type: 'size', default: '15' },
{ name: 'MessageColor', type: 'color', default: 'white' },
{ name: 'MessageSize', type: 'size', default: '15' },
{ name: 'ChatFormat', type: 'format', default: '{Title} {Username}: {Message}' },
{ name: 'ConsoleFormat', type: 'format', default: '{Title} {Username}: {Message}' },
]
const FIELD_NAMES = FIELDS.map((f) => f.name)
/** BetterChat's defaults for a new group of this name — what the form starts from. */
function defaults(group) {
const out = {}
for (const f of FIELDS) out[f.name] = f.default
out.Title = group === 'default' ? '[Player]' : `[${group}]`
return out
}
function occurrences(text, needle) {
return text.split(needle).length - 1
}
/**
* One field's value as BetterChat's setter takes it, or a sentence.
*
* Colours are `#rrggbb` or a plain colour word (BetterChat's own default for a
* message is `white`). A format holds `{Message}` EXACTLY once: without it every
* line a member types is swallowed, and twice cannot be made into a voice,
* whose line has one message.
*/
function checkField(field, raw) {
const text = typeof raw === 'boolean' || typeof raw === 'number' ? String(raw) : typeof raw === 'string' ? raw.trim() : null
if (text === null || /[\r\n]/.test(text)) return { error: `${field.name} must be text on one line` }
switch (field.type) {
case 'int': {
if (!/^-?\d{1,4}$/.test(text)) return { error: `${field.name} must be a whole number from ${field.min} to ${field.max}` }
return { value: String(Number(text)) }
}
case 'size': {
if (!/^\d{1,2}$/.test(text) || Number(text) < 6 || Number(text) > 64) return { error: `${field.name} must be a size from 6 to 64` }
return { value: String(Number(text)) }
}
case 'bool': {
const lowered = text.toLowerCase()
if (lowered !== 'true' && lowered !== 'false') return { error: `${field.name} must be true or false` }
return { value: lowered }
}
case 'color': {
if (/^#[0-9a-fA-F]{6}$/.test(text)) return { value: text.toLowerCase() }
if (/^[a-z]{3,20}$/.test(text)) return { value: text }
return { error: `${field.name} must be a colour like #ffaa55, or a colour word like white` }
}
case 'title': {
if (!text.length || text.length > TITLE_MAX) return { error: `Title must be 1 to ${TITLE_MAX} characters` }
// A brace would be read as a placeholder when the title is put into a line.
if (/[{}]/.test(text)) return { error: 'Title cannot contain { or }' }
return { value: text }
}
case 'format': {
if (text.length > FORMAT_MAX) return { error: `${field.name} must be at most ${FORMAT_MAX} characters` }
if (occurrences(text, '{Message}') !== 1) return { error: `${field.name} must contain {Message} exactly once` }
return { value: text }
}
default:
return { error: `${field.name} is not a field this site knows` }
}
}
/**
* An operator's style, checked whole. All twelve fields are required — a style
* is the whole of a BetterChat group or nothing (D138), which is what keeps a
* half-authored group from being a set of values nobody chose.
*
* Resolves `{ ok: true, fields }` with every value normalised, or
* `{ ok: false, errors }`, one sentence per problem.
*/
function validateStyle(style) {
if (!style || typeof style !== 'object' || Array.isArray(style)) {
return { ok: false, errors: ['a chat style is an object of the twelve BetterChat fields'] }
}
const errors = []
const fields = {}
for (const key of Object.keys(style)) {
if (!FIELD_NAMES.includes(key)) errors.push(`${key} is not a BetterChat group field`)
}
for (const field of FIELDS) {
if (style[field.name] === undefined || style[field.name] === null) {
errors.push(`${field.name} is missing`)
continue
}
const checked = checkField(field, style[field.name])
if (checked.error) errors.push(checked.error)
else fields[field.name] = checked.value
}
return errors.length ? { ok: false, errors } : { ok: true, fields }
}
/** A colour as BetterChat's markup writes it: the hex without its `#`, or the word. */
function markupColor(color) {
return String(color || 'white').replace(/^#/, '')
}
/**
* The format a styled group's voice says a line in (D140), or null.
*
* Built from six of the twelve fields (§33.4 reading 5): the title, its colour
* and size, the message's colour and size, and `ChatFormat`. The line has no
* sender, so `{Username}` renders as nothing — and so does the `:` BetterChat's
* own default puts after it, or every announcement would read `[Title] : …`.
* `{Group}`, `{ID}`, `{Time}` and `{Date}` render as nothing for the same
* reason. The plugin puts the words in for `{message}` and turns the markup into
* the game's rich text.
*/
function voiceFormat(fields) {
if (!fields || !fields.ChatFormat || occurrences(fields.ChatFormat, '{Message}') !== 1) return null
const title =
fields.TitleHidden === 'true'
? ''
: `[#${markupColor(fields.TitleColor)}][+${fields.TitleSize || 15}]${fields.Title || ''}[/+][/#]`
const message = `[#${markupColor(fields.MessageColor)}][+${fields.MessageSize || 15}]{message}[/+][/#]`
// split/join rather than `replace`, whose replacement string treats `$&` and
// friends as patterns — and a title is operator text.
const format = fields.ChatFormat
.replace(/\{Username\}\s*:?/g, '')
.replace(/\{(Group|ID|Time|Date)\}/g, '')
.split('{Title}').join(title)
.split('{Message}').join(message)
.replace(/\s{2,}/g, ' ')
.trim()
return occurrences(format, '{message}') === 1 ? format : null
}
module.exports = { FIELDS, FIELD_NAMES, FORMAT_MAX, TITLE_MAX, defaults, validateStyle, voiceFormat, checkField }

View File

@@ -0,0 +1,210 @@
// ── Carrying out what the reconciler decided ──────────────────────────────
//
// `reconcile.plan` says WHAT a change made in the game becomes; this file writes
// it into the site's own record. Every write here is about ONE server (D190): a
// change in one game affects that server and nothing else, even when the site's
// row reaches further.
//
// • A grant that reaches only this server is deleted or written outright.
// • A grant that reaches more (a fleet grant, or a user's grant scoped `*`)
// gains an EXCEPTION for this server, and keeps reaching every other one.
// • A group shared with other servers is SPLIT: this server gets its own copy,
// the change is made to the copy, and the shared group stops covering it. A
// notice says so, in case the change was meant for every server.
//
// Ops are applied one at a time and each re-reads what it needs, because an
// earlier op in the same plan may have split the group a later one writes to.
// `permSync` runs a plan under one lock for the whole fleet, so two servers'
// plans never split the same shared group at once.
const db = require('./permissions.db')
const model = require('./permissions.model')
/** The site's group of this name on this server, or null (D189). */
async function groupOn(name, serverId) {
const [groups, groupServers] = await Promise.all([db.listGroups(), db.listGroupServers()])
return model.groupsOn(serverId, { groups, groupServers }).find((group) => group.name === name) || null
}
/**
* The group of this name that belongs to THIS server alone, splitting a shared
* one if that is what covers it (D190). Null when the site has no such group.
*/
async function ownGroup(name, serverId) {
const group = await groupOn(name, serverId)
if (!group) return null
const groupServers = await db.listGroupServers()
if (!model.isShared(group, model.serversByGroup(groupServers))) return group
const copy = await db.copyGroup(group.id, 'split')
await db.setGroupServers(copy, { allServers: false, servers: [serverId] })
await db.removeGroupFromServer(group.id, serverId)
await db.noteSplit(serverId, {
group: name,
detail: `changed in the game on ${serverId}; that server now has its own copy of "${name}"`,
})
return db.getGroup(copy)
}
/** The Steam ids and user linked to one Steam id, for finding a user's grant. */
async function userOf(steamId) {
const links = await db.listLinks()
const link = links.find((row) => row.steamId === steamId)
return link ? link.userId : null
}
/**
* A grant the game holds and the site does not. If a grant that reaches this
* server was only kept off it by an EXCEPTION, the exception is what the game
* just undid, so the exception goes. Otherwise a Steam-account grant for this
* server alone is written (D188, D190).
*/
async function adoptGrant(serverId, { steamId, permission, source }) {
const exceptions = (await db.listExceptions()).filter((e) => e.serverId === serverId)
if (exceptions.length) {
const userId = await userOf(steamId)
const [userGrants, steamGrants] = await Promise.all([
userId === null ? [] : db.listGrants({ userId }),
db.listSteamGrants({ steamId }),
])
const candidates = [
...userGrants.map((g) => ({ holder: 'user', id: g.id, permission: g.permission, scope: g.scope })),
...steamGrants.map((g) => ({ holder: 'steam', id: g.id, permission: g.permission, scope: g.scope })),
].filter((g) => model.normaliseName(g.permission) === permission && model.inScope(g.scope, serverId))
for (const grant of candidates) {
const exception = exceptions.find((e) => e.holder === grant.holder && Number(e.grantId) === Number(grant.id))
if (exception) {
await db.deleteException(exception.id)
return
}
}
}
await db.insertSteamGrant({ steamId, permission, scope: serverId, source })
}
/**
* A grant the site holds and the game no longer does. Each source that put it
* on this server stops doing so: one scoped to this server alone is deleted; one
* that reaches further gains an exception here. An event's grant is left to the
* event (the reconciler never sends one here).
*/
async function dropGrant(serverId, { sources = [] }) {
for (const source of sources) {
if (source.type !== 'userGrant' && source.type !== 'steamGrant') continue
const holder = source.type === 'userGrant' ? 'user' : 'steam'
if (source.scope === serverId) {
if (holder === 'user') await db.deleteGrant(source.id)
else await db.deleteSteamGrant(source.id)
} else {
await db.addException({ holder, grantId: source.id, serverId })
}
}
}
/** Run one op. Returns a short line for the log. */
async function applyOp(serverId, op) {
switch (op.op) {
case 'adoptGroup': {
// A group of this name may already exist on another server, or be shared
// with every server but this one: either way this server gets its own.
const existing = await groupOn(op.name, serverId)
if (existing) return `group ${op.name}: already the site's`
const id = await db.insertGroup({ name: op.name, title: op.title, rank: op.rank, parent: op.parent, source: op.source })
await db.setGroupServers(id, { allServers: false, servers: [serverId] })
return `group ${op.name}: adopted`
}
case 'setGroupAttrs': {
const group = await ownGroup(op.group, serverId)
if (!group) return `group ${op.group}: not the site's`
await db.updateGroup(group.id, { title: op.title, rank: op.rank, parent: op.parent })
return `group ${op.group}: title, rank and parent from the game`
}
case 'adoptGroupPermission': {
const group = await ownGroup(op.group, serverId)
if (!group) return `group ${op.group}: not the site's`
await db.addGroupPermission(group.id, op.permission)
return `group ${op.group} + ${op.permission}`
}
case 'dropGroupPermission': {
const group = await ownGroup(op.group, serverId)
if (!group) return `group ${op.group}: not the site's`
await db.removeGroupPermission(group.id, op.permission)
return `group ${op.group} − ${op.permission}`
}
case 'adoptMember': {
const group = await ownGroup(op.group, serverId)
if (!group) return `group ${op.group}: not the site's`
await db.addGroupSteamMember(group.id, op.steamId, { source: op.source })
return `${op.steamId} in ${op.group}`
}
case 'dropMember': {
const group = await ownGroup(op.group, serverId)
if (!group) return `group ${op.group}: not the site's`
// Whichever way the site had them in it: as a Steam account, and as the
// website account that account is linked to.
await db.removeGroupSteamMember(group.id, op.steamId)
const userId = await userOf(op.steamId)
if (userId !== null) await db.removeGroupMember(group.id, userId)
return `${op.steamId} out of ${op.group}`
}
case 'adoptGrant':
await adoptGrant(serverId, op)
return `${op.steamId} + ${op.permission}`
case 'dropGrant':
await dropGrant(serverId, op)
return `${op.steamId} − ${op.permission}`
case 'dropGroup': {
const group = await groupOn(op.group, serverId)
if (!group) return `group ${op.group}: not the site's`
const groupServers = await db.listGroupServers()
if (model.isShared(group, model.serversByGroup(groupServers))) {
await db.removeGroupFromServer(group.id, serverId)
return `group ${op.group}: no longer on ${serverId}`
}
await db.deleteGroup(group.id)
return `group ${op.group}: deleted`
}
default:
return `unknown op ${op.op}`
}
}
/** Run a plan's ops in order. One op failing does not stop the rest. */
async function applyOps(serverId, ops, log = null) {
const done = []
for (const op of ops) {
try {
// eslint-disable-next-line no-await-in-loop
done.push(await applyOp(serverId, op))
} catch (err) {
done.push(`${op.op} failed: ${err.message}`)
if (log) log.warn('permission op failed', { server: serverId, op: op.op, error: err.message })
}
}
return done
}
module.exports = { groupOn, ownGroup, applyOp, applyOps }

View File

@@ -0,0 +1,894 @@
// ── SQL for the permission mirror, and nothing else ───────────────────────
//
// The tables this file reads are described at length in `db/schema.sql`; what
// matters here is which of them is authoritative for what, because several look
// similar and answer completely different questions:
//
// AUTHORED the site's own record of every permission and group on every
// server (D160). Groups are `rust_permgroups` and the rows beside
// them — one group per server unless an admin shares it (D189).
// Holders are website users (`rust_perm_grants`,
// `rust_permgroup_members`, D28) or single Steam accounts
// (`rust_perm_steam_grants`, `rust_permgroup_steam_members`, D188),
// and a grant that reaches several servers may carry exceptions
// (`rust_perm_exceptions`, D190).
// PUSHED `rust_perm_pushed` — what this site has confirmed into one game's
// store. Keyed by STEAM ID, because it records what is in the game
// and the game has never heard of a website account.
// FOUND `rust_perm_drift` — a change made in the game that waits for a
// person: every one under the `adopt` policy, and the few no policy
// can settle alone (D161, D190).
// INSTRUCTED `rust_perm_revocations` — remove this, even though we never put
// it there.
//
// Raw parameterised SQL through `core.query`, no ORM, like every other `.db.js`
// here. Bulk writes are batched into one statement with a generated placeholder
// list rather than looped, because a fleet-wide sync writes hundreds of rows and
// a round trip each is how a boot tick becomes a second long.
const core = require('../../core')
const GROUPS = 'rust_permgroups'
const GROUP_SERVERS = 'rust_permgroup_servers'
const GROUP_PERMISSIONS = 'rust_permgroup_permissions'
const GROUP_MEMBERS = 'rust_permgroup_members'
const GROUP_STEAM_MEMBERS = 'rust_permgroup_steam_members'
const GROUP_CHAT = 'rust_permgroup_chat'
const GRANTS = 'rust_perm_grants'
const STEAM_GRANTS = 'rust_perm_steam_grants'
const EXCEPTIONS = 'rust_perm_exceptions'
const RUN_GRANTS = 'rust_perm_run_grants'
const PUSHED = 'rust_perm_pushed'
const DRIFT = 'rust_perm_drift'
const REVOCATIONS = 'rust_perm_revocations'
const SYNC = 'rust_perm_sync'
const CATALOGUE = 'rust_perm_catalogue'
const LINKS = 'rust_account_links'
const SERVERS = 'rust_servers'
const SETTINGS = 'rust_settings'
// The tables before the rebuild. Read once, by `migrateGroups`, and never again.
const OLD_GROUPS = 'rust_perm_groups'
const OLD_GROUP_PERMISSIONS = 'rust_perm_group_permissions'
const OLD_GROUP_MEMBERS = 'rust_perm_group_members'
const OLD_GROUP_CHAT = 'rust_perm_group_chat'
const MIGRATED_KEY = 'perm.groups.migrated'
/** `(?,?,?),(?,?,?)` for `rows.length` rows of `width` columns. */
function placeholders(rows, width) {
return rows.map(() => `(${new Array(width).fill('?').join(',')})`).join(',')
}
const affected = (result) => Number((result && result.affectedRows) || 0)
// ---- groups (D189) ----
const GROUP_COLUMNS = `id, name, title, \`rank\`, parent, all_servers AS allServers, source,
created_at AS createdAt, updated_at AS updatedAt`
async function listGroups() {
const rows = await core.query(`SELECT ${GROUP_COLUMNS} FROM ${GROUPS} ORDER BY \`rank\` DESC, name ASC, id ASC`)
return rows.map((row) => ({ ...row, allServers: Boolean(Number(row.allServers)) }))
}
async function getGroup(id) {
const rows = await core.query(`SELECT ${GROUP_COLUMNS} FROM ${GROUPS} WHERE id = ?`, [id])
return rows[0] ? { ...rows[0], allServers: Boolean(Number(rows[0].allServers)) } : null
}
/** Every group's server rows: `included` 1 is on, 0 is an all-servers group's exclusion. */
async function listGroupServers() {
const rows = await core.query(`SELECT group_id AS groupId, server_id AS serverId, included FROM ${GROUP_SERVERS}`)
return rows.map((row) => ({ ...row, included: Boolean(Number(row.included)) }))
}
async function insertGroup({ name, title = '', rank = 0, parent = '', allServers = false, source = 'admin' }) {
const result = await core.query(
`INSERT INTO ${GROUPS} (name, title, \`rank\`, parent, all_servers, source) VALUES (?, ?, ?, ?, ?, ?)`,
[name, title, rank, parent, allServers ? 1 : 0, source],
)
return Number(result.insertId)
}
async function updateGroup(id, { title, rank, parent }) {
await core.query(
`UPDATE ${GROUPS} SET title = ?, \`rank\` = ?, parent = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
[title, rank, parent, id],
)
}
async function deleteGroup(id) {
return affected(await core.query(`DELETE FROM ${GROUPS} WHERE id = ?`, [id])) > 0
}
/**
* Put a group on exactly these servers, or on all of them less `excluded`.
* Replaced whole: the form edits the set as one thing.
*/
async function setGroupServers(id, { allServers, servers = [], excluded = [] }) {
await core.query(`UPDATE ${GROUPS} SET all_servers = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [allServers ? 1 : 0, id])
await core.query(`DELETE FROM ${GROUP_SERVERS} WHERE group_id = ?`, [id])
const rows = allServers ? excluded.map((s) => [s, 0]) : servers.map((s) => [s, 1])
if (!rows.length) return
await core.query(
`INSERT INTO ${GROUP_SERVERS} (group_id, server_id, included) VALUES ${placeholders(rows, 3)}`,
rows.flatMap(([serverId, included]) => [id, serverId, included]),
)
}
/**
* Take one server off a group (D190's split, and a group deleted in one game):
* an all-servers group gains an exclusion, any other loses the server's row.
*/
async function removeGroupFromServer(id, serverId) {
const group = await getGroup(id)
if (!group) return
if (group.allServers) {
await core.query(
`INSERT INTO ${GROUP_SERVERS} (group_id, server_id, included) VALUES (?, ?, 0)
ON DUPLICATE KEY UPDATE included = 0`,
[id, serverId],
)
} else {
await core.query(`DELETE FROM ${GROUP_SERVERS} WHERE group_id = ? AND server_id = ?`, [id, serverId])
}
await core.query(`UPDATE ${GROUPS} SET updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [id])
}
async function listGroupPermissions() {
return core.query(`SELECT group_id AS groupId, permission FROM ${GROUP_PERMISSIONS} ORDER BY permission ASC`)
}
/** Replace a group's permission list whole. */
async function setGroupPermissions(id, permissions) {
await core.query(`DELETE FROM ${GROUP_PERMISSIONS} WHERE group_id = ?`, [id])
if (!permissions.length) return
await core.query(
`INSERT IGNORE INTO ${GROUP_PERMISSIONS} (group_id, permission) VALUES ${placeholders(permissions, 2)}`,
permissions.flatMap((permission) => [id, permission]),
)
}
async function addGroupPermission(id, permission) {
return affected(await core.query(
`INSERT IGNORE INTO ${GROUP_PERMISSIONS} (group_id, permission) VALUES (?, ?)`,
[id, permission],
)) > 0
}
async function removeGroupPermission(id, permission) {
return affected(await core.query(
`DELETE FROM ${GROUP_PERMISSIONS} WHERE group_id = ? AND permission = ?`,
[id, permission],
)) > 0
}
/** Every group's BetterChat style, one row per field (phase 17, D138). */
async function listGroupChat() {
return core.query(`SELECT group_id AS groupId, field, value FROM ${GROUP_CHAT} ORDER BY group_id ASC, field ASC`)
}
/** Replace a group's style whole, or remove it with `null`. */
async function setGroupChat(id, fields) {
await core.query(`DELETE FROM ${GROUP_CHAT} WHERE group_id = ?`, [id])
const entries = fields ? Object.entries(fields) : []
if (!entries.length) return
await core.query(
`INSERT INTO ${GROUP_CHAT} (group_id, field, value) VALUES ${placeholders(entries, 3)}`,
entries.flatMap(([field, value]) => [id, field, value]),
)
}
/** One field of a style, for adopting a hand edit. Returns whether the group has that field. */
async function setGroupChatField(id, field, value) {
return affected(await core.query(
`UPDATE ${GROUP_CHAT} SET value = ? WHERE group_id = ? AND field = ?`,
[value, id, field],
)) > 0
}
async function getGroupChat(id) {
const rows = await core.query(`SELECT field, value FROM ${GROUP_CHAT} WHERE group_id = ?`, [id])
return rows.length ? Object.fromEntries(rows.map((r) => [r.field, r.value])) : null
}
/**
* Members who are website accounts, with each account's linked Steam ids joined
* on — one row per (membership, Steam id), which the push and the screen both want.
*/
async function listGroupMembers() {
return core.query(
`SELECT m.group_id AS groupId, m.user_id AS userId, m.added_at AS addedAt,
u.username, l.steam_id AS steamId, p.name AS playerName
FROM ${GROUP_MEMBERS} m
JOIN users u ON u.id = m.user_id
LEFT JOIN ${LINKS} l ON l.user_id = m.user_id
LEFT JOIN rust_players p ON p.steam_id = l.steam_id
ORDER BY m.group_id ASC, u.username ASC`,
)
}
async function addGroupMember(id, userId, addedBy) {
return affected(await core.query(
`INSERT IGNORE INTO ${GROUP_MEMBERS} (group_id, user_id, added_by) VALUES (?, ?, ?)`,
[id, userId, addedBy],
)) > 0
}
async function removeGroupMember(id, userId) {
return affected(await core.query(`DELETE FROM ${GROUP_MEMBERS} WHERE group_id = ? AND user_id = ?`, [id, userId])) > 0
}
/** Members who are one Steam account (D188). */
async function listGroupSteamMembers() {
return core.query(
`SELECT s.group_id AS groupId, s.steam_id AS steamId, s.source, s.added_at AS addedAt, p.name AS playerName
FROM ${GROUP_STEAM_MEMBERS} s
LEFT JOIN rust_players p ON p.steam_id = s.steam_id
ORDER BY s.group_id ASC, s.steam_id ASC`,
)
}
async function addGroupSteamMember(id, steamId, { source = 'admin', addedBy = null } = {}) {
return affected(await core.query(
`INSERT IGNORE INTO ${GROUP_STEAM_MEMBERS} (group_id, steam_id, source, added_by) VALUES (?, ?, ?, ?)`,
[id, steamId, source, addedBy],
)) > 0
}
async function removeGroupSteamMember(id, steamId) {
return affected(await core.query(
`DELETE FROM ${GROUP_STEAM_MEMBERS} WHERE group_id = ? AND steam_id = ?`,
[id, steamId],
)) > 0
}
/**
* A copy of a group — its attributes, permissions, both kinds of member and its
* style — on no server yet. D190's split: the caller puts the copy on the one
* server whose game changed, and takes that server off the original.
*/
async function copyGroup(id, source = 'split') {
const group = await getGroup(id)
if (!group) return null
const copy = await insertGroup({ name: group.name, title: group.title, rank: group.rank, parent: group.parent, source })
await core.query(
`INSERT INTO ${GROUP_PERMISSIONS} (group_id, permission) SELECT ?, permission FROM ${GROUP_PERMISSIONS} WHERE group_id = ?`,
[copy, id],
)
await core.query(
`INSERT INTO ${GROUP_MEMBERS} (group_id, user_id, added_by, added_at)
SELECT ?, user_id, added_by, added_at FROM ${GROUP_MEMBERS} WHERE group_id = ?`,
[copy, id],
)
await core.query(
`INSERT INTO ${GROUP_STEAM_MEMBERS} (group_id, steam_id, source, added_by, added_at)
SELECT ?, steam_id, source, added_by, added_at FROM ${GROUP_STEAM_MEMBERS} WHERE group_id = ?`,
[copy, id],
)
await core.query(
`INSERT INTO ${GROUP_CHAT} (group_id, field, value) SELECT ?, field, value FROM ${GROUP_CHAT} WHERE group_id = ?`,
[copy, id],
)
return copy
}
// ---- grants ----
/**
* Every grant to a website user, with the holder's accounts joined on. One row
* per (grant, linked Steam id); a grant with nothing linked still has one row.
*/
async function listGrants({ userId = null } = {}) {
return core.query(
`SELECT g.id, g.user_id AS userId, g.permission, g.scope, g.source, g.note,
g.granted_at AS grantedAt, u.username,
l.steam_id AS steamId, p.name AS playerName
FROM ${GRANTS} g
JOIN users u ON u.id = g.user_id
LEFT JOIN ${LINKS} l ON l.user_id = g.user_id
LEFT JOIN rust_players p ON p.steam_id = l.steam_id
${userId === null ? '' : 'WHERE g.user_id = ?'}
ORDER BY u.username ASC, g.permission ASC`,
userId === null ? [] : [userId],
)
}
async function getGrant(id) {
const rows = await core.query(
`SELECT id, user_id AS userId, permission, scope, source FROM ${GRANTS} WHERE id = ?`,
[id],
)
return rows[0] || null
}
/** Add a grant, or leave the one that is already there. The return says which. */
async function insertGrant({ userId, permission, scope, source, note, grantedBy }) {
const result = await core.query(
`INSERT IGNORE INTO ${GRANTS} (user_id, permission, scope, source, note, granted_by)
VALUES (?, ?, ?, ?, ?, ?)`,
[userId, permission, scope, source, note, grantedBy],
)
return { inserted: affected(result) > 0, id: result.insertId }
}
/** Delete a grant and the exceptions it carried, which no foreign key can reach. */
async function deleteGrant(id) {
const removed = affected(await core.query(`DELETE FROM ${GRANTS} WHERE id = ?`, [id])) > 0
await deleteExceptionsFor('user', id)
return removed
}
/** Every grant to one Steam account (D188), with the in-game name when the site has one. */
async function listSteamGrants({ steamId = null } = {}) {
return core.query(
`SELECT g.id, g.steam_id AS steamId, g.permission, g.scope, g.source, g.note,
g.granted_at AS grantedAt, p.name AS playerName
FROM ${STEAM_GRANTS} g
LEFT JOIN rust_players p ON p.steam_id = g.steam_id
${steamId === null ? '' : 'WHERE g.steam_id = ?'}
ORDER BY g.steam_id ASC, g.permission ASC`,
steamId === null ? [] : [steamId],
)
}
async function getSteamGrant(id) {
const rows = await core.query(
`SELECT id, steam_id AS steamId, permission, scope, source FROM ${STEAM_GRANTS} WHERE id = ?`,
[id],
)
return rows[0] || null
}
async function insertSteamGrant({ steamId, permission, scope, source = 'admin', note = null, grantedBy = null }) {
const result = await core.query(
`INSERT IGNORE INTO ${STEAM_GRANTS} (steam_id, permission, scope, source, note, granted_by)
VALUES (?, ?, ?, ?, ?, ?)`,
[steamId, permission, scope, source, note, grantedBy],
)
return { inserted: affected(result) > 0, id: result.insertId }
}
async function deleteSteamGrant(id) {
const removed = affected(await core.query(`DELETE FROM ${STEAM_GRANTS} WHERE id = ?`, [id])) > 0
await deleteExceptionsFor('steam', id)
return removed
}
// ---- "everywhere except here" (D190) ----
async function listExceptions() {
return core.query(
`SELECT id, holder, grant_id AS grantId, server_id AS serverId, created_by AS createdBy, created_at AS createdAt
FROM ${EXCEPTIONS}`,
)
}
async function addException({ holder, grantId, serverId, createdBy = null }) {
await core.query(
`INSERT IGNORE INTO ${EXCEPTIONS} (holder, grant_id, server_id, created_by) VALUES (?, ?, ?, ?)`,
[holder, grantId, serverId, createdBy],
)
}
async function deleteException(id) {
return affected(await core.query(`DELETE FROM ${EXCEPTIONS} WHERE id = ?`, [id])) > 0
}
async function deleteExceptionsFor(holder, grantId) {
await core.query(`DELETE FROM ${EXCEPTIONS} WHERE holder = ? AND grant_id = ?`, [holder, grantId])
}
// ---- what events granted (phase 13b) ----
//
// `rust_perm_run_grants` is authored by `rust.kit.entitle`, never by a person,
// and it is read beside the grants above rather than merged into them (D84): the
// push unions them, and a revert deletes exactly one step's rows.
async function listRunGrants() {
return core.query(
`SELECT run_id AS runId, step_id AS stepId, user_id AS userId, server_id AS serverId,
steam_id AS steamId, permission, kit, credit
FROM ${RUN_GRANTS}`,
)
}
async function listRunGrantsForStep(runId, stepId) {
return core.query(
`SELECT user_id AS userId, server_id AS serverId, steam_id AS steamId, permission, kit, credit
FROM ${RUN_GRANTS}
WHERE run_id = ? AND step_id = ?`,
[String(runId), String(stepId)],
)
}
async function insertRunGrants(rows) {
if (!rows.length) return 0
const result = await core.query(
`INSERT IGNORE INTO ${RUN_GRANTS} (run_id, step_id, idem_key, user_id, server_id, steam_id, permission, kit, credit)
VALUES ${placeholders(rows, 9)}`,
rows.flatMap((r) => [
String(r.runId),
String(r.stepId),
String(r.idemKey || ''),
r.userId,
r.serverId,
r.steamId,
r.permission || '',
r.kit,
r.credit ? 1 : 0,
]),
)
return affected(result)
}
async function deleteRunGrantsForStep(runId, stepId) {
return deleteRunGrantsWhere('run_id = ? AND step_id = ?', [String(runId), String(stepId)])
}
async function deleteRunGrantsForKey(runId, idemKey) {
if (!idemKey) return []
return deleteRunGrantsWhere('run_id = ? AND idem_key = ?', [String(runId), String(idemKey)])
}
async function deleteRunGrantsWhere(where, params) {
const found = await core.query(`SELECT DISTINCT server_id AS serverId FROM ${RUN_GRANTS} WHERE ${where}`, params)
if (!found.length) return []
await core.query(`DELETE FROM ${RUN_GRANTS} WHERE ${where}`, params)
return found.map((row) => row.serverId)
}
/**
* One website account by name, for the authoring form. Case-insensitive because
* core stores usernames in a `_ci` collation.
*/
async function findUserByUsername(username) {
const rows = await core.query(`SELECT id, username FROM users WHERE username = ? LIMIT 1`, [username])
return rows[0] || null
}
/** Which website user holds which Steam account. */
async function listLinks() {
return core.query(`SELECT user_id AS userId, steam_id AS steamId FROM ${LINKS}`)
}
/** Links with the account's name and the in-game name, for naming subjects on the screen (D163). */
async function listLinksNamed() {
return core.query(
`SELECT l.steam_id AS steamId, l.user_id AS userId, u.username, p.name AS playerName
FROM ${LINKS} l
JOIN users u ON u.id = l.user_id
LEFT JOIN rust_players p ON p.steam_id = l.steam_id`,
)
}
/** The in-game names the site knows for these Steam ids (D163). */
async function namesFor(steamIds) {
if (!steamIds.length) return []
return core.query(
`SELECT steam_id AS steamId, name FROM rust_players WHERE steam_id IN (${steamIds.map(() => '?').join(',')})`,
steamIds,
)
}
/** Players seen on one server, for the players list's search. Newest first, bounded. */
async function searchPlayers(serverId, q, limit = 25) {
const like = `%${String(q || '').replace(/[\\%_]/g, (c) => `\\${c}`)}%`
return core.query(
`SELECT p.steam_id AS steamId, p.name AS playerName, l.user_id AS userId, u.username
FROM rust_players p
LEFT JOIN ${LINKS} l ON l.steam_id = p.steam_id
LEFT JOIN users u ON u.id = l.user_id
WHERE (p.name LIKE ? OR p.steam_id LIKE ? OR u.username LIKE ?)
AND EXISTS (SELECT 1 FROM rust_player_wipe_stats s WHERE s.steam_id = p.steam_id AND s.server_id = ?)
ORDER BY p.last_seen DESC
LIMIT ${Number(limit) || 25}`,
[like, like, like, serverId],
)
}
// ---- one person's own half of all of it (the player tier) ----
/** The groups one website user belongs to, by account membership. */
async function listGroupsForUser(userId) {
const rows = await core.query(
`SELECT g.id, g.name, g.title, g.\`rank\`, g.all_servers AS allServers, m.added_at AS addedAt
FROM ${GROUP_MEMBERS} m
JOIN ${GROUPS} g ON g.id = m.group_id
WHERE m.user_id = ?
ORDER BY g.\`rank\` DESC, g.name ASC`,
[userId],
)
return rows.map((row) => ({ ...row, allServers: Boolean(Number(row.allServers)) }))
}
/** Every pushed row naming one of these Steam ids, across every server. */
async function listPushedForSteamIds(steamIds) {
if (!steamIds.length) return []
return core.query(
`SELECT server_id AS serverId, kind, subject, object
FROM ${PUSHED}
WHERE subject IN (${steamIds.map(() => '?').join(',')})
AND kind IN ('grant', 'member')`,
steamIds,
)
}
// ---- what is actually out there ----
async function listPushed(serverId) {
return core.query(`SELECT kind, subject, object, value FROM ${PUSHED} WHERE server_id = ?`, [serverId])
}
/**
* Record rows as landed. A row with a VALUE (a `chat-field`, and a `group`'s
* title, rank and parent since protocol 13) moves it on a second landing: the
* value is what the next inventory tells a hand edit from this site's own write
* by. Every other kind has no value and is written once.
*/
async function addPushed(serverId, rows) {
if (!rows.length) return
await core.query(
`INSERT INTO ${PUSHED} (server_id, kind, subject, object, value)
VALUES ${placeholders(rows, 5)}
ON DUPLICATE KEY UPDATE value = VALUES(value)`,
rows.flatMap((row) => [serverId, row.kind, row.subject, row.object, row.value === undefined ? null : row.value]),
)
}
async function setPushedValue(serverId, { kind, subject, object, value }) {
await addPushed(serverId, [{ kind, subject, object, value }])
}
async function removePushed(serverId, rows) {
for (const row of rows) {
// eslint-disable-next-line no-await-in-loop
await core.query(
`DELETE FROM ${PUSHED} WHERE server_id = ? AND kind = ? AND subject = ? AND object = ?`,
[serverId, row.kind, row.subject, row.object],
)
}
}
/**
* Replace one server's "needs a person" list with what the latest sync found.
*
* Whole, and `first_seen` survives through the `ON DUPLICATE KEY UPDATE`. A
* `split` row is a notice rather than a difference — nothing in the game says it
* any more once it is made — so it is left alone until a person dismisses it.
*/
async function replaceDrift(serverId, rows) {
if (!rows.length) {
await core.query(`DELETE FROM ${DRIFT} WHERE server_id = ? AND direction <> 'split'`, [serverId])
return
}
await core.query(
`INSERT INTO ${DRIFT} (server_id, kind, subject, object, detail, direction)
VALUES ${placeholders(rows, 6)}
ON DUPLICATE KEY UPDATE last_seen = CURRENT_TIMESTAMP, detail = VALUES(detail), direction = VALUES(direction)`,
rows.flatMap((row) => [
serverId,
row.kind,
row.subject,
row.object,
row.detail === undefined ? null : row.detail,
row.direction || 'added',
]),
)
await core.query(
`DELETE FROM ${DRIFT}
WHERE server_id = ?
AND direction <> 'split'
AND (kind, subject, object) NOT IN (${placeholders(rows, 3)})`,
[serverId, ...rows.flatMap((row) => [row.kind, row.subject, row.object])],
)
}
/** A split notice (D190). Kept until a person dismisses it. */
async function noteSplit(serverId, { group, detail }) {
await core.query(
`INSERT INTO ${DRIFT} (server_id, kind, subject, object, detail, direction)
VALUES (?, 'group', ?, '', ?, 'split')
ON DUPLICATE KEY UPDATE last_seen = CURRENT_TIMESTAMP, detail = VALUES(detail), direction = 'split'`,
[serverId, group, detail === undefined ? null : detail],
)
}
async function listDrift() {
return core.query(
`SELECT d.id, d.server_id AS serverId, d.kind, d.subject, d.object, d.detail, d.direction,
d.first_seen AS firstSeen, d.last_seen AS lastSeen,
l.user_id AS userId, u.username, p.name AS playerName
FROM ${DRIFT} d
LEFT JOIN ${LINKS} l ON l.steam_id = d.subject
LEFT JOIN users u ON u.id = l.user_id
LEFT JOIN rust_players p ON p.steam_id = d.subject
ORDER BY d.server_id ASC, d.kind ASC, d.subject ASC`,
)
}
async function getDrift(id) {
const rows = await core.query(
`SELECT id, server_id AS serverId, kind, subject, object, detail, direction FROM ${DRIFT} WHERE id = ?`,
[id],
)
return rows[0] || null
}
async function deleteDrift(id) {
await core.query(`DELETE FROM ${DRIFT} WHERE id = ?`, [id])
}
async function queueRevocation({ serverId, kind, subject, object, requestedBy }) {
await core.query(
`INSERT IGNORE INTO ${REVOCATIONS} (server_id, kind, subject, object, requested_by)
VALUES (?, ?, ?, ?, ?)`,
[serverId, kind, subject, object, requestedBy],
)
}
async function listRevocations(serverId) {
return core.query(`SELECT id, kind, subject, object FROM ${REVOCATIONS} WHERE server_id = ?`, [serverId])
}
async function deleteRevocations(ids) {
if (!ids.length) return
await core.query(`DELETE FROM ${REVOCATIONS} WHERE id IN (${ids.map(() => '?').join(',')})`, ids)
}
// ---- the state of the mirror ----
async function ensureSyncRows() {
await core.query(`INSERT IGNORE INTO ${SYNC} (server_id) SELECT id FROM ${SERVERS}`)
}
async function listSync() {
return core.query(
`SELECT s.server_id AS serverId, s.state, s.dirty, s.desired_hash AS desiredHash,
s.synced_hash AS syncedHash, s.boot_id AS bootId, s.wipe_id AS wipeId,
s.last_attempt_at AS lastAttemptAt, s.last_ok_at AS lastOkAt,
s.imported_at AS importedAt, s.report, s.error
FROM ${SYNC} s
ORDER BY s.server_id ASC`,
)
}
/**
* Mark servers as needing a sync. `scope` is a server id, `*`, or a list of ids.
*/
async function markDirty(scope) {
if (!scope || scope === '*') {
await core.query(`UPDATE ${SYNC} SET dirty = 1, updated_at = CURRENT_TIMESTAMP`)
return
}
const ids = Array.isArray(scope) ? scope : [scope]
if (!ids.length) return
await core.query(
`UPDATE ${SYNC} SET dirty = 1, updated_at = CURRENT_TIMESTAMP WHERE server_id IN (${ids.map(() => '?').join(',')})`,
ids,
)
}
/**
* Record the outcome of one attempt. `dirty` is cleared unconditionally: the
* loop's real condition is the digest, recomputed every tick.
*/
async function putSyncResult(serverId, { state, syncedHash, desiredHash, bootId, wipeId, report, error }) {
const okAt = state === 'ok' ? new Date() : null
await core.query(
`INSERT INTO ${SYNC} (server_id, state, dirty, desired_hash, synced_hash, boot_id, wipe_id,
last_attempt_at, last_ok_at, report, error, updated_at)
VALUES (?, ?, 0, ?, ?, ?, ?, NOW(), ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE state = VALUES(state), dirty = 0,
desired_hash = VALUES(desired_hash),
synced_hash = VALUES(synced_hash),
boot_id = VALUES(boot_id), wipe_id = VALUES(wipe_id),
last_attempt_at = NOW(),
last_ok_at = COALESCE(VALUES(last_ok_at), last_ok_at),
report = VALUES(report), error = VALUES(error),
updated_at = NOW()`,
[serverId, state, desiredHash, syncedHash, bootId, wipeId, okAt, report, error],
)
}
/** The first complete inventory of a server has been imported (D198). */
async function markImported(serverId) {
await core.query(`UPDATE ${SYNC} SET imported_at = COALESCE(imported_at, NOW()) WHERE server_id = ?`, [serverId])
}
/** Every server's policy for a change made in the game (D161). */
async function listPolicies() {
return core.query(`SELECT id AS serverId, perm_policy AS policy FROM ${SERVERS}`)
}
async function setPolicy(serverId, policy) {
return affected(await core.query(`UPDATE ${SERVERS} SET perm_policy = ? WHERE id = ?`, [policy, serverId])) > 0
}
// ---- the option source ----
/** What one server's plugins registered, and which plugin registered each (§0.1). */
async function putCatalogue(serverId, rows) {
await core.query(`DELETE FROM ${CATALOGUE} WHERE server_id = ?`, [serverId])
if (!rows.length) return
await core.query(
`INSERT IGNORE INTO ${CATALOGUE} (server_id, permission, owner) VALUES ${placeholders(rows, 3)}`,
rows.flatMap((row) => [serverId, row.permission, row.owner || null]),
)
}
async function listCatalogue() {
return core.query(
`SELECT server_id AS serverId, permission, owner FROM ${CATALOGUE} ORDER BY permission ASC`,
)
}
// ---- the one-time copy out of the old group tables ----
/**
* Copy the groups made before the rebuild into the new tables, once.
*
* A group scoped `*` becomes a group on every server, and one scoped to a server
* becomes that server's group, so what each server receives does not change. The
* marker in `rust_settings` is what makes it once: without it, a site whose admin
* later deleted every group would have them all copied back on the next boot.
* Returns how many groups were copied.
*/
async function migrateGroups() {
const done = await core.query(`SELECT value FROM ${SETTINGS} WHERE setting_key = ?`, [MIGRATED_KEY])
if (done.length) return 0
const old = await core.query(`SELECT name, title, \`rank\`, scope FROM ${OLD_GROUPS}`)
// A copy that failed halfway is finished, not repeated: a group already
// migrated under its name is skipped.
const already = new Set(
(await core.query(`SELECT name FROM ${GROUPS} WHERE source = 'migrated'`)).map((row) => row.name),
)
for (const group of old) {
if (already.has(group.name)) continue
// eslint-disable-next-line no-await-in-loop
const id = await insertGroup({
name: group.name,
title: group.title || '',
rank: Number(group.rank) || 0,
allServers: group.scope === '*',
source: 'migrated',
})
const params = [id, group.name]
/* eslint-disable no-await-in-loop */
if (group.scope !== '*') {
await core.query(
`INSERT IGNORE INTO ${GROUP_SERVERS} (group_id, server_id, included)
SELECT ?, id, 1 FROM ${SERVERS} WHERE id = ?`,
[id, group.scope],
)
}
await core.query(
`INSERT IGNORE INTO ${GROUP_PERMISSIONS} (group_id, permission)
SELECT ?, permission FROM ${OLD_GROUP_PERMISSIONS} WHERE group_name = ?`,
params,
)
await core.query(
`INSERT IGNORE INTO ${GROUP_MEMBERS} (group_id, user_id, added_by, added_at)
SELECT ?, user_id, added_by, added_at FROM ${OLD_GROUP_MEMBERS} WHERE group_name = ?`,
params,
)
await core.query(
`INSERT IGNORE INTO ${GROUP_CHAT} (group_id, field, value)
SELECT ?, field, value FROM ${OLD_GROUP_CHAT} WHERE group_name = ?`,
params,
)
/* eslint-enable no-await-in-loop */
}
await core.query(
`INSERT IGNORE INTO ${SETTINGS} (setting_key, value) VALUES (?, ?)`,
[MIGRATED_KEY, String(old.length)],
)
return old.length
}
module.exports = {
GROUPS,
GRANTS,
STEAM_GRANTS,
RUN_GRANTS,
PUSHED,
DRIFT,
listGroups,
getGroup,
listGroupServers,
insertGroup,
updateGroup,
deleteGroup,
setGroupServers,
removeGroupFromServer,
listGroupPermissions,
setGroupPermissions,
addGroupPermission,
removeGroupPermission,
listGroupChat,
setGroupChat,
setGroupChatField,
getGroupChat,
listGroupMembers,
addGroupMember,
removeGroupMember,
listGroupSteamMembers,
addGroupSteamMember,
removeGroupSteamMember,
copyGroup,
listGrants,
getGrant,
insertGrant,
deleteGrant,
listSteamGrants,
getSteamGrant,
insertSteamGrant,
deleteSteamGrant,
listExceptions,
addException,
deleteException,
deleteExceptionsFor,
listRunGrants,
listRunGrantsForStep,
insertRunGrants,
deleteRunGrantsForStep,
deleteRunGrantsForKey,
findUserByUsername,
listLinks,
listLinksNamed,
namesFor,
searchPlayers,
listGroupsForUser,
listPushedForSteamIds,
listPushed,
addPushed,
setPushedValue,
removePushed,
replaceDrift,
noteSplit,
listDrift,
getDrift,
deleteDrift,
queueRevocation,
listRevocations,
deleteRevocations,
ensureSyncRows,
listSync,
markDirty,
putSyncResult,
markImported,
listPolicies,
setPolicy,
putCatalogue,
listCatalogue,
migrateGroups,
}

View File

@@ -0,0 +1,568 @@
// ── The authored set, and what it means for one server ────────────────────
//
// This file turns "what the site holds" into "what one game server's store
// should contain". Since the permission manager was rebuilt (PLAN_REDESIGNS §1)
// the site holds EVERYTHING on every server — what was there before it, what an
// admin made, and what was changed in the game (D160) — so the decisions that
// live here are:
//
// D28 a grant or membership held by a WEBSITE USER reaches every Steam id
// they have linked, resolved here at the moment of the push.
// D188 one held by a STEAM ACCOUNT reaches exactly that account, linked or not.
// D29 a grant carries a scope — one server, or `*` for the fleet — and a
// server sees only what names it. D190 lets a fleet grant carry
// exceptions: "every server except this one".
// D189 a group belongs to one server unless an admin shares it. What it
// carries and who is in it are the group's, and the same on every server
// it is on.
// D31 the difference between the desired set and what this site has pushed
// is what gets retired.
//
// `buildDesired` also says, for each row, which authored rows produced it (its
// SOURCES). The reconciler needs that to answer a change made in the game: a
// grant removed in the game is deleted when it was this server's alone, and gains
// an exception when it reached further (D190).
//
// Nothing here talks to a sidecar — `permSync.js` does that — and nothing here
// writes: every function below is a pure function of rows, tested without a
// game, a sidecar, or a database.
const crypto = require('node:crypto')
const db = require('./permissions.db')
/** A scope that means every server. */
const FLEET = '*'
/**
* Groups neither framework lets go of: they exist on every server by the
* framework's own rule. They are imported and editable, and never retired.
* `moderator` is Carbon's.
*/
const BUILTIN_GROUPS = new Set(['default', 'admin', 'moderator'])
/**
* Permission and group names, as both frameworks store them. Lowercased on the
* way in, because the store lowers them.
*/
function normaliseName(value) {
return String(value || '').trim().toLowerCase()
}
/** Whether a scope reaches a server. */
function inScope(scope, serverId) {
return scope === FLEET || scope === serverId
}
/**
* A group's title, rank and parent as one comparable value, stored on its
* `group` ledger row. The title is kept verbatim — Carbon's own end in a space —
* so the value the site pushed and the value the game reports are the same
* string when nothing changed.
*/
function groupValue(title, rank, parent) {
return JSON.stringify([String(title == null ? '' : title), Number(rank) || 0, normaliseName(parent)])
}
/** `groupId → Map(serverId → included)`. */
function serversByGroup(groupServers) {
const out = new Map()
for (const row of groupServers || []) {
if (!out.has(row.groupId)) out.set(row.groupId, new Map())
out.get(row.groupId).set(row.serverId, Boolean(row.included))
}
return out
}
/** Whether a group is on a server (D189). */
function groupCovers(group, serverRows, serverId) {
const rows = serverRows.get(group.id)
const row = rows ? rows.get(serverId) : undefined
return group.allServers ? row !== false : row === true
}
/** The servers a group is on, out of a list of server ids. */
function groupReach(group, serverRows, serverIds) {
return serverIds.filter((id) => groupCovers(group, serverRows, id))
}
/**
* The groups on one server, one per name. The model refuses a second group of a
* name on a server; should the tables ever hold one anyway, the older wins and
* the newer is ignored rather than both being pushed as one.
*/
function groupsOn(serverId, authored) {
const serverRows = serversByGroup(authored.groupServers)
const byName = new Map()
for (const group of [...authored.groups].sort((a, b) => a.id - b.id)) {
if (!groupCovers(group, serverRows, serverId)) continue
if (!byName.has(group.name)) byName.set(group.name, group)
}
return [...byName.values()]
}
/** Style rows folded into one object per group: `groupId → { Field: value }`. */
function chatByGroup(rows) {
const out = new Map()
for (const row of rows || []) {
if (!out.has(row.groupId)) out.set(row.groupId, {})
out.get(row.groupId)[row.field] = row.value
}
return out
}
/**
* One row per grant, not one per linked account. The join in `listGrants`
* multiplies a grant by the holder's accounts.
*/
function collapseGrants(rows) {
const byId = new Map()
for (const row of rows) {
const existing = byId.get(row.id)
if (!existing) {
byId.set(row.id, {
id: row.id,
userId: row.userId,
username: row.username,
permission: row.permission,
scope: row.scope,
source: row.source,
note: row.note,
grantedAt: row.grantedAt,
accounts: row.steamId ? [{ steamId: row.steamId, name: row.playerName || null }] : [],
})
continue
}
if (row.steamId) existing.accounts.push({ steamId: row.steamId, name: row.playerName || null })
}
return [...byId.values()]
}
/** The sync row as a client reads it. */
function shapeSync(row) {
let report = null
if (row.report) {
try {
report = JSON.parse(row.report)
} catch {
report = null
}
}
return {
serverId: row.serverId,
state: row.state,
dirty: Boolean(row.dirty),
inSync: Boolean(row.desiredHash) && row.desiredHash === row.syncedHash && row.state === 'ok',
lastAttemptAt: row.lastAttemptAt,
lastOkAt: row.lastOkAt,
importedAt: row.importedAt || null,
error: row.error || null,
report,
}
}
/**
* The whole authored set, read once, in the shape the per-server build wants.
*/
async function readAuthored() {
const [
groups,
groupServers,
groupPermissions,
members,
steamMembers,
grants,
steamGrants,
exceptions,
links,
runGrants,
groupChat,
] = await Promise.all([
db.listGroups(),
db.listGroupServers(),
db.listGroupPermissions(),
db.listGroupMembers(),
db.listGroupSteamMembers(),
db.listGrants(),
db.listSteamGrants(),
db.listExceptions(),
db.listLinks(),
db.listRunGrants(),
db.listGroupChat(),
])
const steamIdsByUser = new Map()
for (const link of links) {
if (!steamIdsByUser.has(link.userId)) steamIdsByUser.set(link.userId, [])
steamIdsByUser.get(link.userId).push(link.steamId)
}
return {
groups,
groupServers,
groupPermissions,
members,
steamMembers,
grants,
steamGrants,
exceptions,
runGrants,
groupChat,
steamIdsByUser,
}
}
/** A row's identity, for set arithmetic against what was pushed. */
const rowKey = (row) => `${row.kind} ${row.subject} ${row.object}`
/**
* What one server's store should contain, and the rows that say so.
*
* `payload` what goes on the wire
* `rows` the same set in `rust_perm_pushed`'s shape, for the diff
* `hash` a stable digest of `rows`
* `sources` rowKey → the authored rows that produced it (see the file header)
*
* A user with no linked Steam account contributes nothing and is not an error.
*/
function buildDesired(serverId, authored) {
const { groupPermissions, members, steamIdsByUser } = authored
const steamMembers = authored.steamMembers || []
const grants = authored.grants || []
const steamGrants = authored.steamGrants || []
const runGrants = authored.runGrants || []
const exceptions = new Set(
(authored.exceptions || []).filter((e) => e.serverId === serverId).map((e) => `${e.holder}:${e.grantId}`),
)
const serverRows = serversByGroup(authored.groupServers)
const rows = []
const sources = new Map()
const addSource = (row, source) => {
const key = rowKey(row)
if (!sources.has(key)) sources.set(key, [])
sources.get(key).push(source)
}
const onServer = groupsOn(serverId, authored)
const groupById = new Map(onServer.map((group) => [group.id, group]))
const shared = (group) => isShared(group, serverRows)
const permissionsByGroup = new Map(onServer.map((group) => [group.id, []]))
const membersByGroup = new Map(onServer.map((group) => [group.id, []]))
for (const group of onServer) {
const row = { kind: 'group', subject: group.name, object: '', value: groupValue(group.title, group.rank, group.parent) }
rows.push(row)
addSource(row, { type: 'group', groupId: group.id, shared: shared(group) })
}
for (const entry of groupPermissions) {
const group = groupById.get(entry.groupId)
if (!group) continue
const permission = normaliseName(entry.permission)
if (!permission) continue
permissionsByGroup.get(group.id).push(permission)
const row = { kind: 'group-permission', subject: group.name, object: permission }
rows.push(row)
addSource(row, { type: 'group', groupId: group.id, shared: shared(group) })
}
const seenMember = new Set()
const addMember = (group, steamId, source) => {
const row = { kind: 'member', subject: steamId, object: group.name }
addSource(row, source)
const key = `${group.id}:${steamId}`
if (seenMember.has(key)) return
seenMember.add(key)
membersByGroup.get(group.id).push(steamId)
rows.push(row)
}
for (const entry of members) {
const group = groupById.get(entry.groupId)
if (!group) continue
// Resolved from the link map, not from the joined row, so a user with two
// accounts is a member twice and a user with none is a member nowhere.
for (const steamId of steamIdsByUser.get(entry.userId) || []) {
addMember(group, steamId, { type: 'userMember', groupId: group.id, userId: entry.userId, shared: shared(group) })
}
}
for (const entry of steamMembers) {
const group = groupById.get(entry.groupId)
if (!group) continue
addMember(group, entry.steamId, { type: 'steamMember', groupId: group.id, steamId: entry.steamId, shared: shared(group) })
}
const permissionsBySteamId = new Map()
const seenGrant = new Set()
const addGrant = (steamId, permission, source) => {
const row = { kind: 'grant', subject: steamId, object: permission }
addSource(row, source)
const key = `${steamId}:${permission}`
if (seenGrant.has(key)) return
seenGrant.add(key)
if (!permissionsBySteamId.has(steamId)) permissionsBySteamId.set(steamId, [])
permissionsBySteamId.get(steamId).push(permission)
rows.push(row)
}
// A grant held by a website user (D28), less its exceptions (D190). The
// exception's server is left out, and every other server keeps it.
const seenUserGrant = new Set()
for (const row of grants) {
if (!inScope(row.scope, serverId)) continue
if (seenUserGrant.has(row.id)) continue
seenUserGrant.add(row.id)
if (exceptions.has(`user:${row.id}`)) continue
const permission = normaliseName(row.permission)
if (!permission) continue
for (const steamId of steamIdsByUser.get(row.userId) || []) {
addGrant(steamId, permission, { type: 'userGrant', id: row.id, userId: row.userId, scope: row.scope })
}
}
// A grant held by one Steam account (D188).
for (const row of steamGrants) {
if (!inScope(row.scope, serverId)) continue
if (exceptions.has(`steam:${row.id}`)) continue
const permission = normaliseName(row.permission)
if (!permission) continue
addGrant(row.steamId, permission, { type: 'steamGrant', id: row.id, steamId: row.steamId, scope: row.scope })
}
// ── What events granted (phase 13b, D84) ──────────────────────────────
//
// Unioned through the same `seenGrant`, so a permission held both ways is ONE
// row in the game. An event grant reaches only the kit's server (D102), and
// every account the user has linked (D28). The CREDIT is one extra use on the
// account that took part, while it is still linked to the winner.
const credits = new Map()
for (const row of runGrants) {
if (row.serverId !== serverId) continue
const linked = steamIdsByUser.get(row.userId) || []
const permission = normaliseName(row.permission)
if (permission) {
for (const steamId of linked) addGrant(steamId, permission, { type: 'runGrant', runId: row.runId, stepId: row.stepId })
}
if (Number(row.credit) && linked.includes(row.steamId)) {
const key = `${row.steamId}|${row.kit}`
credits.set(key, (credits.get(key) || 0) + 1)
}
}
// ── A group's BetterChat style (phase 17, D138) ───────────────────────
const chat = chatByGroup(authored.groupChat)
for (const group of onServer) {
const fields = chat.get(group.id)
if (!fields) continue
for (const field of Object.keys(fields).sort()) {
rows.push({ kind: 'chat-field', subject: group.name, object: field, value: fields[field] })
}
}
const creditRows = [...credits.entries()]
.map(([key, count]) => {
const bar = key.indexOf('|')
return { steamId: key.slice(0, bar), kit: key.slice(bar + 1), count }
})
.sort((a, b) => (a.steamId + a.kit).localeCompare(b.steamId + b.kit))
const payload = {
groups: onServer.map((group) => ({
name: group.name,
// Verbatim: an empty title is sent empty, not replaced by the name.
title: group.title == null ? '' : group.title,
rank: Number(group.rank) || 0,
parent: normaliseName(group.parent),
permissions: permissionsByGroup.get(group.id),
members: membersByGroup.get(group.id),
...(chat.has(group.id) ? { chat: chat.get(group.id) } : {}),
})),
grants: [...permissionsBySteamId.entries()].map(([steamId, permissions]) => ({ steamId, permissions })),
// Always sent, even empty (D103).
credits: creditRows,
}
const hashed = [
...rows,
...creditRows.map((c) => ({ kind: 'credit', subject: c.steamId, object: `${c.kit}#${c.count}` })),
]
return { payload, rows, hash: hashRows(hashed), sources }
}
/** Whether a group is on more than one server, or on every server. */
function isShared(group, serverRows) {
if (group.allServers) return true
const rows = serverRows.get(group.id)
if (!rows) return false
let on = 0
for (const included of rows.values()) if (included) on++
return on > 1
}
/**
* A digest of the desired set. Sorted before hashing, and a row's VALUE is in
* it (a style field, a group's title, rank and parent): a change to one must push.
*/
function hashRows(rows) {
const canonical = rows
.map((row) => `${row.kind} ${row.subject} ${row.object}${row.value === undefined || row.value === null ? '' : `=${row.value}`}`)
.sort()
.join('\n')
return crypto.createHash('sha256').update(canonical).digest('hex')
}
/**
* What this site put in a server and has since withdrawn: `pushed − desired`.
*
* Two things are never retired: a built-in group, which the framework keeps
* anyway; and a row in `hold` — a change made in the game that is waiting for a
* person's answer (the `adopt` policy, D161), which is neither the site's to
* push back nor its to remove yet.
*/
function retirements(pushed, desiredRows, hold = new Set()) {
const desired = new Set(desiredRows.map(rowKey))
return pushed.filter((row) => {
const key = rowKey(row)
if (desired.has(key) || hold.has(key)) return false
if (row.kind === 'group' && BUILTIN_GROUPS.has(row.subject)) return false
return true
})
}
/**
* ── What one person holds, as that person reads it ────────────────────────
*
* Unchanged in intent by the rebuild: scope arithmetic answered here, `live`
* per server from the pushed ledger, and no reason given for "waiting". A group
* now reaches the servers it is on (D189) rather than a scope.
*/
async function forPlayer(userId, steamIds, serverRows) {
const [groups, groupServers, groupPermissions, grants, steamGrants, exceptions, pushed] = await Promise.all([
db.listGroupsForUser(userId),
db.listGroupServers(),
db.listGroupPermissions(),
db.listGrants({ userId }),
Promise.all(steamIds.map((steamId) => db.listSteamGrants({ steamId }))).then((lists) => lists.flat()),
db.listExceptions(),
db.listPushedForSteamIds(steamIds),
])
const servers = serverRows.map((row) => ({ id: row.id, name: row.name || row.id }))
const serverIds = servers.map((s) => s.id)
const byGroup = serversByGroup(groupServers)
const excepted = new Set(exceptions.map((e) => `${e.holder}:${e.grantId}:${e.serverId}`))
const live = new Map()
for (const row of pushed) {
const key = `${row.kind}:${normaliseName(row.object)}`
if (!live.has(key)) live.set(key, new Set())
live.get(key).add(row.serverId)
}
const reachOf = (ids, key) => {
const landed = live.get(key) || new Set()
return servers.filter((s) => ids.includes(s.id)).map((s) => ({ ...s, live: landed.has(s.id) }))
}
const grantReach = (grant, holder) =>
serverIds.filter((id) => inScope(grant.scope, id) && !excepted.has(`${holder}:${grant.id}:${id}`))
const permissionsByGroup = new Map()
for (const row of groupPermissions) {
if (!permissionsByGroup.has(row.groupId)) permissionsByGroup.set(row.groupId, [])
permissionsByGroup.get(row.groupId).push(normaliseName(row.permission))
}
const shapeGrant = (grant, holder) => ({
permission: grant.permission,
scope: grant.scope,
source: grant.source,
note: grant.note || null,
since: grant.grantedAt,
reach: reachOf(grantReach(grant, holder), `grant:${normaliseName(grant.permission)}`),
})
return {
groups: groups.map((group) => {
const reach = groupReach(group, byGroup, serverIds)
return {
name: group.name,
title: group.title || group.name,
// Kept for older clients: `*` for a group on every server, else the
// servers it is on.
scope: group.allServers ? FLEET : reach.join(','),
since: group.addedAt,
permissions: (permissionsByGroup.get(group.id) || []).sort(),
reach: reachOf(reach, `member:${normaliseName(group.name)}`),
}
}),
grants: [
...collapseGrants(grants).map((grant) => shapeGrant(grant, 'user')),
...steamGrants.map((grant) => shapeGrant(grant, 'steam')),
].sort((a, b) => a.permission.localeCompare(b.permission)),
}
}
module.exports = {
FLEET,
BUILTIN_GROUPS,
normaliseName,
inScope,
groupValue,
serversByGroup,
groupCovers,
groupReach,
groupsOn,
isShared,
forPlayer,
readAuthored,
buildDesired,
retirements,
hashRows,
rowKey,
collapseGrants,
shapeSync,
chatByGroup,
}

View File

@@ -0,0 +1,198 @@
// ── What the permission screen reads (D162, D163, U-1) ────────────────────
//
// The screen follows uMod PermissionsManager's flow — a server, then players ⇄
// groups, then a subject, then a plugin's permissions with Granted / Revoked —
// and every toggle on it carries its own state on that server. This file
// assembles what that needs in one read per request:
//
// • plugins grouped by the plugin that REGISTERED each permission (§0.1),
// never by the name's prefix — `zonemanager.ignoreflag.nokits` is
// ZoneManager's. A name no plugin owns (Carbon's built-in modules) is
// grouped by its prefix, and says so.
// • the groups on the server (D189), with where else each one is.
// • every subject holding anything there, named by linked account and in-game
// name, or Steam id when there is neither (D163).
// • the raw facts the toggle states are computed from: what the site wants and
// why (its sources), what has landed (the pushed ledger), and what the last
// report said did not.
const db = require('./permissions.db')
const model = require('./permissions.model')
const servers = require('../servers/servers.model')
/** The servers, their policy and sync state, and every row waiting for a person. */
async function overview() {
const [serverRows, sync, policies, drift] = await Promise.all([
servers.listForAdmin(),
db.listSync(),
db.listPolicies(),
db.listDrift(),
])
const syncById = new Map(sync.map((row) => [row.serverId, model.shapeSync(row)]))
const policyById = new Map(policies.map((row) => [row.serverId, row.policy]))
return {
servers: serverRows.map((row) => ({
id: row.id,
name: row.name || row.id,
policy: policyById.get(row.id) || 'auto-adopt',
sync: syncById.get(row.id) || null,
})),
drift: drift.map((row) => ({ ...row, detail: row.detail === undefined ? null : row.detail })),
}
}
/** A permission's plugin button: its registering plugin, or its prefix. */
function pluginOf(row) {
if (row.owner) return { key: `plugin:${row.owner}`, label: row.owner, registered: true }
const prefix = row.permission.includes('.') ? row.permission.slice(0, row.permission.indexOf('.')) : row.permission
return { key: `prefix:${prefix}`, label: prefix, registered: false }
}
/**
* Everything the screen shows for one server. Null for a server the site does
* not have.
*/
async function serverView(serverId) {
const serverRows = await servers.listForAdmin()
const server = serverRows.find((row) => row.id === serverId)
if (!server) return null
const [authored, catalogue, pushed, sync, policies, drift, links] = await Promise.all([
model.readAuthored(),
db.listCatalogue(),
db.listPushed(serverId),
db.listSync(),
db.listPolicies(),
db.listDrift(),
db.listLinksNamed(),
])
const serverIds = serverRows.map((row) => row.id)
const desired = model.buildDesired(serverId, authored)
const byGroup = model.serversByGroup(authored.groupServers)
const syncRow = sync.find((row) => row.serverId === serverId)
const linkBySteam = new Map(links.map((row) => [row.steamId, row]))
// ── Plugins, by who registered each permission ──
const plugins = new Map()
for (const row of catalogue.filter((r) => r.serverId === serverId)) {
const plugin = pluginOf(row)
if (!plugins.has(plugin.key)) plugins.set(plugin.key, { ...plugin, permissions: [] })
plugins.get(plugin.key).permissions.push(row.permission)
}
// ── Groups on this server ──
const chat = model.chatByGroup(authored.groupChat)
const onServer = model.groupsOn(serverId, authored)
const permissionsByGroup = new Map()
for (const row of authored.groupPermissions) {
if (!permissionsByGroup.has(row.groupId)) permissionsByGroup.set(row.groupId, [])
permissionsByGroup.get(row.groupId).push(model.normaliseName(row.permission))
}
const members = new Map()
for (const row of authored.members) {
if (!members.has(row.groupId)) members.set(row.groupId, new Map())
const byUser = members.get(row.groupId)
if (!byUser.has(row.userId)) byUser.set(row.userId, { userId: row.userId, username: row.username, steamIds: [] })
if (row.steamId) byUser.get(row.userId).steamIds.push(row.steamId)
}
const groups = onServer.map((group) => {
const reach = model.groupReach(group, byGroup, serverIds)
return {
id: group.id,
name: group.name,
title: group.title,
rank: group.rank,
parent: group.parent,
source: group.source,
builtin: model.BUILTIN_GROUPS.has(group.name),
allServers: group.allServers,
servers: reach,
shared: model.isShared(group, byGroup),
permissions: (permissionsByGroup.get(group.id) || []).sort(),
members: [...((members.get(group.id) || new Map()).values())],
steamMembers: authored.steamMembers.filter((m) => m.groupId === group.id).map((m) => m.steamId),
chat: chat.get(group.id) || null,
}
})
// ── Subjects: every Steam id holding anything here, by the desired set ──
const subjects = new Map()
const subject = (steamId) => {
if (!subjects.has(steamId)) subjects.set(steamId, { steamId, grants: [], groups: [] })
return subjects.get(steamId)
}
for (const row of desired.rows) {
if (row.kind === 'grant') {
subject(row.subject).grants.push({ permission: row.object, sources: desired.sources.get(model.rowKey(row)) || [] })
} else if (row.kind === 'member') {
subject(row.subject).groups.push(row.object)
}
}
// A grant kept off this server by an exception still belongs on the screen:
// it is "on every server except this one", and the toggle can take it back.
const exceptions = authored.exceptions.filter((e) => e.serverId === serverId)
const grantById = new Map(authored.grants.map((g) => [`user:${g.id}`, g]))
for (const g of authored.steamGrants) grantById.set(`steam:${g.id}`, g)
const excepted = []
for (const e of exceptions) {
const grant = grantById.get(`${e.holder}:${e.grantId}`)
if (!grant) continue
const steamIds = e.holder === 'steam' ? [grant.steamId] : (authored.steamIdsByUser.get(grant.userId) || [])
for (const steamId of steamIds) {
subject(steamId)
excepted.push({ id: e.id, steamId, permission: model.normaliseName(grant.permission), holder: e.holder, grantId: e.grantId })
}
}
const steamIds = [...subjects.keys()]
const names = new Map((await db.namesFor(steamIds)).map((row) => [row.steamId, row.name]))
const players = [...subjects.values()]
.map((s) => {
const link = linkBySteam.get(s.steamId)
return {
...s,
name: names.get(s.steamId) || (link && link.playerName) || null,
account: link ? { userId: link.userId, username: link.username } : null,
}
})
.sort((a, b) => (a.name || a.steamId).localeCompare(b.name || b.steamId))
const report = syncRow ? model.shapeSync(syncRow).report : null
const policy = (policies.find((row) => row.serverId === serverId) || {}).policy || 'auto-adopt'
return {
server: { id: server.id, name: server.name || server.id },
servers: serverRows.map((row) => ({ id: row.id, name: row.name || row.id })),
policy,
sync: syncRow ? model.shapeSync(syncRow) : null,
plugins: [...plugins.values()].sort((a, b) => Number(b.registered) - Number(a.registered) || a.label.localeCompare(b.label)),
groups,
players,
excepted,
// What has landed on this server: `grant steamId permission`, `member steamId
// group`, `group-permission group permission`.
landed: pushed
.filter((row) => row.kind === 'grant' || row.kind === 'member' || row.kind === 'group-permission')
.map(model.rowKey),
report: report
? {
unresolved: report.unresolved || [],
pending: report.pending || [],
notLanded: report.notLanded || [],
}
: null,
drift: drift.filter((row) => row.serverId === serverId),
}
}
module.exports = { overview, serverView, pluginOf }

View File

@@ -0,0 +1,277 @@
// ── Three sets, and what a change made in the game becomes ────────────────
//
// `rust_perm_pushed`'s own comment has always named three sets — what is in the
// game, what this site put there, and what the site wants there. Until protocol
// 13 the plugin could only compute the first for the names the site claimed.
// The inventory (PLAN_REDESIGNS §1.2) gives the site all three, so the whole of
// "what happened, and what do we do about it" is decided here:
//
// in the game pushed desired means
// yes no no ADDED in the game
// no yes yes REMOVED in the game
// yes yes yes a group whose title, rank or parent the
// game holds differently from what was
// pushed: CHANGED in the game
// yes no yes landed by some other hand: recorded
//
// (desired − pushed is the ordinary push, and pushed − desired the ordinary
// retirement; neither is this file's business.)
//
// Then the server's policy (D161) says what each change becomes: the site's own
// (`auto-adopt`, the default), a question for a person (`adopt`), or undone
// (`revoke`). The first inventory of a server imports what it finds whatever the
// policy (D198).
//
// **Two things are never judged, and both are how a site would otherwise throw
// away its own grants.** A permission the server has not REGISTERED right now —
// a plugin unloaded for a minute — is missing from the inventory because the
// plugin that owns it is, not because anybody revoked it. And a group permission
// an event lease holds is the lease's until it ends.
//
// Pure: rows in, a plan out. `permissions.apply.js` carries the plan out.
const { rowKey, groupValue, normaliseName, BUILTIN_GROUPS } = require('./permissions.model')
const JUDGED = new Set(['group', 'group-permission', 'member', 'grant'])
/** The inventory in the pushed ledger's shape. */
function presentRows(inventory) {
const rows = []
for (const group of (inventory && inventory.groups) || []) {
const name = normaliseName(group.name)
if (!name) continue
rows.push({ kind: 'group', subject: name, object: '', value: groupValue(group.title, group.rank, group.parent) })
for (const permission of group.permissions || []) {
rows.push({ kind: 'group-permission', subject: name, object: normaliseName(permission) })
}
}
for (const user of (inventory && inventory.users) || []) {
for (const permission of user.permissions || []) {
rows.push({ kind: 'grant', subject: String(user.steamId), object: normaliseName(permission) })
}
for (const group of user.groups || []) {
rows.push({ kind: 'member', subject: String(user.steamId), object: normaliseName(group) })
}
}
return rows
}
/** The group attributes a `group` row's value carries. */
function parseGroupValue(value) {
try {
const [title, rank, parent] = JSON.parse(value)
return { title: String(title == null ? '' : title), rank: Number(rank) || 0, parent: normaliseName(parent) }
} catch {
return null
}
}
/**
* Sort every row into added, removed, changed or landed.
*
* `registered` is the set of names the server registers right now; `leased` the
* lease-held pairs, as `group-permission` rows.
*/
function classify({ present, pushed, desired, registered, leased = [] }) {
const leasedKeys = new Set(leased.map((row) => rowKey({ kind: 'group-permission', subject: normaliseName(row.subject), object: normaliseName(row.object) })))
const judged = (row) => {
if (!JUDGED.has(row.kind)) return false
if ((row.kind === 'grant' || row.kind === 'group-permission') && !registered.has(row.object)) return false
// `default` holds every connected player by the framework's rule (§1.2).
if (row.kind === 'member' && row.object === 'default') return false
if (leasedKeys.has(rowKey(row))) return false
return true
}
const index = (rows) => new Map(rows.filter(judged).map((row) => [rowKey(row), row]))
const P = index(present)
const U = index(pushed)
const D = index(desired)
const added = []
const removed = []
const changed = []
const landed = []
for (const [key, row] of P) {
if (!U.has(key) && !D.has(key)) added.push(row)
else if (!U.has(key) && D.has(key)) landed.push({ ...D.get(key) })
else if (row.kind === 'group' && U.has(key) && D.has(key)) {
const pushedValue = U.get(key).value
// A value the site pushed, that the site still wants, and that the game no
// longer holds: somebody changed the group in the game. A ledger row with
// no value (before protocol 13) cannot say, and the site's value is pushed.
if (pushedValue && row.value !== pushedValue && D.get(key).value === pushedValue) changed.push(row)
}
}
for (const [key, row] of U) {
if (!P.has(key) && D.has(key)) removed.push(row)
}
// A group removed in the game takes its permissions and members with it; they
// are the group's removal, not changes of their own.
const goneGroups = new Set(removed.filter((row) => row.kind === 'group').map((row) => row.subject))
const keep = (row) =>
row.kind === 'group' || !goneGroups.has(row.kind === 'member' ? row.object : row.subject)
return { added, removed: removed.filter(keep), changed, landed }
}
/**
* What the changes become under one server's policy.
*
* Returns:
* `ops` for `permissions.apply.js`, in the order they must run —
* groups before what goes in them
* `drift` "needs a person" rows (D161's `adopt`, and what no policy can
* settle alone)
* `revocations` what the `revoke` policy undoes at this sync
* `hold` row keys this sync must neither push back nor retire nor
* record, because a person has not answered yet
*/
function plan({ classes, policy, importing, sources }) {
const ops = []
const drift = []
const revocations = []
const hold = new Set()
const source = importing ? 'imported' : 'adopted'
const adoptOp = (row) => {
if (row.kind === 'group') {
const attrs = parseGroupValue(row.value) || { title: '', rank: 0, parent: '' }
return { op: 'adoptGroup', name: row.subject, ...attrs, source }
}
if (row.kind === 'group-permission') return { op: 'adoptGroupPermission', group: row.subject, permission: row.object, source }
if (row.kind === 'member') return { op: 'adoptMember', group: row.object, steamId: row.subject, source }
return { op: 'adoptGrant', steamId: row.subject, permission: row.object, source }
}
const dropOp = (row) => {
if (row.kind === 'group') return { op: 'dropGroup', group: row.subject }
if (row.kind === 'group-permission') return { op: 'dropGroupPermission', group: row.subject, permission: row.object }
if (row.kind === 'member') {
return { op: 'dropMember', group: row.object, steamId: row.subject, sources: sources.get(rowKey(row)) || [] }
}
return { op: 'dropGrant', steamId: row.subject, permission: row.object, sources: sources.get(rowKey(row)) || [] }
}
const order = { adoptGroup: 0, setGroupAttrs: 1, adoptGroupPermission: 2, adoptMember: 2, adoptGrant: 2, dropGroupPermission: 3, dropMember: 3, dropGrant: 3, dropGroup: 4 }
// ── The first inventory: everything present becomes the site's (D160, D198) ──
//
// Additions and changed attributes are imported whatever the policy. A removal
// at import is something this site pushed that the game has since lost — it is
// pushed back, as it always was, rather than deleted on the strength of a
// snapshot taken the moment the site first looked.
if (importing) {
for (const row of classes.added) ops.push(adoptOp(row))
for (const row of classes.changed) ops.push({ op: 'setGroupAttrs', group: row.subject, ...parseGroupValue(row.value) })
return { ops: ops.sort((a, b) => order[a.op] - order[b.op]), drift, revocations, hold }
}
if (policy === 'revoke') {
// The site's set wins. An addition is removed at this sync; a removal or a
// changed group is simply pushed back by the desired set.
for (const row of classes.added) {
// A built-in group cannot be removed; one made in the game under `revoke`
// is — but `default` and `admin` are never "added", the import took them.
if (row.kind === 'group' && BUILTIN_GROUPS.has(row.subject)) continue
revocations.push({ kind: row.kind, subject: row.subject, object: row.object })
}
return { ops, drift, revocations, hold }
}
if (policy === 'adopt') {
// Every change waits for a person, and until then the game is left as it is.
// A group made in the game carries its title, rank and parent, so adopting it
// later keeps them.
for (const row of classes.added) {
drift.push({ kind: row.kind, subject: row.subject, object: row.object, direction: 'added', ...(row.kind === 'group' ? { detail: row.value } : {}) })
}
for (const row of classes.removed) {
drift.push({ kind: row.kind, subject: row.subject, object: row.object, direction: 'removed' })
hold.add(rowKey(row))
}
for (const row of classes.changed) {
drift.push({ kind: 'group', subject: row.subject, object: '', direction: 'changed', detail: row.value })
hold.add(rowKey(row))
}
return { ops, drift, revocations, hold }
}
// ── auto-adopt, the default (D161, D190) ──
for (const row of classes.added) ops.push(adoptOp(row))
for (const row of classes.removed) {
const op = dropOp(row)
// A grant only an event gave cannot be adopted away: the event owns it, and
// its revert will withdraw it. It is pushed back, and a person is told.
if (op.op === 'dropGrant' && op.sources.length && op.sources.every((s) => s.type === 'runGrant')) {
drift.push({ kind: row.kind, subject: row.subject, object: row.object, direction: 'removed', detail: 'event' })
continue
}
ops.push(op)
}
for (const row of classes.changed) ops.push({ op: 'setGroupAttrs', group: row.subject, ...parseGroupValue(row.value) })
return { ops: ops.sort((a, b) => order[a.op] - order[b.op]), drift, revocations, hold }
}
/**
* The desired set with the held rows taken out: not in the payload, so the
* plugin does not put them back, and not in `rows`, so the report does not
* record them. A held group keeps its place — only its title, rank and parent
* are left off, which the plugin reads as "leave them".
*/
function withHold(desired, hold) {
if (!hold || !hold.size) return desired
const heldGroups = new Set()
const payload = { ...desired.payload }
payload.groups = desired.payload.groups.map((group) => {
const key = rowKey({ kind: 'group', subject: group.name, object: '' })
const out = { ...group }
if (hold.has(key)) {
heldGroups.add(group.name)
delete out.title
delete out.rank
delete out.parent
}
out.permissions = (group.permissions || []).filter((p) => !hold.has(rowKey({ kind: 'group-permission', subject: group.name, object: p })))
out.members = (group.members || []).filter((s) => !hold.has(rowKey({ kind: 'member', subject: s, object: group.name })))
return out
})
payload.grants = desired.payload.grants
.map((grant) => ({
...grant,
permissions: grant.permissions.filter((p) => !hold.has(rowKey({ kind: 'grant', subject: grant.steamId, object: p }))),
}))
.filter((grant) => grant.permissions.length)
return {
...desired,
payload,
rows: desired.rows.filter((row) => !hold.has(rowKey(row))),
heldGroups,
}
}
module.exports = { presentRows, parseGroupValue, classify, plan, withHold }

View File

@@ -0,0 +1,106 @@
// ── The voice the module's own lines are said in (phase 17, D140) ──────────
//
// One fleet setting (§33.4 reading 5): the name of a permission group that has
// a BetterChat style, or nothing for plain chat. News lines and `rust.announce`
// lines are then said in that group's title and colours — composed here, said by
// our plugin with no player as the sender, so they look right whether or not
// BetterChat is loaded.
//
// The style is read at the moment a line is said, never copied into the
// setting: an operator who recolours the group changes the voice with it, and a
// group whose style is taken away stops being a voice rather than leaving a
// stale one behind.
const settingsDb = require('../visibility/visibility.db')
const chatStyle = require('./chatStyle')
const db = require('./permissions.db')
const model = require('./permissions.model')
const VOICE_KEY = 'announce.voice'
/**
* The chosen group's id as a string, or '' for plain chat.
*
* Since groups became per server (D189) a name can belong to several groups, so
* the setting holds a group's id. A setting written before that holds a NAME,
* and is read as the first styled group of that name until somebody chooses again.
*/
async function chosen() {
return (await settingsDb.getSetting(VOICE_KEY)) || ''
}
/** The chosen group's style fields, or null. */
async function chosenFields() {
const value = await chosen()
if (!value) return { value, fields: null }
if (/^\d+$/.test(value)) return { value, fields: await db.getGroupChat(Number(value)) }
const groups = await db.listGroups()
for (const group of groups.filter((g) => g.name === model.normaliseName(value))) {
// eslint-disable-next-line no-await-in-loop
const fields = await db.getGroupChat(group.id)
if (fields) return { value: String(group.id), fields }
}
return { value, fields: null }
}
/**
* The format a line is said in right now, or null for plain chat — which is
* also the answer when the chosen group has since lost its style or gone.
*/
async function currentFormat() {
const { fields } = await chosenFields()
return fields ? chatStyle.voiceFormat(fields) : null
}
/** The setting, and every group that could be a voice, for the admin page. */
async function describe() {
const [{ value }, rows, groups, groupServers] = await Promise.all([
chosenFields(),
db.listGroupChat(),
db.listGroups(),
db.listGroupServers(),
])
const byId = new Map(groups.map((g) => [g.id, g]))
const options = []
// Which servers each group is on, so two groups of one name can be told apart.
const where = (group) => {
if (group.allServers) return 'all servers'
const ids = groupServers.filter((r) => r.groupId === group.id && r.included).map((r) => r.serverId)
return ids.length ? ids.join(', ') : 'no server'
}
for (const [groupId, fields] of model.chatByGroup(rows)) {
const format = chatStyle.voiceFormat(fields)
const group = byId.get(groupId)
if (format && group) {
options.push({ group: String(groupId), name: group.name, where: where(group), title: fields.Title || group.name, format })
}
}
return { voice: value, options: options.sort((a, b) => a.name.localeCompare(b.name) || a.group.localeCompare(b.group)) }
}
/**
* Choose the voice by group id. A group is accepted only when it has a style a
* voice can be made from; '' goes back to plain chat. Resolves `{ ok }` or
* `{ ok: false, message }`.
*/
async function choose(group, userId = null) {
const value = String(group || '').trim()
if (value) {
const fields = /^\d+$/.test(value) ? await db.getGroupChat(Number(value)) : null
if (!fields || !chatStyle.voiceFormat(fields)) {
return { ok: false, message: 'That group has no chat style, so it cannot be a voice. Give it one under Permissions first.' }
}
}
await settingsDb.setSetting(VOICE_KEY, value, userId)
return { ok: true, voice: value }
}
module.exports = { VOICE_KEY, chosen, currentFormat, describe, choose }

View File

@@ -0,0 +1,281 @@
// ── When a server wipes next (phase 16, D128 · D130) ────────────────────────
//
// The module knows every PAST wipe — each one is a fact a frame carried — and
// nothing about the next. D128 made the next one something an operator states,
// and D130 made the statement a RULE plus an optional one-off date, so it never
// goes stale: a rule computes the next wipe from the clock, and once a wipe has
// happened the rule simply names the one after it.
//
// **Computed on every read, never stored** (PLAN.md §32.4 reading 7). Nothing has
// to roll it forward after a wipe, and nothing can disagree with it.
//
// ── The rules ─────────────────────────────────────────────────────────────
//
// none no forecast. The operator has not said the server follows any
// calendar, so the game's forced wipe is NOT assumed either.
// forced Facepunch's forced wipe and nothing else.
// weekly every `wipe_day` at `wipe_time` in `wipe_tz`, AND the forced wipe.
// biweekly every other `wipe_day`, on the weeks `wipe_anchor` falls in, AND
// the forced wipe.
//
// Every rule includes the forced wipe because Facepunch forces it on every server
// whatever its own schedule (reading 3): a weekly server's next wipe is the
// earlier of its own next day and the first Thursday of the month.
//
// A one-off date, while it is in the future, IS the next wipe, and any computed
// wipe before it is skipped (reading 5). That one reading covers both of D130's
// cases — a date after the computed wipe delays it, a date before it adds one —
// and it applies under `none` too: an operator who states a date has stated a
// forecast. Once the date has passed it is ignored rather than cleared.
//
// ── The zone arithmetic ───────────────────────────────────────────────────
//
// Core offers modules none (`events/recurrence.js` is core's own, and §2.7 forbids
// importing it), so it is done here through `Intl`, which Node ships with full
// ICU. Calendar dates are counted as whole days since the epoch — a local date is
// a date, not an instant — and turned into an instant only at the end, in the
// server's own zone.
//
// A wall-clock time that does not exist (the hour skipped in spring) moves
// FORWARD by the gap, and one that happens twice (the hour repeated in autumn)
// takes the FIRST occurrence (reading 6). That is Temporal's `compatible`
// disambiguation, and the tests pin both edges in both zones the walk uses.
/** Facepunch's forced wipe: the first Thursday of the month, 19:00 UK time (reading 4). */
const FORCED = Object.freeze({ weekday: 4, time: '19:00', tz: 'Europe/London' })
const RULES = Object.freeze(['none', 'forced', 'weekly', 'biweekly'])
const DAY_MS = 86_400_000
const formatters = new Map()
/** One cached formatter per zone; building one costs far more than using it. */
function formatterFor(tz) {
let fmt = formatters.get(tz)
if (!fmt) {
fmt = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
hourCycle: 'h23',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
})
formatters.set(tz, fmt)
}
return fmt
}
/** Is `tz` a zone this process can compute in? `Intl` throws a RangeError on one it cannot. */
function isZone(tz) {
if (typeof tz !== 'string' || !tz) return false
try {
formatterFor(tz)
return true
} catch {
return false
}
}
/** The wall clock in `tz` at instant `ms`, as `{ y, m, d, hh, mm, ss }`. */
function wallClock(ms, tz) {
const parts = {}
for (const p of formatterFor(tz).formatToParts(new Date(ms))) parts[p.type] = p.value
return {
y: Number(parts.year),
m: Number(parts.month),
d: Number(parts.day),
hh: Number(parts.hour),
mm: Number(parts.minute),
ss: Number(parts.second),
}
}
/** How far `tz` is ahead of UTC at instant `ms`, in milliseconds. */
function offsetAt(ms, tz) {
const w = wallClock(ms, tz)
const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.hh, w.mm, w.ss)
return asUtc - Math.floor(ms / 1000) * 1000
}
/**
* The instant at which `tz`'s wall clock reads `day` (days since the epoch) at
* `hh:mm`, disambiguated as the header says.
*
* Offsets change at most once a day, so the offsets a day either side are the
* only two a wall time can have. Each gives a candidate; a candidate is real if
* the zone's offset AT it is the one that produced it.
*/
function instantOf(day, hh, mm, tz) {
const naive = day * DAY_MS + (hh * 60 + mm) * 60_000
const before = offsetAt(naive - DAY_MS, tz)
const after = offsetAt(naive + DAY_MS, tz)
const candidates = [naive - before, naive - after].filter((t, i) => offsetAt(t, tz) === (i === 0 ? before : after))
// A skipped hour: neither candidate reads back as that wall time. Using the
// offset from BEFORE the gap lands the same distance past it — 01:30 in a
// spring-forward from 01:00 to 02:00 becomes 02:30.
if (!candidates.length) return naive - before
return Math.min(...candidates)
}
/** Today's date in `tz`, as days since the epoch. */
function localDay(ms, tz) {
const w = wallClock(ms, tz)
return Math.floor(Date.UTC(w.y, w.m - 1, w.d) / DAY_MS)
}
/** 0 = Sunday … 6 = Saturday, for a day count. 1970-01-01 was a Thursday. */
const weekdayOf = (day) => (((day + 4) % 7) + 7) % 7
/** `HH:MM` → `[hh, mm]`, or null. */
function parseTime(value) {
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(String(value || ''))
return match ? [Number(match[1]), Number(match[2])] : null
}
/** `YYYY-MM-DD` (or a Date) → days since the epoch, or null. */
function parseDay(value) {
if (value instanceof Date) {
if (Number.isNaN(value.getTime())) return null
return Math.floor(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()) / DAY_MS)
}
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value || ''))
if (!match) return null
const ms = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))
const back = new Date(ms)
// Reject a date that rolled over (2026-02-30 is not 2026-03-02).
if (back.getUTCDate() !== Number(match[3])) return null
return Math.floor(ms / DAY_MS)
}
/** The first forced wipe strictly after `now`. */
function nextForced(now) {
const [hh, mm] = parseTime(FORCED.time)
const today = wallClock(now, FORCED.tz)
// This month's first Thursday, then next month's. Two are always enough: a
// month's forced wipe that has passed is followed by next month's.
for (let step = 0; step < 2; step += 1) {
const first = Math.floor(Date.UTC(today.y, today.m - 1 + step, 1) / DAY_MS)
const thursday = first + ((FORCED.weekday - weekdayOf(first) + 7) % 7)
const at = instantOf(thursday, hh, mm, FORCED.tz)
if (at > now) return at
}
return null
}
/** The first wipe a weekly or biweekly rule names strictly after `now`, or null. */
function nextByRule(row, now) {
const time = parseTime(row.wipeTime)
const day = Number(row.wipeDay)
if (!time || !Number.isInteger(day) || day < 0 || day > 6 || !isZone(row.wipeTz)) return null
const anchor = row.wipeRule === 'biweekly' ? parseDay(row.wipeAnchor) : null
if (row.wipeRule === 'biweekly' && anchor == null) return null
// Start a day early: "today" is judged in the server's zone and `now` may be a
// few hours either side of it in another. Three weeks covers a biweekly rule
// whose on-week has just passed.
const start = localDay(now, row.wipeTz) - 1
for (let d = start; d < start + 22; d += 1) {
if (weekdayOf(d) !== day) continue
// eslint-disable-next-line no-continue
if (anchor != null && (((d - anchor) % 14) + 14) % 14 >= 7) continue
const at = instantOf(d, time[0], time[1], row.wipeTz)
if (at > now) return at
}
return null
}
/** A one-off date as an instant, or null. */
function onceOf(value) {
if (value == null || value === '') return null
const ms = value instanceof Date ? value.getTime() : Date.parse(value)
return Number.isNaN(ms) ? null : ms
}
/**
* When `row` wipes next, and what decided it.
*
* `row` carries the six schedule fields in their camelCase names (`wipeRule`,
* `wipeDay`, `wipeTime`, `wipeTz`, `wipeAnchor`, `wipeOnceAt`). Answers
* `{ at, source }` — `at` an ISO instant, `source` one of `once`, `forced` or
* `rule` — or `null` when no forecast can honestly be made.
*
* Throws nothing: a row with a zone this process does not know, or a time that
* does not parse, answers what the rest of it can (the forced wipe still stands)
* rather than failing the page that asked.
*/
function nextWipe(row, now = Date.now()) {
if (!row) return null
const once = onceOf(row.wipeOnceAt)
if (once != null && once > now) return { at: new Date(once).toISOString(), source: 'once' }
const rule = RULES.includes(row.wipeRule) ? row.wipeRule : 'none'
if (rule === 'none') return null
const forced = nextForced(now)
const own = rule === 'forced' ? null : nextByRule(row, now)
// On a tie the forced wipe is the reason: it happens whatever the rule says.
if (own != null && (forced == null || own < forced)) return { at: new Date(own).toISOString(), source: 'rule' }
if (forced != null) return { at: new Date(forced).toISOString(), source: 'forced' }
return null
}
/**
* Check an operator's schedule before it is saved. Answers a list of sentences,
* empty when the schedule is sound — the admin form shows them as they are.
*
* The rule's own fields are required only by the rules that read them, and the
* one-off date must be in the future on save: a date in the past says nothing
* about the next wipe, and accepting one would be storing a mistake.
*/
function validateSchedule(schedule, now = Date.now()) {
const errors = []
const rule = schedule.wipeRule == null ? 'none' : schedule.wipeRule
if (!RULES.includes(rule)) errors.push(`The wipe rule is one of ${RULES.join(', ')}, not "${rule}".`)
if (rule === 'weekly' || rule === 'biweekly') {
const day = Number(schedule.wipeDay)
if (schedule.wipeDay == null || schedule.wipeDay === '' || !Number.isInteger(day) || day < 0 || day > 6) {
errors.push('A weekly or biweekly rule needs a day of the week.')
}
if (!parseTime(schedule.wipeTime)) errors.push('The wipe time is HH:MM, on a 24-hour clock.')
if (!isZone(schedule.wipeTz)) errors.push(`"${schedule.wipeTz || ''}" is not a time zone this site knows (use an IANA name such as Europe/London).`)
}
if (rule === 'biweekly') {
const anchor = parseDay(schedule.wipeAnchor)
if (anchor == null) {
errors.push('A biweekly rule needs the date of one wipe on it, as YYYY-MM-DD.')
} else if (Number.isInteger(Number(schedule.wipeDay)) && weekdayOf(anchor) !== Number(schedule.wipeDay)) {
errors.push('The biweekly rule’s date must fall on its day of the week.')
}
}
if (schedule.wipeOnceAt != null && schedule.wipeOnceAt !== '') {
const once = onceOf(schedule.wipeOnceAt)
if (once == null) errors.push('The one-off wipe is not a date and time.')
else if (once <= now) errors.push('The one-off wipe must be in the future.')
}
return errors
}
module.exports = {
FORCED,
RULES,
nextWipe,
validateSchedule,
isZone,
// Exposed for the tests, which pin the arithmetic directly.
instantOf,
parseDay,
weekdayOf,
}

View File

@@ -23,7 +23,11 @@ const STATE = 'rust_server_state'
async function listServers({ enabledOnly = false } = {}) {
return core.query(
`SELECT id, name, sidecar_base_url AS sidecarBaseUrl, sidecar_token_enc AS sidecarTokenEnc,
protocol, enabled, sort_order AS sortOrder, created_at AS createdAt, updated_at AS updatedAt
protocol, enabled, sort_order AS sortOrder, announce_news AS announceNews,
news_delivery AS newsDelivery,
wipe_rule AS wipeRule, wipe_day AS wipeDay, wipe_time AS wipeTime, wipe_tz AS wipeTz,
DATE_FORMAT(wipe_anchor, '%Y-%m-%d') AS wipeAnchor, wipe_once_at AS wipeOnceAt,
created_at AS createdAt, updated_at AS updatedAt
FROM ${SERVERS}
${enabledOnly ? 'WHERE enabled = 1' : ''}
ORDER BY sort_order ASC, id ASC`,
@@ -33,7 +37,10 @@ async function listServers({ enabledOnly = false } = {}) {
async function getServer(id) {
const rows = await core.query(
`SELECT id, name, sidecar_base_url AS sidecarBaseUrl, sidecar_token_enc AS sidecarTokenEnc,
protocol, enabled, sort_order AS sortOrder, created_at AS createdAt, updated_at AS updatedAt
protocol, enabled, sort_order AS sortOrder,
wipe_rule AS wipeRule, wipe_day AS wipeDay, wipe_time AS wipeTime, wipe_tz AS wipeTz,
DATE_FORMAT(wipe_anchor, '%Y-%m-%d') AS wipeAnchor, wipe_once_at AS wipeOnceAt,
created_at AS createdAt, updated_at AS updatedAt
FROM ${SERVERS}
WHERE id = ?`,
[id],
@@ -70,17 +77,124 @@ async function upsertServer({ id, name, sidecarBaseUrl, sidecarTokenEnc, protoco
)
}
/**
* Write one server's wipe schedule (phase 16, D130), all six columns at once.
*
* Its own statement rather than six more columns on `upsertServer`, because the
* schedule is written only when a save CARRIES one: a client that predates the
* schedule and posts the rest of the row must not reset it to `none`.
*
* `wipeOnceAt` is a Date or null. The pool negotiates the session's zone
* (`timezone: 'auto'` in core), so a Date written here reads back as the same
* instant.
*/
async function setSchedule(id, { wipeRule, wipeDay, wipeTime, wipeTz, wipeAnchor, wipeOnceAt }) {
await core.query(
`UPDATE ${SERVERS}
SET wipe_rule = ?, wipe_day = ?, wipe_time = ?, wipe_tz = ?, wipe_anchor = ?, wipe_once_at = ?
WHERE id = ?`,
[wipeRule, wipeDay, wipeTime, wipeTz, wipeAnchor, wipeOnceAt, id],
)
}
async function deleteServer(id) {
await core.query(`DELETE FROM ${SERVERS} WHERE id = ?`, [id])
}
/**
* `worldReady` from the hello the row keeps whole (`raw`): true, false, or null for
* a plugin that never says — which PLAN.md §28.6 reads as ready. The permission and
* title pushes hold while it is false (PLAN_FIXES F7): the plugin connects before the
* save loads, and a sync sent then waits on a main thread that is busy loading, times
* out, and the restart it was for is never shown as restored.
*/
function withWorldReady(row) {
if (!row) return row
const value = row.worldReady
const ready = value === null || value === undefined ? null : value === true || value === 1 || String(value) === 'true'
return { ...row, worldReady: ready, zoneHelper: helperOf(row.zoneHelper) }
}
/**
* The ZoneManager helper's state from the same hello (PLAN_FIXES D182): `{ state,
* version?, reason? }`, or null when the plugin reported none — no ZoneManager, or
* a plugin older than protocol 13. The driver hands JSON_EXTRACT back as text.
*/
function helperOf(value) {
if (value === null || value === undefined) return null
let parsed = value
if (typeof value === 'string') {
try {
parsed = JSON.parse(value)
} catch {
return null
}
}
if (!parsed || typeof parsed !== 'object' || typeof parsed.state !== 'string') return null
return {
state: parsed.state,
...(typeof parsed.version === 'string' ? { version: parsed.version } : {}),
...(typeof parsed.reason === 'string' ? { reason: parsed.reason } : {}),
}
}
/** The last thing each server said about itself, keyed by server id. */
async function listState() {
return core.query(
return (await core.query(
`SELECT server_id AS serverId, reachable, online, players, max_players AS maxPlayers,
hostname, level, seed, world_size AS worldSize, boot_id AS bootId,
save_created_at AS saveCreatedAt, protocol, updated_at AS updatedAt
save_created_at AS saveCreatedAt, wipe_id AS wipeId, protocol,
last_seen_at AS lastSeenAt, updated_at AS updatedAt,
JSON_EXTRACT(raw, '$.worldReady') AS worldReady,
JSON_EXTRACT(raw, '$.zoneHelper') AS zoneHelper
FROM ${STATE}`,
)).map(withWorldReady)
}
/** One server's observed state, or `null`. The single-row twin of `listState`. */
async function getState(serverId) {
const rows = await core.query(
`SELECT server_id AS serverId, reachable, online, players, max_players AS maxPlayers,
hostname, level, seed, world_size AS worldSize, boot_id AS bootId,
save_created_at AS saveCreatedAt, wipe_id AS wipeId, protocol,
last_seen_at AS lastSeenAt, updated_at AS updatedAt,
JSON_EXTRACT(raw, '$.worldReady') AS worldReady,
JSON_EXTRACT(raw, '$.zoneHelper') AS zoneHelper
FROM ${STATE}
WHERE server_id = ?`,
[serverId],
)
return withWorldReady(rows[0] || null)
}
/**
* Mark a server unreachable **without forgetting what it last said**.
*
* `putState` replaces the row whole, which is right when a sidecar answered: the
* frame it answered with is the complete truth about that server. It is wrong
* when nothing answered. A refresh that cannot reach a sidecar knows exactly one
* new fact — that it could not reach it — and writing the whole row from that
* one fact sets `hostname`, `level`, `seed`, `world_size` and `wipe_id` to NULL.
*
* The site's whole premise is that it renders the last thing each server said
* while every server is off. A row blanked the first time a game host reboots
* cannot do that: the page loses the map, the size, the seed and the wipe, and
* what it shows is not "offline, here is what we know" but "offline, and we have
* never heard of it". It is invisible in every test that stubs a reachable
* sidecar, and it shows up as a page that was complete an hour ago.
*
* So: three columns move, and the description stays where it is.
*/
async function markUnreachable(serverId, reachable = false) {
await core.query(
`INSERT INTO ${STATE} (server_id, reachable, online, players, updated_at)
VALUES (?, ?, 0, 0, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
reachable = VALUES(reachable),
online = 0,
players = 0,
updated_at = CURRENT_TIMESTAMP`,
[serverId, reachable ? 1 : 0],
)
}
@@ -99,14 +213,21 @@ async function putState(state) {
await core.query(
`INSERT INTO ${STATE}
(server_id, reachable, online, players, max_players, hostname, level, seed,
world_size, boot_id, save_created_at, protocol, raw, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
world_size, boot_id, save_created_at, wipe_id, protocol, raw, last_seen_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, IF(?, CURRENT_TIMESTAMP, NULL), CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
reachable = VALUES(reachable), online = VALUES(online), players = VALUES(players),
max_players = VALUES(max_players), hostname = VALUES(hostname), level = VALUES(level),
seed = VALUES(seed), world_size = VALUES(world_size), boot_id = VALUES(boot_id),
save_created_at = VALUES(save_created_at), protocol = VALUES(protocol),
raw = VALUES(raw), updated_at = CURRENT_TIMESTAMP`,
save_created_at = VALUES(save_created_at), wipe_id = VALUES(wipe_id),
protocol = VALUES(protocol),
raw = VALUES(raw),
-- Only a CONNECTED game moves this; an unreachable write leaves it alone,
-- and so does a board the sidecar kept after the game went away (D68).
-- That is what lets a page say how long a server has been down rather
-- than how recently we failed to reach it.
last_seen_at = IF(?, CURRENT_TIMESTAMP, last_seen_at),
updated_at = CURRENT_TIMESTAMP`,
[
state.serverId,
state.reachable ? 1 : 0,
@@ -119,8 +240,11 @@ async function putState(state) {
state.worldSize === undefined ? null : state.worldSize,
state.bootId || null,
state.saveCreatedAt || null,
state.wipeId || null,
state.protocol === undefined ? null : state.protocol,
state.raw ? JSON.stringify(state.raw) : null,
state.seen === false ? 0 : 1,
state.seen === false ? 0 : 1,
],
)
}
@@ -131,7 +255,10 @@ module.exports = {
listServers,
getServer,
upsertServer,
setSchedule,
deleteServer,
listState,
getState,
markUnreachable,
putState,
}

View File

@@ -16,6 +16,7 @@
const core = require('../../core')
const db = require('./servers.db')
const { nextWipe } = require('./nextWipe')
const log = core.logger('servers')
@@ -48,15 +49,50 @@ function withToken(row) {
}
}
return { id: row.id, name: row.name, baseUrl: row.sidecarBaseUrl, token, protocol: row.protocol }
return {
id: row.id,
name: row.name,
baseUrl: row.sidecarBaseUrl,
token,
protocol: row.protocol,
// D104: whether a published news post is said in this server's chat.
announceNews: Boolean(Number(row.announceNews)),
// D142: where that post goes — chat, or a popup.
newsDelivery: row.newsDelivery === 'popup' ? 'popup' : 'chat',
}
}
/**
* How many servers were enabled when this process last looked. An action's
* `cost()` is synchronous and cannot ask the database, so `rust.announce` to
* every server is priced at this — refreshed by every poll, which runs
* continuously. One until the first poll, which is the least a fleet can be.
*/
let enabledCount = 1
function lastEnabledCount() {
return enabledCount
}
/** Every enabled server, with tokens, for the poller. */
async function listForPolling() {
const rows = await db.listServers({ enabledOnly: true })
enabledCount = rows.length
return rows.map(withToken)
}
/**
* One ENABLED server with its token, for a call to its sidecar made on a page's
* behalf (the map's live layers), or `null`. The same rule as `getPublic`: a
* disabled server is not there.
*/
async function getForCalling(id) {
if (!id) return null
const row = await db.getServer(id)
if (!row || !row.enabled) return null
return withToken(row)
}
/**
* The public view: every enabled server and what it last said.
*
@@ -73,6 +109,7 @@ async function listPublic(now = Date.now()) {
function shapePublic(row, state, now) {
const updatedAt = state && state.updatedAt ? new Date(state.updatedAt) : null
const lastSeenAt = state && state.lastSeenAt ? new Date(state.lastSeenAt) : null
const stale = !updatedAt || now - updatedAt.getTime() > STALE_AFTER_MS
return {
@@ -87,11 +124,64 @@ function shapePublic(row, state, now) {
level: (state && state.level) || null,
worldSize: state && state.worldSize != null ? Number(state.worldSize) : null,
seed: state && state.seed != null ? Number(state.seed) : null,
// The CURRENT wipe, from the state row rather than from the newest row in
// `rust_wipes`. The two usually agree and the state row is the one that is
// right when they do not: a wipe list is derived from events that have been
// ingested, so a server that has just wiped and said nothing since has a new
// wipe id here and no row there at all.
wipeId: (state && state.wipeId) || null,
wipedAt: (state && state.saveCreatedAt) || null,
// Two timestamps, because they are two facts. `lastSeenAt` is when a frame
// last arrived and is what a page means by "last reported"; `updatedAt` is
// when this module last wrote the row, and is what `stale` is computed from.
// Reading the second as the first is what made an offline server claim it had
// reported just now, on every failed poll, for as long as it stayed down.
lastSeenAt: lastSeenAt ? lastSeenAt.toISOString() : null,
updatedAt: updatedAt ? updatedAt.toISOString() : null,
stale,
// Phase 16 (D130): `{ at, source }` or null, computed from the operator's
// schedule on every read — never stored, so it cannot go stale after a wipe.
// Public: a wipe date is announced to bring players back, not kept secret.
nextWipe: nextWipe(row, now),
}
}
/**
* The schedule as stored, for the admin form: what the operator typed, not what
* it computes to. A one-off date that has passed is still returned, and the form
* shows it as past (§32.4 reading 5) rather than silently dropping it.
*/
function scheduleOf(row) {
const once = row.wipeOnceAt ? new Date(row.wipeOnceAt) : null
return {
rule: row.wipeRule || 'none',
day: row.wipeDay == null ? null : Number(row.wipeDay),
time: row.wipeTime || null,
tz: row.wipeTz || null,
anchor: row.wipeAnchor || null,
onceAt: once && !Number.isNaN(once.getTime()) ? once.toISOString() : null,
}
}
/**
* One enabled server, or `null`.
*
* It exists because `/rust/servers/:id` is a page and a page needs to be able to
* 404. A detail view built by fetching the list and finding the row in it cannot
* tell "no such server" from "a server that has said nothing" — both are an
* absence — and renders an empty page under a heading for a server that does not
* exist. Filtering happens here, where `enabled = 0` and "never configured" are
* the same answer on purpose: a disabled server is not a 403, it is not there.
*/
async function getPublic(id, now = Date.now()) {
if (!id) return null
const row = await db.getServer(id)
if (!row || !row.enabled) return null
return shapePublic(row, await db.getState(row.id), now)
}
/**
* The admin view: configuration plus reachability, and **no token**.
*
@@ -118,6 +208,10 @@ async function listForAdmin(now = Date.now()) {
reachable: Boolean(state && state.reachable),
bootId: (state && state.bootId) || null,
sidecarProtocol: state && state.protocol != null ? Number(state.protocol) : null,
// D182: whether ZoneManager counts somebody already standing in a zone the
// bridge makes. Anything but `patched` is said on the servers page.
zoneHelper: (state && state.zoneHelper) || null,
schedule: scheduleOf(row),
}
})
}
@@ -132,8 +226,12 @@ module.exports = {
STALE_AFTER_MS,
withToken,
listForPolling,
getForCalling,
lastEnabledCount,
listPublic,
getPublic,
listForAdmin,
shapePublic,
scheduleOf,
encryptToken,
}

Some files were not shown because too many files have changed in this diff Show More