34 Commits

Author SHA1 Message Date
16cfbe194d Merge pull request 'ci(release): derive the version from commit subjects, and add a manual backdoor' (#17) from feature/release-per-merge into main
All checks were successful
Release / release (push) Successful in -30s
SonarQube / analysis (push) Successful in 1m47s
Reviewed-on: #17
2026-08-19 18:07:55 +00:00
8ec21086b5 ci(release): derive the version from commit subjects, and add a manual backdoor
All checks were successful
PR Checks / client-build (pull_request) Successful in 18s
PR Checks / server-tests (pull_request) Successful in 20s
PR Checks / frozen-manifest (pull_request) Successful in 56s
A bundle used to cost a second pull request whose entire content was a number.
The workflow published only when a merge to `main` left `module.json` at a
version with no release yet, so a merge that did not touch that line released
nothing. Measured rather than argued: v0.3.0 (2026-08-12) is the only release
this repo has ever cut, while the nine Teams phases and the cutover landed on
`main` in the week since.

Adopt the engine `link` and `installer` already run - feat!/BREAKING CHANGE ->
major, feat -> minor, fix|perf -> patch, nothing releasable -> no release. The
number that ships is the tag, and CI writes it into the `module.json` inside the
bundle, with an assertion that the rewrite happened: a bundle carrying the wrong
version would install under a number that is not the one it was released as.

`module.json`'s version is kept as a floor rather than deleted - a version above
the newest tag still releases at that version - so the declared model survives as
the special case it always was, and is still how a `coreApi` bump overrules the
subjects. `workflow_dispatch` covers what the rules cannot reach: leave `version`
blank to bump the newest tag by `bump`, or name an exact version. Where the log
and the input disagree the larger bump wins, because a button pressed on a log
full of `feat:` would otherwise publish its `patch` default over a minor's worth
of work.

Two things carried over from `link` at the same time: a tag pushed without a
release behind it is now recovered rather than making that state permanent, and
the changelog moved into the plan step (so the assemble step clears `$OUT`, not
`dist/`, which now holds it).

On this repo's `main` the engine computes v0.4.0. The workflow still never
writes to a branch.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-19 13:01:31 -05:00
637121bce3 Merge pull request 'feat(guilds): a UO guild is a Team (Teams cutover 5/6)' (#16) from edge into main
All checks were successful
SonarQube / analysis (push) Successful in 2m18s
Release / release (push) Successful in 7s
Reviewed-on: #16
2026-08-19 09:02:38 +00:00
fe176920c5 ci(core-ref): pin to the Teams cutover, not a phase 3 edge sha
All checks were successful
PR Checks / client-build (pull_request) Successful in 25s
PR Checks / frozen-manifest (pull_request) Successful in 49s
PR Checks / server-tests (pull_request) Successful in 8m40s
The pin said "edge @ Teams phase 3" and edge is about to stop existing. More to
the point, this module has since gained the Team provider, three declared slots,
the /guild command and the contribution names on those slots - none of which the
pinned core knew about, so the frozen-manifest job has been proving this module
against a core older than half of it.

routes.manifest.json does not move: the job compares core-with-module against
core-without-module, so core's own Teams routes cancel out and what is left is
this module's 73, unchanged. Verified locally against the cutover core before
moving the pin rather than after.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-19 04:00:01 -05:00
d98f0c1a3d Merge pull request 'feat(guilds): name the core contribution each declared slot wants' (#15) from feature/teams-slot-contributions into edge
Reviewed-on: #15
2026-08-19 06:19:52 +00:00
1a13f680f5 feat(guilds): name the core contribution each declared slot wants
Some checks failed
PR Checks / client-build (pull_request) Successful in 27s
PR Checks / frozen-manifest (pull_request) Failing after 47s
PR Checks / server-tests (pull_request) Failing after 13m23s
Core no longer fills a slot by name - it offers a contribution and the module
that owns the page says where each one goes (MODULE_API 1.6.0, amended). The
three slot names are unchanged and stay this module's own vocabulary; what is
new is the second argument saying which of core's three contributions belongs
in each place.

Nothing here worked differently before. The change is for every game that is
not this one: core used to fill the literal name uo.guild.detail, so a second
module declaring a place under its own id got an empty page and no error.

The registration fake gained the same validation core does, including the
contribution catalogue - written down rather than imported, since this suite
runs against the built chunk with no core in the process, which makes it a
claim about core that has to be re-read when core's list changes.

42 client tests, 437 server tests.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-19 01:15:49 -05:00
7d0378842b Merge pull request 'feat(guilds): /guild — the module's own chat command' (#14) from feature/teams-phase7-slash-commands into edge
Reviewed-on: #14
2026-08-19 00:16:11 +00:00
466842c6f2 fix(guilds): do not offer linking where linking cannot reach
Some checks failed
PR Checks / server-tests (pull_request) Successful in 28s
PR Checks / client-build (pull_request) Successful in 17s
PR Checks / frozen-manifest (pull_request) Failing after 35s
Found on the live rig, with the shard's guild feature gated to staff: the
refusal still read "link your account — this shard shows guild information to
linked players". Signing in reaches `logged_in` and linking a game account
reaches `player`; `staff` and `admin` are roles an operator grants, and no
amount of linking earns them. Inviting someone to do something that changes
nothing is worse than plainly saying no.

Also drops the host name from the list embed's title. `ctx.site` carries a base
URL and no brand name, so naming the deployment there could only ever mean
printing its hostname into a title on the shard's own Discord server.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-18 19:08:22 -05:00
2d1d91e372 feat(guilds): /guild, the module's own chat command
The first command through `api.registerSlashCommands` (MODULE_API 1.6.0,
TEAMS.md §7.1). The definition and the handler both live here; the bot pulls the
definition and runs no line of this module.

`/guild` and not `/team`, deliberately. Core does not own the word for a Team —
that is what deleted its Team pages in phase 3 — so it does not publish the noun
in a channel either. Core ships the dispatcher and zero commands.

The audience rungs are re-resolved in the handler rather than assumed: a shard
that gates guilds to staff does not become public because the question arrived
over Discord. The provider's own staleness guard is honoured too, so a stale
board answers "not connected" instead of reporting what it still holds, and
`resolveUserId` is exported rather than copied so "linked" means here what it
means on the roster.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-18 18:53:45 -05:00
990a50b491 Merge pull request 'feat(guilds): a third place on the guild page, and where that page lives' (#13) from feature/teams-phase6-notifications into edge
Reviewed-on: #13
2026-08-18 23:10:02 +00:00
c57310c505 feat(guilds): a third place on the guild page, and where that page lives
All checks were successful
PR Checks / server-tests (pull_request) Successful in 23s
PR Checks / client-build (pull_request) Successful in 17s
PR Checks / frozen-manifest (pull_request) Successful in 34s
Two lines only core cannot supply for itself.

`uo.guild.header` is a third declared slot, at the top of the page, for core's
per-Team notification control. A third rather than a corner of the feed because a
slot holds one component and the first fill wins: the control is an action ON this
page and the other two are content IN it, and separate slots are what let this
module say so.

`pageUrlTemplate` tells core where a guild page actually is. Teams are a contract
primitive with no core surface — core owns the tables and the access rules, this
module owns the word "guild" and therefore the page — which leaves core unable to
write a link to one. A notification email that cannot take you to the thread it is
about is most of the way to useless. Core substitutes `{externalId}` and does
nothing else with it; a template naming its own host is refused at registration.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-18 14:35:36 -05:00
7ce78e303c Merge pull request 'feat(guilds): declare a second place on the guild page, for core's forum' (#12) from feature/teams-phase4-forum-slot into edge
Reviewed-on: #12
2026-08-18 14:17:46 +00:00
46e3f5a127 ci(core-ref): bump the pin past registerTeamProvider
All checks were successful
PR Checks / client-build (pull_request) Successful in 15s
PR Checks / server-tests (pull_request) Successful in 19s
PR Checks / frozen-manifest (pull_request) Successful in 42s
`frozen-manifest` has been failing since Teams phase 2, on this PR and on #11
before it, for a reason that has nothing to do with either: the pinned core
(website#140, the module-system de-UO slice) predates `api.registerTeamProvider`,
which this module has called since phase 1 of its Teams work. The module therefore
fails to LOAD in the pinned checkout — "api.registerTeamProvider is not a function"
— and a module that does not load adds no routes, which the job correctly reports
as the module having removed everything it serves.

So the red was real and was pointing at the pin, exactly as the pin's own comment
says it should: core moves for reasons that have nothing to do with this module,
and a bump is a deliberate commit saying which core the module was last proved
against.

Bumped to `edge` at Teams phase 3 (website#152) — the first core that has both
`registerTeamProvider` and the roster projection this module now implements.
Reproduced the whole job locally against that core: core's own manifest is current
at the new pin, the module loads, and the difference is 73 routes, all documented.
`routes.manifest.json` is unchanged and needed no regeneration, which is the
expected result for a client-only change.

Not bumped to the phase 4 core, deliberately: that is website#153 and is not merged
yet. Nothing in this module needs it — the second slot is a client-side
declaration, invisible to the route manifest.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-18 07:31:58 -05:00
9d0a197008 feat(guilds): declare a second place on the guild page, for core's forum
Some checks failed
PR Checks / client-build (pull_request) Successful in 14s
PR Checks / frozen-manifest (pull_request) Failing after 34s
PR Checks / server-tests (pull_request) Successful in 8m40s
The mirror of the activity feed, one phase later. Core owns the Team forum —
membership, manual grants and the member/guest split are all core's rules, and a
module reimplementing any of them would be reimplementing a security boundary — but
core publishes no Team page, because it does not own the word "guild". So this
module declares the place and core puts the forum in it.

TWO declarations rather than one, and that is the interesting part. A slot holds one
component and the first fill wins, so folding the forum into `uo.guild.detail`
alongside the feed would hand core the decision about where each of its two
contributions sits on a page this module owns. Separate slots also keep them
independent: with the forum switched off, the feed renders exactly as before.

The registration test now asserts the set of declared slots and that EVERY one of
them is rendered by the page that owns it, rather than naming a single slot twice.
A slot nothing renders is a slot core fills into the void.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-18 07:24:37 -05:00
eb30e4ae37 Merge pull request 'feat(guilds): the roster projection, a guild detail page, and the slot core fills' (#11) from feat/teams-phase3-projection-slot into edge
Reviewed-on: #11
2026-08-18 02:12:18 +00:00
dda0e32dd3 feat(guilds): a guild detail page, and the slot core puts the feed in
Some checks failed
PR Checks / client-build (pull_request) Successful in 16s
PR Checks / frozen-manifest (pull_request) Failing after 33s
PR Checks / server-tests (pull_request) Successful in 8m46s
The module's half of the org lead's correction: Teams is the contract, guilds
are the presentation, and the presentation is this module's.

Adds `/uo/guilds/:id` — the detail view the board never had — with the roster
from this module's OWN board, which is the same data it answers core's Team
provider from. Reading core's projection of our own answer back would be a round
trip through a staler copy of it.

The page declares `uo.guild.detail` and core fills it with the Team activity
feed. That is the one part of this page core cannot hand over: only core can
resolve whether the viewer is inside the Team, and the public/members split on
that feed is a security boundary. The guild is named in OUR terms — core maps
its own Team from the module id and the external id — so this module never holds
core's row id or slug.

`TeamOverviewStrip` is deleted with the core Team page it filled.
`team.member.row` is not declared here either: the useful thing to put in a
roster row is a link to the character behind it, and nothing core could supply
identifies one.

`GET /public/shard/guilds/:id` backs the page, gated and projected through the
same `guilds` feature as the board — so an operator who raises that audience
raises this too, and the locked acct/webId fields never survive below admin. A
roster is where those appear in bulk, which makes this the endpoint where
getting the projection wrong would matter most.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 20:58:30 -05:00
d4aa5ade12 feat(teams): project rosters by audience rung, and add to the Team page
The module's half of TEAMS.md phase 3.

`projectRoster` is the optional fourth provider method and the only one core
calls on a request path. Core holds the roster and owns its public shape; the
question that is this module's is who is allowed to look, because the audience
rungs and their configuration live here.

The answer is all-or-nothing, which is the honest translation rather than a
shortcut: a rung is a property of the FEATURE, and there is no configuration in
which some members of a guild are public and others are not.

The refusal semantics INVERT here, and the tests say so. For the other three
methods a refusal means "change nothing" and an empty array would be
destructive. Core fails CLOSED on this one, so the dangerous answer is the
opposite — returning every key because the config could not be read would
publish a roster an operator gated to staff. Every path that cannot reach a
confident answer refuses, including the catch.

The anonymous case is answered directly rather than by handing `viewerLevel` a
synthetic request. Given one with no `req.user` it falls through to
`auth.getUserFromRequest`, which expects real cookies and throws on a fake — and
that throw would have become a refusal, so every anonymous visitor would have
been served an empty roster on a shard whose guilds are public. Caught by the
tests, not by reading.

`team.overview` gets a live population reading beside core's stored one. Core's
number comes from the last roster sync and is coarse by construction; this is
the `presence.online` feed this module already holds. It is explicitly not a
per-Team presence figure — the shard publishes a global aggregate and no
per-guild breakdown exists on the wire, so claiming one would be inventing a
number — and it renders nothing at all when it has nothing true to say.

`team.member.row` is left unfilled. The useful thing to put there is a link to
the character behind a row, and the props core can supply do not identify one:
the member key and the site account id are withheld from every public roster.
An empty cell beats a guess.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 20:16:22 -05:00
0d618599cf Merge pull request 'feat(teams): ingest guild rank, and report every leader rather than one' (#10) from feat/protocol4-guild-rank into edge
Reviewed-on: #10
2026-08-17 22:48:54 +00:00
76b2321f25 Merge pull request 'feat(teams): answer core's Team provider from the guild board' (#9) from feat/teams-phase2-provider into edge
Reviewed-on: #9
2026-08-17 22:48:20 +00:00
99d1ca25a7 feat(teams): ingest guild rank, and report every leader rather than one
Some checks failed
PR Checks / client-build (pull_request) Successful in 15s
PR Checks / server-tests (pull_request) Successful in 20s
PR Checks / frozen-manifest (pull_request) Failing after 34s
The module half of the Protocol 4 rank amendment (servuo-plugins, same wire
version -- Protocol 4 is unreleased on `edge`, so it is amended rather than
bumped).

`shard_guild_members` gains `rank`, `rank_cliloc` and `rank_name`. The provider
then answers the question it previously could not: `getTeamLeaders()` returns
EVERY member at rank 4, not just the board's single `leader_serial`. That
limitation was the whole reason the wire grew a per-member rank -- TEAMS.md §2.5
treats multiple leaders as the normal case and core has always supported them.

The board's `leader_serial` is folded in as a floor rather than replaced. It
comes from a different frame, so on a shard whose roster has not been re-emitted
since the amendment it is the only leadership signal there is, and moving to
ranks must not lose it.

## NULL rank is a real state, and it is load-bearing

The shard withholds the rank for a staff account, because ServUO's
`PlayerMobile.GuildRank` reports Leader for anyone at GameMaster or above
whatever their actual rank. Every layer here preserves that:

  - the ingest stores NULL rather than defaulting to 0, which would be a
    demotion this code invented;
  - `leader` requires an integer rank >= 4, so absence is never leadership;
  - the leaders query compares on `rank`, and NULL is excluded by the comparison.

Reading a missing rank as either 0 or "leader" would republish the exact lie the
shard went out of its way not to send.

## Rank labels

Three sources, in order: a custom rank's literal string, then the operator's
cliloc table, then the five standard names. The last exists because the cliloc
table is populated only if someone ran the client-file extraction, and a roster
on a shard that has not should still read "Warlord" rather than nothing. A
failing lookup falls back rather than failing the roster -- a label is decoration,
and losing it must not lose the data.

`rank` is backticked everywhere it is written, like `int` on shard_online: it is
reserved in MySQL 8 and merely a keyword in MariaDB, so it parses bare here and
must not be relied on to.

The schema fragment carries ALTERs as well as the CREATE. No production install
has this table -- it is new in an unreleased protocol -- but `edge` deployments do,
from the roster work that landed before the amendment, and CREATE TABLE IF NOT
EXISTS adds a table and never a column. Same gap the sidecar's own store hit when
`guilds.members` was added.

## Verification

The unit tests stub the db layer, so the round trip was proved separately: the
VERBATIM roster frame captured from the live ServUO run was fed through the real
ingest into MariaDB and then read back through the provider.

  stored:   0x1F5 rank=4  0x1F6 rank=3  0x1F7 rank=2  0x1F8 rank=1
            0x1F9 rank=NULL (the GameMaster)  0x2E0 rank=4
  provider: leaders = [0x1F5, 0x2E0]   <- two, which the board alone cannot express
            labels  = Leader / Warlord / Emissary / Member, with no cliloc table
            0x1F9   = not a leader, no label

9/9 checks. Suite 413 -> 421 tests, all passing.

Refs docs/link/v4.md §2.3, docs/website/TEAMS.md §2.5

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 17:42:32 -05:00
c6929c6bae fix(teams): take query from the core facade, not a core.db that does not exist
Some checks failed
PR Checks / client-build (pull_request) Successful in 23s
PR Checks / server-tests (pull_request) Successful in 29s
PR Checks / frozen-manifest (pull_request) Failing after 40s
The Team provider's db layer built its query helper as `core.db.query(...)`. The
facade has no `db` member -- every other *.db.js in this module destructures
`query` from it directly -- so every call threw `Cannot read properties of
undefined (reading 'query')`.

The failure mode is the bad part. That throw is caught by the provider's own
error handling and turned into `{ ok: false, reason: 'roster unreadable: …' }`,
which is a perfectly valid refusal -- so core would have accepted it, held the
projection it had, and reported staleness. A provider that answers correctly and
never returns data, forever, with nothing in any log louder than a warning.

Invisible to the unit tests because they stub every db function, so the helper
was never called. Found by running a real roster frame through the ingest and
then asking the provider what it saw, against the real database.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 17:41:22 -05:00
51e58104bf Merge pull request 'feat(teams): answer core's Team provider from the guild board' (#9) from feat/teams-phase2-provider into edge
Reviewed-on: #9
2026-08-17 22:19:01 +00:00
268449f2a6 feat(teams): answer core's Team provider from the guild board
Some checks failed
PR Checks / client-build (pull_request) Successful in 16s
PR Checks / server-tests (pull_request) Successful in 21s
PR Checks / frozen-manifest (pull_request) Failing after 44s
A UO guild is a Team. This registers module-uo as the authoritative source of
them (MODULE_API 1.6.0, docs/website/TEAMS.md §2.3) and answers the three
questions core asks, from the board and the roster Protocol 4 put there.

`externalId` is the persistent ServUO `Guild.Id`, which survives a rename -- so
core sees "an id whose name changed" and applies its rename rule rather than an
unrelated new guild appearing beside the old one. That mapping is this module's
to make: only the game knows what identity survives what.

The most important code here is the refusal guard, and it is deliberately
conservative. Core's contract is that module unavailability becomes staleness and
never emptiness, and this module is the only thing that can honour it -- an empty
array from here reads as an authoritative "there are none", and core archives
Teams and departs members from an authoritative answer. Three states refuse: no
uo-link configured, the integration disabled, and the socket not connected.

**The third is the one worth arguing about.** The board is durable and survives an
outage, so serving it while disconnected looks harmless. It is not: core cannot
tell a board five minutes stale from one five days stale, and a complete answer
licenses destruction. There is a test named for that.

A fourth refusal has no equivalent anywhere else: a guild whose roster has not
arrived. Protocol 4's roster comes on its own frames, separately from the
`guild.update` that creates the board row, so there is a real window where a
155-member guild has zero roster rows. The board's own `members` count is the only
thing that distinguishes "the roster is late" from "this guild is empty", and it
is checked -- with the count in the refusal message, because it is the evidence.
The other side is tested too: when the board says zero, an empty roster is the
truth and withholding it would freeze a disbanding guild's membership forever.

Two limitations, both honest and both in the code as comments:

  - **`rankLabel` is null.** The wire's roster member is the standard actor object
    (`serial`, `name`, `player`, `acct?`, `webId?`) and carries no guild rank.
    Inventing a label from the leader flag would be core displaying something this
    module made up.

  - **One leader, not several.** TEAMS.md §2.5 expects multiple leaders from
    `GuildRank.Rank >= 4` and core supports them, but Protocol 4 does not put rank
    on the wire, so the only leadership visible here is the board's single
    `leader_serial`. Raising it to the full set is a protocol change, not
    something this module can fix.

`online` comes from `shard_online` rather than the roster, which carries no
per-member presence and only a board-level count -- the same source the public
"who's online" surface already uses. `userId` prefers the roster's own `web_id`
(what the shard asserted at roster time) and falls back to the `shard_account_links`
join for a member whose row predates their link; resolving it here rather than in
core is the contract, since core reading `shard_account_links` would be core
naming a module's table.

`coreApi` stays `^1.3.0` -- 1.6.0 satisfies it, which is what makes the bump minor.

18 provider tests plus two on the entry point: that all three methods are
registered, and that registration performs no query. The second matters because
register() runs while core's app.js is still being required with the pool pointed
at a dead port, which both routeManifest.js and swagger.js depend on.

`fakeApi` gained `registerTeamProvider` with the same `once` rule core applies --
one provider per deployment, so a second registration has to fail here too rather
than passing a shape core rejects at load.

411 -> 413 tests, all passing.

Refs docs/website/TEAMS.md §2.3, Part 12 phase 2

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 15:31:58 -05:00
e93361aa48 Merge pull request 'feat(shard): ingest guild rosters and departures (protocol 4)' (#8) from feat/teams-phase1-guild-roster into edge
Reviewed-on: #8
2026-08-17 19:29:05 +00:00
2fa4d87a40 feat(shard): ingest guild rosters and departures (protocol 4)
All checks were successful
PR Checks / client-build (pull_request) Successful in 15s
PR Checks / server-tests (pull_request) Successful in 19s
PR Checks / frozen-manifest (pull_request) Successful in 38s
Protocol 2 gave the guild board a member *count* and nothing else, so the Guilds
page could say a guild had 155 members but never who they were, and
findGuildForActor deliberately answered only for leaders because membership for
rank-and-file was not in the feed at all. Protocol 4 puts it there.

`shard_guild_members` holds one row per member per guild, keyed on
(guild_id, serial). `guild.roster` replaces a guild's rows; `guild.leave` removes
one. A guild.remove now clears the membership too, so a disbanded guild does not
leave orphaned rows behind.

The chunking needs explaining. A roster over the shard's per-frame cap arrives as
several frames carrying seq/more/total. The sidecar reassembles them for its own
GET /guilds board, but the live WebSocket feed and the /history backfill both
carry the individual frames — so this ingest sees them unreassembled.

It copes without buffering, because a table expresses what the sidecar's single
JSON column could not: the frame carrying seq 0 clears the guild first, and every
frame then upserts its own rows. Upsert rather than insert because the /history
backfill replays stored frames on every reconnect, and a redelivery has to be a
no-op rather than a duplicate-key error. The cost is a sub-second window during a
multi-frame update where the table holds part of a roster; buffering to close it
would duplicate the sidecar's reassembly for a projection that is already only as
fresh as a 60s sweep.

On visibility: both kinds are mapped to the existing `guilds` feature. Without
that mapping rule 2 fails an unmapped kind closed to admin-only, which would have
quietly kept rosters off the public page forever. Mapping them is safe because a
roster is the first frame carrying locked fields inside an ARRAY of actors rather
than one nested actor, and the projection walker already recurses into arrays and
matches acct/webId by suffix — so a member's account name is stripped below admin
by exactly the rule that already strips guild.leader.acct. There is a test for
that specifically, because the difference is a public page listing character names
versus one publishing 150 account names.

`acct`/`web_id` are still stored, since that is what lets a linked member be
matched to a site user; they are just never projected below admin.

guild.leave is appended to the event log, as the departure counterpart to
guild.join and for the same reason — it is what a "so-and-so left" feed reads.
guild.roster stays out: it is board state like guild.update, and it is the one fat
frame on the wire, so logging it would put a full membership snapshot into
shard_events on every membership change.

The PUBLIC_KINDS guard test caught the addition, which is what it is for; its
expected set now carries a v4 group alongside the v3 one.

Refs: docs/website/TEAMS.md Part 12 Phase 1

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-17 12:57:26 -05:00
97e2fddfcd Merge pull request 'chore(ci): scan this repo with SonarQube (phase 4, slice 0)' (#7) from chore/sonarqube into main
All checks were successful
Release / release (push) Successful in 8s
SonarQube / analysis (push) Successful in 1m54s
Reviewed-on: #7
2026-08-12 07:37:39 +00:00
62c8ee68b4 chore(ci): scan this repo with SonarQube (phase 4, slice 0)
All checks were successful
PR Checks / client-build (pull_request) Successful in 14s
PR Checks / frozen-manifest (pull_request) Successful in 34s
PR Checks / server-tests (pull_request) Successful in 8m50s
Until now this was the one part of the platform that had never been scanned.
The 75 files here arrived in the Phase 3 extraction and left their Sonar
history behind in core's project, so a whole module's worth of shipped code
has no dashboard at all.

Adds sonar-project.properties (project key Module-uo) and a sonarqube.yml
mirroring website's: push to main, never a PR gate, nothing waiting on the
quality gate.

Two things differ from core's config, both because this repo is shaped
differently:

  - There is no src/ to point sonar.sources at — the server half keeps
    boot.js/core.js/index.js at server/ root beside its subdirectories — so
    the whole tree is included and the non-source parts are excluded. That
    direction is deliberate: a new top-level server directory is scanned by
    default rather than silently unscanned.
  - server/scripts and client/scripts are IN. checkImports.js and
    checkExternals.js are the enforcement of MODULE_API.md 5.1 and 3.6, they
    carry their own test suites, and both have already shipped defects a
    reviewer missed. Build code that decides whether a release is allowed out
    is not throwaway code.

The workflow builds the client chunk before running either suite, for the
reason pr-checks.yml already calls load-bearing: build.test.js and
registration.test.js read dist/entry.js and SKIP without it, so the other
order reports coverage for a suite that quietly asked less than it looks like
it did.

Both suites run from the repo root rather than with --prefix, so the LCOV SF:
paths come out repo-root-relative and resolve against sonar.sources. That is
why the server suite's --require is spelled out here instead of reusing
`npm test --prefix server`, whose path is relative to server/.

Verified locally: 385 server test cases across 57 covered files and 40 client
cases, both LCOV and Generic Test Execution XML well-formed with
repo-root-relative paths.

Needs one-time setup in the Gitea UI before it can run — secret SONAR_TOKEN
and variable SONAR_HOST_URL, same as the other repos.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-12 02:36:11 -05:00
e81b61d044 Merge pull request 'feat(release): ship an OpenAPI fragment, a frozen manifest and a bundle (phase 3, slice 5)' (#6) from feature/close-phase3 into main
All checks were successful
Release / release (push) Successful in 24s
Reviewed-on: #6
2026-08-12 04:11:29 +00:00
a0c24456c7 ci: retry npm registry reads before failing a check
All checks were successful
PR Checks / client-build (pull_request) Successful in 14s
PR Checks / server-tests (pull_request) Successful in 18s
PR Checks / frozen-manifest (pull_request) Successful in 33s
The frozen-manifest job read ETIMEDOUT from the registry installing the client
deps, after it had already cloned core at the pin and proved core's own manifest
regenerates — a red X that meant nothing about this PR. There are five `npm ci`
calls across the three jobs and the runner is shared, so this will recur.

npm's own retry, turned up at the workflow level so every install gets it.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 23:08:48 -05:00
044211fd41 fix(docs): repair the escaped apostrophes, and document this module's env vars
Some checks failed
PR Checks / client-build (pull_request) Successful in 14s
PR Checks / frozen-manifest (pull_request) Failing after 34s
PR Checks / server-tests (pull_request) Successful in 8m49s
Nineteen `#swagger` descriptions carried a `\'` inside a single-quoted string.
That is correct JavaScript and wrong here: swagger-autogen does not evaluate the
annotation as JS, so the backslash survives into the spec and Swagger UI renders
"the shard\'s published ruleset" to a reader. Replaced with a typographic
apostrophe, which the same files already use elsewhere.

Found by opening /api/docs in a browser against a real core with this module
installed — the fragment was valid JSON, the paths were right, every test passed,
and it was still wrong on screen. Nothing that reads the artifact can see this;
only reading the rendered page can.

Also documents the four environment variables this module reads
(UOLINK_BASE_URL / _WS_URL / _PROTOCOL, TOWNCRIER_DURATION_SEC). Core's
.env.example is dropping them in the paired website PR: they were never core's,
and a half-copy in two repos goes stale silently.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 22:57:00 -05:00
5cdcf0fbb6 feat(release): ship an OpenAPI fragment, a frozen manifest and a bundle (phase 3, slice 5)
All checks were successful
PR Checks / server-tests (pull_request) Successful in 19s
PR Checks / frozen-manifest (pull_request) Successful in 35s
PR Checks / client-build (pull_request) Successful in 8m49s
The three artifacts that make this module installable and checkable, closing
phase 3's extraction. Nothing about what the module serves changes: the same 72
URLs, the same behaviour.

**The OpenAPI fragment (MODULE_API.md §2.8, §6.1a) was never built, on either
side.** The 417 `#swagger` annotations came across in slice 1 and went nowhere,
and core's /api/docs.json merged nothing — so every route this module serves was
in no spec at all, which is core's standing rule ("never ship a route that isn't
in the spec") being broken by the extraction rather than by a route.

`server/scripts/swaggerFragment.js` generates it. The prefixes are DERIVED: the
script runs the module's own `register()` against a recording api and asks
`require.cache` which file each router came from, so a mount prefix exists in one
place — `server/index.js` — and not in a table beside it. The 31 schemas moved
here from core's swagger.js, namespaced `Uo…` because core wins every key
collision in the merge; `Error` and `ValidationError` stay referenced by core's
names, since they resolve in the merged document.

**The frozen route manifest (§5.3)** is derived too, and by subtraction: CI
clones core at the ref pinned in ci/core-ref.json, generates its manifest without
this module and then with it, and the difference is what this module serves. That
buys the half of §5.3 that matters most for free — a module that shadowed or
displaced one of core's routes shows up as a REMOVAL, not merely as an addition
elsewhere. The same job checks the fragment against ground truth: every route
must have an operation and every operation must be a route.

**The release workflow** publishes `module-uo-<version>.tar.gz` plus a manifest
carrying its sha256. The version is declared in module.json rather than computed
from commit subjects, and the workflow never writes to a branch — it tags and
publishes — so `main` needs no push exception. The bundle is assembled from an
include list, because an exclude list ships whatever it forgot.

Four annotation defects, inherited from core and never visible until something
generated a spec from these files: two `requestBody` literals a brace short (the
route documented with an empty body), and two descriptions whose inner quoting
swagger-autogen cannot survive — it re-quotes `"` and a backtick to `'` before
evaluating, so either inside a single-quoted description ends the string early
and the annotation is dropped. It reports each one and then prints Success in
green, so the generator now captures its diagnostics and makes them fatal.

Also fixed while writing it: passing one shared `doc` to swagger-autogen six
times. It renders components.schemas from an EXAMPLE object and writes the result
back into what it was handed, so each pass re-wrapped the last and the fragment
came out at 484 MB.

- 409 server tests (+21), 40 client tests unchanged
- swagger-fragment.json: 69 paths covering all 72 routes
- routes.manifest.json: 72 routes; core's own surface unchanged, 0 removals
- verified end to end by assembling the bundle exactly as CI will, unpacking it
  into a real core and regenerating the manifest

Refs: docs/website/MODULE_SYSTEM.md §2.7.1, MODULE_API.md §2.8, §5.3, §6.1a

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 22:40:21 -05:00
e468bbd3b9 Merge pull request 'fix(db): own the two settings seeds, and repair the protocol-3 one-shot (phase 3, slice 4)' (#5) from feature/own-settings-seeds into main
Reviewed-on: #5
2026-08-12 03:01:32 +00:00
d70e5e10d0 test(client): assert the URLs this module calls
All checks were successful
PR Checks / client-build (pull_request) Successful in 18s
PR Checks / server-tests (pull_request) Successful in 8m45s
Five assertions that stayed behind in core's `apiClient.test.js` when the
bindings moved in slice 1 — the atlas-vs-shard path split, the query-string
filtering, the slug encoding, the admin atlas methods — plus a new one pinning
the seven admin URLs the shipped Android app calls by name. They were asserting
UO URLs from inside core's suite, which is the boundary Phase 3 removes, and
core's slice-4 deletion of those bindings would otherwise have deleted the
coverage with them.

The fake `window.__rg` carries the REAL react/react-dom/router rather than
stubs: `src/core.js` compares its imported bindings against the published ones
and logs a "bundled its own copy" error when they differ, so stubs make every
run of this file print the exact wording of a real defect.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 21:31:49 -05:00
f7bb3d912e fix(db): own the two settings seeds, and repair the protocol-3 one-shot
Core seeded `game_account_signup` and `uo_link_protocol_3_migrated`, two keys
that name a game concept. That made core's schema declare a module's settings,
which is the structural half of what Phase 3 removes (MODULE_SYSTEM.md §2.7.1,
slice 4). Both INSERTs move here. The keys are deliberately unchanged: they are
live rows on every existing install and renaming one silently resets an
operator's choice to the default.

The marker is not just a tidy-up. It and the `UPDATE uo_link_config SET
protocol = 3` it makes one-shot were adjacent in core's schema.sql until slice 1
moved the UPDATE here and left the INSERT behind — and the two files do not run
together: core's schema is replayed in full before any module fragment. So the
marker existed before the UPDATE ever read it, the NOT EXISTS guard was false on
every boot of an upgraded install, and the migration could never fire. An
install carrying a protocol-2 row would have stayed pinned at 2 against a v3
sidecar, 409ing every REST call — the exact failure the migration prevents.
Latent rather than live: it bites only an install that first boots a
post-slice-1 build while already holding a uo_link_config row, and `edge` has
not cut over.

`schemaFragment.test.js` asserts the order, plus the fragment rules core
validates at load time (leading-verb allowlist, IF NOT EXISTS, grandfathered
table prefixes) — restated here for the same reason manifest.test.js restates
the manifest rules. Its statement splitter is a character walk, because a
comment in this file contains quotes.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-11 21:27:52 -05:00
49 changed files with 13219 additions and 120 deletions

View File

@@ -27,11 +27,29 @@
# Building the chunk in CI is not only a check: it is how the chunk that ships is
# produced, since an operator never builds (MODULE_SYSTEM.md §1.14).
#
# Not here yet, deliberately, because there is nothing for them to act on until
# the extraction is further along: the release workflow (the
# `module-uo-<version>.tar.gz` artifact and its sha256 manifest) and the module's
# own frozen route manifest, which needs core checked out at a pinned ref
# (MODULE_API.md §5.3). Each lands with the slice it checks.
# • `server: check:swagger` — `swagger-fragment.json` describes the routes this
# module registers, today. Core has no way to generate it: core is a prebuilt
# image, this module arrived on a volume afterwards, and it mounts through a
# call no static parser can follow. So the fragment core merges into
# `/api/docs.json` is whatever this repo committed, and a stale one documents
# a URL surface that does not exist (§2.8).
#
# • `frozen-manifest` — the job with the interesting shape. It clones CORE at
# the ref pinned in `ci/core-ref.json`, generates its route manifest twice
# (without this module, then with) and takes the difference. That difference
# is what this module serves, and it is checked three ways: it must match the
# committed `routes.manifest.json`, it must not have REMOVED or changed one of
# core's own routes, and every route in it must have an operation in
# `swagger-fragment.json` — the per-module form of core's rule that a route
# which isn't in the spec doesn't ship (§5.3, §2.8).
#
# Nothing else can ask those questions. Every other check here runs against
# this repo alone, where a mount prefix is a string in `server/index.js` and a
# documented path is a string in a JSON file; whether they name the same URL
# is a fact about a running core, and this is the only job that has one.
#
# Still not here, deliberately: nothing. The release workflow is
# `.gitea/workflows/release.yml` and runs on a tag rather than on a PR.
#
# Enforcement (one-time, in the Gitea UI):
# Repository Settings → Branches → Branch Protection (rule for `main`)
@@ -43,18 +61,34 @@
#
# Runner: the shared self-hosted `ubuntu-latest` runner. These jobs need only
# Node — no Docker socket, no database.
#
# Scope note: `edge` is gated as well as `main`. Multi-phase work lands there
# first, so gating only the `main` hop would run these checks for the first time
# at the cutover — the one moment a red build is most expensive to discover. This
# is the same call `RunicGateway/installer` made for the same reason, and it was
# taken here after a nine-PR Android workstream landed on an ungated `edge` with
# no CI at all. Adding a branch to the `branches:` list is the whole change.
name: PR Checks
on:
pull_request:
branches: [main]
branches: [main, edge]
# A newer push to the same PR cancels the in-flight run.
concurrency:
group: pr-checks-${{ github.ref }}
cancel-in-progress: true
# npm's own retry, turned up. The shared runner reads ETIMEDOUT from the registry
# often enough to matter, and there are five `npm ci` calls across these jobs — a
# red X that means "the network hiccuped" costs a reviewer more than it costs the
# runner to retry, and teaches everyone to re-run rather than read a failure.
env:
NPM_CONFIG_FETCH_RETRIES: 5
NPM_CONFIG_FETCH_RETRY_MINTIMEOUT: 20000
NPM_CONFIG_FETCH_RETRY_MAXTIMEOUT: 120000
jobs:
server-tests:
runs-on: ubuntu-latest
@@ -79,6 +113,9 @@ jobs:
- name: Check the module boundary (MODULE_API.md §5.1)
run: npm run check:imports --prefix server
- name: Check the OpenAPI fragment is current (MODULE_API.md §2.8)
run: npm run check:swagger --prefix server
client-build:
runs-on: ubuntu-latest
timeout-minutes: 20
@@ -107,3 +144,70 @@ jobs:
- name: Check the built chunk's externals (MODULE_API.md §3.6)
run: npm run check:externals --prefix client
# ── The URLs this module actually serves ──────────────────────────────────
#
# Everything above proves the module against itself. This proves it against a
# real core: the one place where "the prefix I register" and "the path I
# document" are the same fact rather than two strings that ought to agree.
#
# The module is COPIED into the core checkout, never symlinked — core's loader
# filters its scan with `entry.isDirectory()`, which reports a link as a link
# and skips it silently, so a symlinked module produces a manifest with no
# module routes in it and a diff that looks like the module registering
# nothing.
frozen-manifest:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
with:
path: module
- uses: actions/setup-node@v4
with:
node-version: 20
# Anonymous HTTPS, and a full clone rather than a shallow one: the pin is a
# commit sha, and `--depth 1` can only fetch a branch tip.
- name: Clone core at the pinned ref (MODULE_API.md §5.3)
run: |
REPO=$(node -p "require('./module/ci/core-ref.json').repo")
REF=$(node -p "require('./module/ci/core-ref.json').ref")
echo "core: $REPO @ $REF"
git clone --quiet "$REPO" core
git -C core checkout --quiet "$REF"
- name: Install core's server deps
run: npm ci --prefix core/server
# Core alone. `--check` first, so a pin that no longer regenerates its own
# committed manifest fails HERE, naming the pin, instead of showing up below
# as this module having removed a route it never touched.
- name: Generate core's manifest without this module
run: |
npm run routes:manifest --prefix core/server -- --check
cp core/server/routes.manifest.json before.json
# The chunk has to exist before the loader will accept the module at all —
# `client.entry` is validated during the manifest step of the scan, and a
# missing one is a load failure, not a warning.
- name: Build the client chunk
run: |
npm ci --prefix module/client
npm run build --prefix module/client
- name: Install the module into core
run: |
mkdir -p core/modules/uo
tar -C module --exclude=.git --exclude=node_modules -cf - . | tar -C core/modules/uo -xf -
npm ci --omit=dev --prefix core/modules/uo/server
- name: Generate core's manifest with this module
run: |
npm run routes:manifest --prefix core/server
cp core/server/routes.manifest.json after.json
- name: Check the frozen manifest and the fragment's coverage
working-directory: module
run: node server/scripts/frozenManifest.js --before ../before.json --after ../after.json --check

View File

@@ -0,0 +1,421 @@
# Build and publish the installable bundle: `module-uo-<version>.tar.gz` plus the
# manifest carrying its sha256 (docs/website/MODULE_SYSTEM.md §2.3, §2.5).
#
# ── What a release IS here ──────────────────────────────────────────────────
#
# **An operator never builds anything** (MODULE_SYSTEM.md §1.14 — the constraint
# the whole module system is shaped around). So a release is not source: it is the
# directory core's loader expects to find at `modules/uo/`, already assembled —
# the prebuilt client chunk, the one runtime dependency installed, the schema
# fragment and the OpenAPI fragment — packed as it will be unpacked. Phase 4's
# admin install downloads the tarball, verifies it against the `sha256` in the
# manifest, and unpacks it onto the volume. Nothing runs `npm` on the way.
#
# ── The version is DERIVED, and the declaration is a floor ──────────────────
#
# This file used to release only when a merge to `main` left `module.json` at a
# version with no release yet — the version DECLARED, never computed, on the
# argument that two sources for one number is how they drift. That was true and
# it was still the wrong trade: it makes every bundle cost a second reviewed PR
# whose entire content is a number, and between 2026-08-12 and 2026-08-19 it cost
# this repo *every* bundle — v0.3.0 was the only release while nine phases of
# Teams work landed, because nothing in them touched that line.
#
# So the engine `link` and `installer` already run is adopted here (MODULE_SYSTEM
# §2.7.1, decision 19 as amended):
#
# feat!: / BREAKING CHANGE -> major feat: -> minor fix|perf: -> patch
# nothing releasable -> no release is cut
# (first ever run, no tag) -> releases what module.json declares
#
# **The declared version is kept as a floor, not deleted.** If `module.json` names
# a version above the newest tag, that version releases — which is the old model
# exactly, surviving as the special case it always was. Raising it by hand is
# still how you say "this one is a minor, whatever the subjects imply", and it is
# still the natural place to move when a `coreApi` bump forces the question. What
# no longer happens is a merge full of `feat:` producing nothing.
#
# The number that ships is therefore the TAG, and CI writes it into the
# `module.json` inside the bundle at assembly time. The committed `module.json` is
# a floor and a starting point, not a record of the last release — `link` reached
# the same arrangement with `Cargo.toml`, for the same reason: a release engine
# that has to commit a bump back to `main` stops working the day someone protects
# the branch, and this one is protected.
#
# ── The backdoor ────────────────────────────────────────────────────────────
#
# `workflow_dispatch` publishes on demand, for the case the rules above cannot
# reach: `module.json` changed in a way worth shipping — a widened `coreApi`, a
# new mount, a capability — with no releasable code behind it. Leave `version`
# blank to bump the newest tag by `bump` (default `patch`), or name an exact
# version to publish that. A dispatch releases even when nothing in the log is
# releasable; that is the entire point of pressing the button.
#
# Re-running on a version that is already released is a no-op, so a rerun after an
# unrelated failure is safe. A tag that exists with no release behind it is NOT a
# no-op — see the recovery branch in the plan step.
#
# This workflow still never writes to a branch. It tags and publishes, so `main`
# needs no push exception.
#
# Prerequisites (Settings → Actions → Secrets on RunicGateway/Module-uo):
# REGISTRY_TOKEN — Gitea access token with `write:repository`, to push the tag
# and create the release.
name: Release
on:
push:
branches: [main]
workflow_dispatch:
inputs:
version:
description: 'Exact version to publish (e.g. 0.4.1). Blank = bump the newest tag by the level below.'
required: false
default: ''
bump:
description: 'Bump level when version is blank: patch | minor | major'
required: false
default: 'patch'
concurrency:
group: release-module-uo
cancel-in-progress: false
env:
GITEA_HOST: gitea.whitlocktech.com
REPO: RunicGateway/Module-uo
jobs:
release:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
# Full history: the plan step reads every tag and every subject since the
# newest one, and a shallow clone has neither.
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Plan the release (version + changelog)
id: plan
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
EVENT: ${{ github.event_name }}
IN_VERSION: ${{ github.event.inputs.version }}
IN_BUMP: ${{ github.event.inputs.bump }}
run: |
set -euo pipefail
mkdir -p dist
git fetch --tags --force >/dev/null 2>&1 || true
DECLARED="$(node -p "require('./module.json').version")"
LAST_TAG="$(git describe --tags --match 'v*' --abbrev=0 2>/dev/null || true)"
CURRENT="${LAST_TAG#v}"
RANGE="${LAST_TAG:+${LAST_TAG}..}HEAD"
echo "module.json declares ${DECLARED}; newest tag is ${LAST_TAG:-<none>}"
SUBJECTS="$(git log --no-merges --format='%s' $RANGE || true)"
BODIES="$(git log --no-merges --format='%B' $RANGE || true)"
BUMP=none
if echo "$BODIES" | grep -qE 'BREAKING[ -]CHANGE' ; then BUMP=major; fi
if echo "$SUBJECTS" | grep -qE '^[a-z]+(\([^)]+\))?!:' ; then BUMP=major; fi
if [ "$BUMP" = none ] && echo "$SUBJECTS" | grep -qE '^feat(\([^)]+\))?:' ; then BUMP=minor; fi
if [ "$BUMP" = none ] && echo "$SUBJECTS" | grep -qE '^(fix|perf)(\([^)]+\))?:' ; then BUMP=patch; fi
bump() { # <x.y.z> <major|minor|patch> -> bumped
IFS=. read -r MA MI PA <<< "$1"
case "$2" in
major) echo "$((MA+1)).0.0" ;;
minor) echo "${MA}.$((MI+1)).0" ;;
patch) echo "${MA}.${MI}.$((PA+1))" ;;
esac
}
# `sort -V` orders version strings, so the higher of two is its last
# line. Used rather than a hand-rolled field compare because 0.10.0 vs
# 0.9.0 is exactly the comparison a string sort gets wrong.
higher() { printf '%s\n%s\n' "$1" "$2" | sort -V | tail -1; }
rank() { case "$1" in major) echo 3 ;; minor) echo 2 ;; patch) echo 1 ;; *) echo 0 ;; esac; }
bigger_bump() { if [ "$(rank "$1")" -ge "$(rank "$2")" ]; then echo "$1"; else echo "$2"; fi; }
VERSION=""
if [ -n "${IN_VERSION:-}" ]; then
# The backdoor's exact form. Deliberately unvalidated against the log:
# a human typed it, and the already-released check below is the only
# guard that matters.
VERSION="${IN_VERSION}"
echo "dispatch: publishing the requested version ${VERSION}"
else
LEVEL="$BUMP"
# A dispatch with nothing releasable in the log still releases — that
# is what the button is for. Where the log DOES say something, the
# larger of the two wins rather than the input: pressing the button on
# a log full of `feat:` without touching the dropdown would otherwise
# publish its `patch` default over a minor's worth of work, and a
# version that undersells its own contents cannot be taken back.
if [ "${EVENT:-}" = workflow_dispatch ]; then
LEVEL="$(bigger_bump "$LEVEL" "${IN_BUMP:-patch}")"
if [ "$BUMP" = none ]; then
echo "dispatch: nothing releasable in the log, bumping ${LEVEL} anyway"
elif [ "$LEVEL" != "$BUMP" ]; then
echo "dispatch: the log says ${BUMP}, the run asked for ${LEVEL} — taking ${LEVEL}"
fi
fi
if [ -z "$CURRENT" ]; then
VERSION="$DECLARED" # first ever release: ship what is declared
elif [ "$LEVEL" != none ]; then
VERSION="$(bump "$CURRENT" "$LEVEL")"
fi
# The floor. A `module.json` above the newest tag releases at that
# version even when the log says nothing and even when the log says
# patch — which is the pre-2026-08-19 model, kept as a special case.
if [ -n "$CURRENT" ] && [ "$DECLARED" != "$CURRENT" ] \
&& [ "$(higher "$DECLARED" "$CURRENT")" = "$DECLARED" ]; then
if [ -z "$VERSION" ] || [ "$(higher "$DECLARED" "$VERSION")" = "$DECLARED" ]; then
echo "module.json declares ${DECLARED}, above both ${CURRENT} and the derived version — releasing that."
VERSION="$DECLARED"
fi
fi
fi
RELEASE=true
if [ -z "$VERSION" ]; then
RELEASE=false
VERSION="$CURRENT"
echo "Nothing releasable since ${LAST_TAG} (no feat/fix/perf/breaking subject) — standing down."
fi
# An existing tag is NOT automatically "nothing to do". A tag with no
# release behind it means a previous run tagged and then died before
# publishing — which is what happened on servuo-plugins' first release,
# where absent secrets took the release API call to 401 after the tag
# had already been pushed. Standing down on the tag alone makes that
# state permanent. Note this deliberately OVERRIDES the RELEASE=false
# above: with the tag in place there is nothing releasable after it, so
# the normal path would stand down, which is why it could never
# self-heal. Anything other than 200/404 — a network failure, a bad
# token — is not evidence of absence, and guessing "no" would publish
# over a good release, so refuse instead.
REUSE_TAG=false
if [ -n "$VERSION" ] && git rev-parse -q --verify "refs/tags/v${VERSION}" >/dev/null; then
CI_TOKEN="$(printf '%s' "${REGISTRY_TOKEN:-}" | tr -d '\r\n')"
REL_HTTP="$(curl -s -o /dev/null -w '%{http_code}' \
-H "Authorization: token ${CI_TOKEN}" \
"https://${GITEA_HOST}/api/v1/repos/${REPO}/releases/tags/v${VERSION}" || echo 000)"
case "$REL_HTTP" in
200) echo "v${VERSION} is already released — nothing to do."; RELEASE=false ;;
404) echo "::warning::Tag v${VERSION} exists but has no release — a previous run failed after tagging. Reusing the tag and publishing the release it is missing."
REUSE_TAG=true; RELEASE=true ;;
*) echo "::error::Could not determine whether v${VERSION} is released (HTTP ${REL_HTTP}). Refusing to guess."; exit 1 ;;
esac
fi
# Changelog range. A recovery run has nothing after the tag, so
# summarize what the tag itself contains rather than emitting an empty
# list: the range that produced it, i.e. previous-tag..this-tag.
if [ "$REUSE_TAG" = true ]; then
PREV_TAG="$(git describe --tags --match 'v*' --abbrev=0 "v${VERSION}^" 2>/dev/null || true)"
CL_RANGE="${PREV_TAG:+${PREV_TAG}..}v${VERSION}"
SINCE="$PREV_TAG"
else
CL_RANGE="$RANGE"
SINCE="$LAST_TAG"
fi
CL_SUBJECTS="$(git log --no-merges --format='%s' $CL_RANGE || true)"
{
echo "## module-uo v${VERSION}"
echo
echo "Install from the website's Admin → Modules screen by pasting the URL of"
echo "\`module-uo-${VERSION}.json\`, or unpack the tarball onto the modules volume"
echo "as \`modules/uo/\`. Requires a core whose \`MODULE_API_VERSION\` satisfies"
echo "\`$(node -p "require('./module.json').coreApi")\`."
echo
FEATS="$(echo "$CL_SUBJECTS" | grep -E '^feat' || true)"
FIXES="$(echo "$CL_SUBJECTS" | grep -E '^(fix|perf)' || true)"
[ -n "$FEATS" ] && { echo "### Features"; echo "$FEATS" | sed 's/^/- /'; echo; }
[ -n "$FIXES" ] && { echo "### Fixes"; echo "$FIXES" | sed 's/^/- /'; echo; }
echo "### All changes"
if [ -n "$SINCE" ]; then echo "Since ${SINCE}:"; fi
echo "$CL_SUBJECTS" | sed 's/^/- /'
echo
echo "### Verifying this download"
echo
echo "Releases are **unsigned** — the \`sha256\` in \`module-uo-${VERSION}.json\` is the"
echo "trust anchor, and the website verifies it before unpacking."
echo
echo '```bash'
echo "sha256sum -c SHA256SUMS --ignore-missing"
echo '```'
} > dist/CHANGELOG.md
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "tag=v${VERSION}" >> "$GITHUB_OUTPUT"
echo "release=${RELEASE}" >> "$GITHUB_OUTPUT"
echo "reuse_tag=${REUSE_TAG}" >> "$GITHUB_OUTPUT"
echo "bump=${BUMP}" >> "$GITHUB_OUTPUT"
echo "==> release=${RELEASE} version=${VERSION} bump=${BUMP} declared=${DECLARED} last_tag=${LAST_TAG:-<none>}"
# Before anything is built or tagged, so a repo without secrets fails
# legibly rather than half-publishing: the tag push can succeed on the
# credential actions/checkout left in the local git config while the
# release API call 401s, leaving the repo tagged and unreleased.
- name: Verify release credentials are configured
if: ${{ steps.plan.outputs.release == 'true' }}
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -euo pipefail
if [ -z "$(printf '%s' "${REGISTRY_TOKEN:-}" | tr -d '\r\n')" ]; then
echo "::error::Missing Actions secret REGISTRY_TOKEN (needs write:repository) on ${REPO}."
exit 1
fi
echo "Release credentials present."
- name: Build the client chunk
if: ${{ steps.plan.outputs.release == 'true' }}
run: |
npm ci --prefix client
npm run build --prefix client
# `--omit=dev` and then PACKED: express, express-validator and swagger-autogen
# are build- and test-time only — the shipped half is handed express on `ctx`
# (MODULE_API.md §2.3) — and `ws` is the one runtime dependency. Node resolves
# it by walking up from `modules/uo/server/`, which is why it ships inside the
# tarball rather than being installed on the operator's box.
- name: Install the shipped runtime dependency
if: ${{ steps.plan.outputs.release == 'true' }}
run: npm ci --omit=dev --prefix server
# ── Assemble exactly what an operator's volume gets ──────────────────
#
# Stated as an INCLUDE list, not an exclude list. An exclude list ships
# whatever it forgot: the day someone adds `server/tools/` with a scratch
# credential in it, an exclude list packs it and nobody finds out.
- name: Assemble the bundle
if: ${{ steps.plan.outputs.release == 'true' }}
run: |
set -euo pipefail
VERSION="${{ steps.plan.outputs.version }}"
OUT="dist/module-uo-${VERSION}"
rm -rf "$OUT" && mkdir -p "$OUT"
# The manifest core reads — with the RELEASED version written into it.
# The committed `module.json` is a floor, not a record of the last
# release (see the header), so copying it verbatim would ship a bundle
# whose `installed_modules` row and admin screen disagree with the tag
# it came from. This is the one place the derived number becomes the
# module's own.
jq --arg v "$VERSION" '.version = $v' module.json > "$OUT/module.json"
# The two fragments, and the licence the code is under — a bundle that
# ships GPL code without its licence is not distributable.
cp swagger-fragment.json LICENSE.md README.md "$OUT/"
# The server half, minus what never runs inside core's process.
mkdir -p "$OUT/server"
for d in boot.js core.js index.js config data db model router utils; do
cp -r "server/$d" "$OUT/server/"
done
cp server/package.json "$OUT/server/"
cp -r server/node_modules "$OUT/server/"
# The client half is the BUILT chunk only. `client/src` is 5,000 lines
# of source an operator has no use for and core will never read.
mkdir -p "$OUT/client/dist"
cp client/dist/entry.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
# entry point is missing fails on an operator's box with a
# `startup_failed` row instead of here. The version assertion guards the
# rewrite above — a bundle that still carries the declared version would
# install under a number that is not the one it was released as.
node -e '
const fs = require("fs"), path = require("path");
const [root, want] = process.argv.slice(1);
const m = JSON.parse(fs.readFileSync(path.join(root, "module.json"), "utf8"));
if (m.version !== want) {
console.error(`bundle declares ${m.version}, but this is release ${want}`);
process.exit(1);
}
for (const p of [m.server, m.schema, m.purge, m.client.entry, "swagger-fragment.json"]) {
if (!fs.existsSync(path.join(root, p))) { console.error("bundle is missing " + p); process.exit(1); }
}
console.log("bundle contents check: ok");
' "$OUT" "$VERSION"
tar -C dist -czf "dist/module-uo-${VERSION}.tar.gz" "module-uo-${VERSION}"
rm -rf "$OUT"
SHA="$(sha256sum "dist/module-uo-${VERSION}.tar.gz" | cut -d' ' -f1)"
SIZE="$(stat -c%s "dist/module-uo-${VERSION}.tar.gz")"
# The install manifest. Same shape as the installer's bundle JSON — a
# per-asset sha256 fetched over HTTPS, no signatures — because that is
# the model this project already has and a second one would be a second
# thing to get right (MODULE_SYSTEM.md §1.11).
jq -n \
--arg id "$(node -p "require('./module.json').id")" \
--arg name "$(node -p "require('./module.json').name")" \
--arg version "$VERSION" \
--arg coreApi "$(node -p "require('./module.json').coreApi")" \
--arg artifact "module-uo-${VERSION}.tar.gz" \
--arg sha256 "$SHA" \
--argjson size "$SIZE" \
--arg url "https://${GITEA_HOST}/${REPO}/releases/download/v${VERSION}/module-uo-${VERSION}.tar.gz" \
'{schema:1, id:$id, name:$name, version:$version, coreApi:$coreApi,
artifact:$artifact, url:$url, sha256:$sha256, size:$size}' \
> "dist/module-uo-${VERSION}.json"
echo "${SHA} module-uo-${VERSION}.tar.gz" > dist/SHA256SUMS
cat "dist/module-uo-${VERSION}.json"
# Skipped on a recovery run: the tag is already there and is the thing being
# published against.
- name: Tag the release
if: ${{ steps.plan.outputs.release == 'true' && steps.plan.outputs.reuse_tag != 'true' }}
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -euo pipefail
TAG="${{ steps.plan.outputs.tag }}"
git config user.name 'Runic Gateway CI'
git config user.email 'ci@whitlocktech.net'
git tag -a "$TAG" -m "module-uo ${TAG}"
git push origin "$TAG"
- name: Create the Gitea release and upload the bundle
if: ${{ steps.plan.outputs.release == 'true' }}
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -euo pipefail
TAG="${{ steps.plan.outputs.tag }}"
VERSION="${{ steps.plan.outputs.version }}"
API="https://${GITEA_HOST}/api/v1/repos/${REPO}"
CI_TOKEN="$(printf '%s' "${REGISTRY_TOKEN}" | tr -d '\r\n')"
REL_ID="$(curl -sSf -X POST "${API}/releases" \
-H "Authorization: token ${CI_TOKEN}" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg tag "$TAG" --arg body "$(cat dist/CHANGELOG.md)" \
'{tag_name:$tag, name:$tag, body:$body, draft:false, prerelease:false}')" \
| jq -r '.id')"
echo "Created release ${TAG} (id=${REL_ID})"
for f in "module-uo-${VERSION}.tar.gz" "module-uo-${VERSION}.json" SHA256SUMS; do
curl -sSf -X POST "${API}/releases/${REL_ID}/assets?name=${f}" \
-H "Authorization: token ${CI_TOKEN}" \
-F "attachment=@dist/${f}" >/dev/null
echo " uploaded ${f}"
done

View File

@@ -0,0 +1,103 @@
# Run SonarQube static analysis against the code that just landed on `main` and
# report the results to the self-hosted SonarQube server for review. This is
# intentionally NON-BLOCKING: it triggers on push to main (i.e. AFTER merge),
# not on pull_request, so it never gates a PR. It complements pr-checks.yml
# (which gates PRs) and release.yml (which publishes the bundle) — this one only
# feeds the dashboard.
#
# Mirrors RunicGateway/website's sonarqube.yml, for the same reason pr-checks.yml
# does: this module is two npm packages shaped like that repo's `server/` and
# `client/`, and it is loaded into that repo's process. Until now it was the one
# part of the platform that had never been scanned — 75 files that arrived in the
# Phase 3 extraction with core's Sonar history left behind in core's project.
#
# Prerequisites (one-time, in the Gitea UI — Repo → Settings → Actions):
# • Secret SONAR_TOKEN — a SonarQube "Analysis" token generated at
# My Account → Security in SonarQube for the
# Module-uo project (or a global one).
# • Variable SONAR_HOST_URL — the SonarQube base URL on your LAN, e.g.
# http://192.168.0.56:9000
# (kept as a variable, not committed, so the internal address stays out of git.)
#
# The runner (self-hosted `ubuntu-latest`, same as the other workflows) must be
# able to reach SONAR_HOST_URL on your network. Nothing here waits on the
# SonarQube Quality Gate, so a failing gate does not fail this job — check the
# dashboard when you want to.
name: SonarQube
on:
push:
branches: [main]
# Allow re-running the analysis on demand from the Actions tab.
workflow_dispatch: {}
concurrency:
group: sonarqube-${{ github.ref }}
cancel-in-progress: true
jobs:
analysis:
runs-on: ubuntu-latest
steps:
- name: Check out (full history for accurate new-code + blame)
uses: actions/checkout@v4
with:
# SonarQube uses git history to attribute issues to authors and to
# compute "new code". A shallow clone degrades both.
fetch-depth: 0
# Node 22, where pr-checks.yml pins 20: the built-in `lcov` coverage
# reporter this job depends on needs >= 22. The version that matters for
# correctness is the one in pr-checks.yml, which matches the core process
# this module is loaded into; nothing here ships.
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Install deps for both halves
run: |
npm ci --prefix server
npm ci --prefix client
# The chunk has to exist before the client suite runs: build.test.js and
# registration.test.js read `client/dist/entry.js`, and both SKIP when
# there is no build. Run the other way round they skip silently and this
# job reports coverage for a suite that quietly asked less than it looks
# like it did — the same ordering pr-checks.yml calls load-bearing.
- name: Build the client chunk
run: npm run build --prefix client
# SonarQube runs static analysis only — it never executes the test suite,
# so we must produce the coverage report ourselves and hand it to the
# scanner (see sonar.javascript.lcov.reportPaths in sonar-project.properties).
#
# Both suites are invoked from the REPO ROOT rather than with `--prefix`,
# so the LCOV `SF:` paths come out repo-root-relative (`server/router/...`,
# `client/src/...`) and resolve against sonar.sources. That is also why the
# server suite's `--require` is spelled out here instead of reusing
# `npm test --prefix server`, whose path is relative to `server/`.
- name: Generate server test coverage (LCOV)
run: |
mkdir -p server/coverage
node --test --experimental-test-coverage \
--require ./server/test/_setup.js \
--test-reporter=spec --test-reporter-destination=stdout \
--test-reporter=lcov --test-reporter-destination=server/coverage/lcov.info \
--test-reporter=./scripts/sonar-test-reporter.mjs --test-reporter-destination=server/coverage/test-execution.xml \
server/test/*.test.js
- name: Generate client test coverage (LCOV)
run: |
mkdir -p client/coverage
node --test --experimental-test-coverage \
--test-reporter=spec --test-reporter-destination=stdout \
--test-reporter=lcov --test-reporter-destination=client/coverage/lcov.info \
--test-reporter=./scripts/sonar-test-reporter.mjs --test-reporter-destination=client/coverage/test-execution.xml \
client/test/*.test.js
- name: Run SonarQube scan
uses: sonarsource/sonarqube-scan-action@v4
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }}

8
.gitignore vendored
View File

@@ -19,7 +19,13 @@ client/coverage/
*.env
!.env.example
# Release staging
# Release staging. `.gitea/workflows/release.yml` assembles the bundle under
# /dist and packs it from there. Note this is the ROOT dist only — the module's
# two committed generated artifacts, swagger-fragment.json and
# routes.manifest.json, are deliberately NOT ignored: core merges the first
# verbatim and the second is the frozen URL surface, so both have to be
# reviewable in a diff (MODULE_API.md §2.8, §5.3).
/dist/
*.tar.gz
# logs / os

View File

@@ -96,6 +96,19 @@ when someone builds on the server is not shippable.
branch and no cutover, unlike `website`, whose module work accumulates on `edge`
and reaches `main` once.
### Static analysis runs after the merge, not on the PR
`.gitea/workflows/sonarqube.yml` scans `main` on push and reports to the
self-hosted SonarQube instance under the project key **`Module-uo`**. It is
deliberately non-blocking: it never gates a pull request, and a failing quality
gate does not fail the job. Check the dashboard when you want to; the things
that must not reach `main` are gated by `pr-checks.yml` instead.
It runs both suites from the repo root to produce coverage, and builds the
client chunk first — two of the client tests read `dist/entry.js` and skip
without it, which would leave this job reporting on a suite that quietly asked
less than it appears to.
### Commit messages
We use [Conventional Commits](https://www.conventionalcommits.org/) —

135
README.md
View File

@@ -24,7 +24,7 @@ The module's **id** is `uo` — that is what appears in `module.json`, in the `i
table, in the `modules/<id>/` path on disk and in the URL segment (`/uo/*`, `/admin/uo/*`,
`/player/uo/*`). `Module-uo` is the repository; `module-uo` is the module and its release artifact.
## Status: the bundle skeleton exists; the extraction has started
## Status: the extraction is complete; this repo is the UO half of the site
The design of record is
[`website/MODULE_SYSTEM.md`](https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/website/MODULE_SYSTEM.md)
@@ -37,32 +37,50 @@ in the docs repo — **read them before opening a PR here.** Where the two diffe
| 0 — CI trigger fix, cut `website` `edge`, bootstrap this repo | `website`, here | ✅ done |
| 1 — module API contract (`docs/website/MODULE_API.md`) + the atlas spike | `docs`, `website` | ✅ done |
| 2 — core scaffolding: loader, `installed_modules`, registries, client registry | `website` | ✅ done |
| 3 — extract the UO half of the site into this repo | `website`, here | 🟡 in progress |
| 3 — extract the UO half of the site into this repo | `website`, here | ✅ done |
| 4 — delivery: the admin Modules screen + the Docker path | `website` | ⬜ |
Phase 3 moves the UO half of `website/` here in ten slices (`MODULE_SYSTEM.md` §2.7.1), server-first
and then client. Each slice is one PR here that adds, and one PR in `website` that deletes — this one
merging first, so `website`'s `edge` branch serves the feature from core right up to the moment core
drops it.
Phase 3 moved the UO half of `website/` here in six slices (`MODULE_SYSTEM.md` §2.7.1): the bundle
skeleton, the whole server half, core's client extension slots, the whole client half, the de-UO of
core's own copy, and this one — the artifacts that make the result installable and checkable. Each
slice was one PR here that added and one in `website` that deleted, this one merging first, so
`website`'s `edge` branch served each feature from core right up to the moment core dropped it.
**Slice 0 is the bundle skeleton, and it registers nothing on purpose.** What it proves is the
delivery path itself: core discovers the module, validates `module.json`, calls `register()`, serves
the client chunk, injects it, and reports the module `started` — and the chunk resolves React, the
renderer and the router from core's `window.__rg` rather than bundling its own. Every slice after
this one adds registrations to `server/index.js` and `client/src/entry.jsx`.
Neither half sliced by feature in the end, and for the same reason on both sides: a mount prefix is
claimed whole and a shared leaf moves with its **last** consumer, so the closure of either half is
the whole half.
**What core serves and what this repo serves is now a fact you can read**, not a claim: 72 URLs, in
[`routes.manifest.json`](routes.manifest.json), derived by loading this module into a real core and
diffing. Not one of core's own URLs moved — that is the promise `MODULE_SYSTEM.md` §1.2 makes to the
shipped Android app and the Discord bot, and it is checked on every PR.
## Working on it
```bash
npm ci --prefix server && npm test --prefix server && npm run check:imports --prefix server
npm run check:swagger --prefix server # is swagger-fragment.json still current?
npm ci --prefix client && npm test --prefix client && npm run build --prefix client
npm run check:externals --prefix client # asks the BUILT chunk, so it runs after the build
```
The two `check:*` scripts are the contract's acceptance criteria rather than this module's own tests:
no import may escape the module root (`MODULE_API.md` §5.1), and no bare specifier may survive into
the built chunk (§3.6). The matching failure — a shared dependency being *bundled* — fails the build
itself, from a guard inside `vite.config.js`.
The `check:*` scripts are the contract's acceptance criteria rather than this module's own tests: no
import may escape the module root (`MODULE_API.md` §5.1), no bare specifier may survive into the
built chunk (§3.6), and the OpenAPI fragment core merges must describe the routes registered today
(§2.8). The matching build failure — a shared dependency being *bundled* — comes from a guard inside
`vite.config.js`.
**Changed a route, or its `#swagger` annotations?** `npm run swagger --prefix server` regenerates
`swagger-fragment.json`; commit it. Core cannot generate it — core is a prebuilt image and this
module mounts through a call no static parser can follow — so the file this repo commits is the one
an operator's `/api/docs` shows.
**Changed a mount prefix, or added a route?** `routes.manifest.json` is regenerated by the
`frozen-manifest` CI job, which clones core at the ref pinned in [`ci/core-ref.json`](ci/core-ref.json),
loads this module into it and takes the difference. To do it locally, check this repo out into that
core as `modules/uo` (**copy it — a symlink is silently skipped by the loader**), run core's
`npm run routes:manifest` with and without it, and hand both files to
`server/scripts/frozenManifest.js`.
Running it against a real core means checking this repo out as `website/modules/uo`, building the
client half, and booting core. The four-step browser smoke in `MODULE_API.md` §7.7 is the only thing
@@ -72,24 +90,35 @@ neither has a shape a DOM-less test runner can see.
## What it contains
One repo, one bundle: the server half and the client half live side by side and version together, so
a route and the screen that calls it can never be mismatched. A ✅ is in the tree today.
a route and the screen that calls it can never be mismatched.
```
module.json ✅ id, version, coreApi range, mounts, extensions
server/index.js ✅ the entry point — register(ctx, api), synchronous, no database
server/scripts/ ✅ checkImports.js — the §5.1 boundary check
server/test/ ✅ node --test, with a fake ctx standing in for core
server/ routers, controllers, models, utils
server/db/schema.sql idempotent fragment, replayed by core's ensureSchema()
server/db/purge.sql destructive; only ever run by an explicit purge
client/src/entry.jsx ✅ the chunk's entry — registers routes, nav, feature provider
client/src/shim/ ✅ react, react-dom, react-router-dom, jsx-runtime, from window.__rg
client/vite.config.js ✅ the library build, the aliases, the not-bundled guard
client/src/ route components, nav registrations, feature provider
client/dist/ ✅ PREBUILT ESM chunk, built by CI — never by an operator
module.json id, version, coreApi range, mounts, extensions
swagger-fragment.json generated · the OpenAPI core merges into /api/docs.json
routes.manifest.json generated · the 72 URLs this module serves
ci/core-ref.json the core commit the two above were proved against
server/index.js the entry point — register(ctx, api), synchronous, no database
server/router/ routers + controllers, one directory per tier
server/model/ one directory per table family; nothing crosses the boundary
server/utils/ sidecar client, visibility, ingest, town crier, cliloc, atlas
server/config/ the push stream catalog
server/db/schema.sql idempotent fragment, replayed by core's ensureSchema()
server/db/purge.sql destructive; only ever run by an explicit purge
server/scripts/ the three checks: imports, the fragment, the frozen manifest
server/test/ node --test, with a fake ctx standing in for core
client/src/entry.jsx the chunk's entry — registers routes, nav, slots, feature provider
client/src/shim/ react, react-dom, react-router-dom, jsx-runtime, from window.__rg
client/vite.config.js the library build, the aliases, the not-bundled guard
client/dist/ PREBUILT ESM chunk, built by CI — never by an operator
```
Release artifact: `module-uo-<version>.tar.gz`, plus a manifest carrying its `sha256`.
**The three generated files are committed on purpose.** Two of them are what core reads instead of
looking at this source — it never has it — and the third records which core they were proved against.
A generated file nobody reviews is a generated file nobody notices going wrong, so each lands in a
diff.
Release artifact: `module-uo-<version>.tar.gz`, plus `module-uo-<version>.json` carrying its
`sha256`. See below.
## How it reaches an operator
@@ -103,6 +132,54 @@ The [installer](https://gitea.whitlocktech.com/RunicGateway/installer) is **not*
It deploys the *shard* side — the plugin overlay and the uo-link sidecar — and never contacts the
website. Module delivery is website-side only.
### Releases
**Every merge to `main` that carries a releasable commit publishes a bundle.** The next version is
computed from conventional-commit subjects since the newest `v*` tag, as in `link` and `installer`:
`feat!:` or `BREAKING CHANGE` is a major, `feat:` a minor, `fix:` or `perf:` a patch, and a `main`
that gained none of those cuts no release. The number that ships is the **tag**, and CI writes it
into the `module.json` inside the bundle.
`module.json`'s version survives as a **floor**: name a version there above the newest tag and that
version is what releases, which is how you overrule the subjects — when a `coreApi` bump forces a
minor, say. What no longer happens is a `main` full of `feat:` producing nothing because a separate
PR to move one number had not been merged yet.
For a change with nothing releasable behind it — a widened `coreApi`, a new mount, a capability —
run the **Release** workflow by hand (Actions → Release → Run workflow). Leave `version` blank to
bump the newest tag by `bump` (default `patch`), or type an exact version to publish that.
Each release carries:
| Asset | What it is |
|---|---|
| `module-uo-<version>.tar.gz` | the directory core expects at `modules/uo/` — already assembled, with the chunk built and `ws` installed |
| `module-uo-<version>.json` | id, version, `coreApi`, the artifact's URL, size and **`sha256`** |
| `SHA256SUMS` | the same hash, in the shape every other repo here publishes |
Releases are **unsigned**; the `sha256` is the trust anchor, and the website verifies it before
unpacking. That is the model `installer`'s bundles already use, and a second trust model would be a
second thing to get right.
The tarball is assembled from an **include** list, never an exclude list — an exclude list ships
whatever it forgot. Tests, scripts, `client/src` and the dev dependencies are not in it.
## Environment variables
Four, all optional, all read by this module rather than by core — which is why they are documented
here and not in core's `.env.example`. In Docker they go in the Compose `.env`, since that is what
reaches the container.
| Var | Default | What |
|---|---|---|
| `UOLINK_BASE_URL` | — | Default sidecar base URL for a site with nothing saved yet. The admin panel's stored value wins. |
| `UOLINK_WS_URL` | — | Same, for the WebSocket URL. |
| `UOLINK_PROTOCOL` | `3` | Wire protocol this build speaks. Again only a fallback — set it lower only if you deliberately run an older sidecar. |
| `TOWNCRIER_DURATION_SEC` | `3600` | How long a published news post's in-game town-crier message stays up (≤ `86400`). |
**The sidecar's auth token is deliberately not here.** It is entered in Admin → Shard, encrypted at
rest with core's `SECRET_ENC_KEY`, and write-only in the API — never returned to any client.
## Compatibility
`module.json` declares a `coreApi` semver range, checked at boot against core's `MODULE_API_VERSION`.

6
ci/core-ref.json Normal file
View File

@@ -0,0 +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/uo and runs CORE's own routeManifest.js — nothing else can answer whether the URLs the module claims are the URLs it actually serves. Pinned rather than tracking `edge` 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.",
"repo": "https://gitea.whitlocktech.com/RunicGateway/website.git",
"ref": "963d734dcc09580a7d8bb676370b4faf9b8727b2",
"refName": "main @ the Teams cutover (website#161)"
}

View File

@@ -39,6 +39,7 @@ export const shard = {
champs: () => req('/public/shard/champs'),
// Protocol 2.0 boards.
guilds: () => req('/public/shard/guilds'),
guild: (id) => req(`/public/shard/guilds/${encodeURIComponent(id)}`),
governors: () => req('/public/shard/governors'),
governorHistory: (city, limit) =>
req(`/public/shard/governors/${encodeURIComponent(city)}/history${withQs(limit ? `limit=${limit}` : '')}`),

View File

@@ -48,7 +48,7 @@ if (createElement !== rg.react.createElement || createRoot !== rg.reactDom.creat
)
}
// The curated kit (§3.4). Seven members, closed: anything else this module needs
// The curated kit (§3.4). Eight members, closed: anything else this module needs
// it bundles itself, which is why `components/` next door exists at all.
export const {
PublicLayout,
@@ -59,6 +59,11 @@ export const {
useAsync,
useAuth,
useSite,
// Eighth member (MODULE_API 1.6.0): the slot renderer, for the INVERTED
// direction — this module declares a place on its own page and CORE fills it.
// Shared rather than reimplemented so core's content failing inside our page is
// contained by core's own error boundary.
Slot,
} = rg.ui
// The registry, for entry.jsx. Everything else here is read by pages.

View File

@@ -26,6 +26,7 @@ import Shard from './routes/public/Shard.jsx'
import ShardActivity from './routes/public/ShardActivity.jsx'
import ChampSpawns from './routes/public/ChampSpawns.jsx'
import Guilds from './routes/public/Guilds.jsx'
import Guild from './routes/public/Guild.jsx'
import Governors from './routes/public/Governors.jsx'
import Houses from './routes/public/Houses.jsx'
import Rules from './routes/public/Rules.jsx'
@@ -81,6 +82,7 @@ registry.registerRoutes(ID, {
{ path: 'shard/activity', element: <ShardActivity /> },
{ path: 'champs', element: <ChampSpawns /> },
{ path: 'guilds', element: <Guilds /> },
{ path: 'guilds/:id', element: <Guild /> },
{ path: 'governors', element: <Governors /> },
{ path: 'houses', element: <Houses /> },
{ path: 'rules', element: <Rules /> },
@@ -180,6 +182,35 @@ registry.registerFeatureProvider(ID, ID, useShardFlags)
registry.registerExtension(ID, 'site.footer.status', ShardStatusLink)
registry.registerExtension(ID, 'admin.users.detail', UserShardSections)
registry.registerExtension(ID, 'player.invite.accepted', InviteGameAccountStep)
// ── The inverted slot: this module DECLARES, core fills ────────────────────
//
// The other three above are core's slots that this module fills. This one is the
// reverse (TEAMS.md Part 3): Teams are a core primitive that this module
// populates, but core does not own the word "guild" and publishes no Team page of
// its own — so the page is ours and core contributes the activity feed to it.
//
// Declared under this module's own namespace, which core enforces. The second
// argument is what gets core's content into the place: **core offers a
// CONTRIBUTION and never names a slot**, so this module says where each one goes
// and keeps its own word for the place. Core's fills are applied after every
// module chunk has evaluated, so declaring here is early enough; on a core that
// knows nothing of Teams the slot simply stays empty.
registry.declareModuleSlot(ID, 'uo.guild.detail', { core: 'team.activity' })
// A SECOND place on the same page, for core's Team forum (TEAMS.md Part 5). Two
// declarations rather than one, because a slot holds one component and this module
// wants to decide where each of core's two contributions sits on its own page —
// the feed reads as part of the guild's story, the forum is a room you go into.
// Neither knows the other exists, and a core that fills only one leaves the other
// empty.
registry.declareModuleSlot(ID, 'uo.guild.forum', { core: 'team.forum' })
// And a THIRD, at the top of the same page, for core's per-Team notification
// control (TEAMS.md §6.3). Same reasoning as the other two and a different place:
// muting a guild is an action ON this page, so it sits with the page's heading
// rather than after its content. Core resolves whether this viewer is in the
// Team at all — this module neither knows nor asks.
registry.declareModuleSlot(ID, 'uo.guild.header', { core: 'team.notify' })
// `module.json`'s `coreApi` range is checked by the loader before this file is
// ever served, so there is nothing to re-check here. It is logged because a

View File

@@ -0,0 +1,122 @@
import { useParams, Link } from 'react-router-dom'
import api from '../../api.js'
import { ErrorState, Loading, PageHeader, PublicLayout, Slot, useAsync } from '../../core.js'
// One guild: its roster, and the place core puts the Team activity feed.
//
// **This page is the reason the extension-slot direction inverts**
// (docs/website/TEAMS.md Part 3). Teams are a core platform primitive and this
// module is what populates them — but core does not own the word "guild", so it
// publishes no Team page of its own. The page is this module's; the activity feed
// on it is core's, because only core can resolve whether the viewer is inside the
// Team, and the public/members split on that feed is a security boundary.
//
// So the module declares `uo.guild.detail` (entry.jsx) and core fills it. On a
// core that does not know about Teams the slot is simply never filled and this
// page renders its roster alone, which is the same tolerance every other slot has.
//
// The roster comes from this module's OWN board — the same data it answers core's
// Team provider from — rather than from core's Team API. That is deliberate: the
// board is the authoritative copy here, and reading core's projection of our own
// answer back would be a round trip through a staler copy of our own data.
function rankOf(m) {
// Absent rank means NOT KNOWN, never rank 0. The bridge omits it entirely for
// staff, because ServUO reports GameMaster-and-above as Leader whatever their
// real rank — emitting that verbatim would publish every staff member in a
// guild as one of its leaders (docs/link/v4.md).
if (m.rankName) return m.rankName
return null
}
function MemberRow({ m }) {
const rank = rankOf(m)
const linked = m.webId != null || m.acct != null
return (
<tr style={{ borderTop: '1px solid var(--line)' }}>
<td style={{ padding: '9px 10px', color: 'var(--head)' }}>
{m.name || 'Unknown'}
{m.rank === 4 && (
<span className="sans" style={{ color: 'var(--accent)', marginLeft: 8, fontSize: '0.72rem' }}>Leader</span>
)}
</td>
<td className="sans dim" style={{ padding: '9px 10px', fontSize: '0.86rem' }}>{rank || '—'}</td>
<td className="sans dim" style={{ padding: '9px 10px', fontSize: '0.86rem' }}>
{linked ? 'Linked' : '—'}
</td>
</tr>
)
}
export default function Guild() {
const { id } = useParams()
const { loading, error, data } = useAsync(() => api.shard.guild(id), [id])
const roster = (data && data.roster) || []
return (
<PublicLayout section="website">
<div className="shell-narrow page-body">
<p style={{ marginBottom: 14 }}>
<Link to="/uo/guilds">← All guilds</Link>
</p>
{loading && <Loading />}
{error && <ErrorState message="Could not load this guild right now." />}
{!loading && !error && data && (
<>
<PageHeader
eyebrow={data.abbr ? `[${data.abbr}]` : 'Guild'}
title={data.name || 'A guild'}
/>
<p className="sans dim" style={{ fontSize: '0.88rem' }}>
{data.members ?? roster.length} members
{data.online != null && ` · ${data.online} online`}
{data.alliance && ` · ${data.alliance}`}
</p>
{/* A third place for core, up here rather than below the roster: core
puts this guild's notification control in it, and a control that
acts on the page belongs beside the page's title and not after its
content. Empty for a visitor with no membership, and on a core
that fills nothing. */}
<Slot name="uo.guild.header" externalId={String(id)} moduleId="uo" />
{roster.length > 0 && (
<div style={{ overflowX: 'auto', marginTop: 18 }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr className="sans dim" style={{ textAlign: 'left', fontSize: '0.72rem', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
<th style={{ padding: '8px 10px' }}>Name</th>
<th style={{ padding: '8px 10px' }}>Rank</th>
<th style={{ padding: '8px 10px' }}>Account</th>
</tr>
</thead>
<tbody>
{/* Keyed by serial: two characters can share a display name,
which this shard's own world actually contains. */}
{roster.map((m) => <MemberRow key={m.serial} m={m} />)}
</tbody>
</table>
</div>
)}
{roster.length === 0 && (
<p className="sans dim" style={{ marginTop: 18 }}>No roster has been received for this guild yet.</p>
)}
{/* Core's Team activity feed lands here. Nothing renders on a core
that does not fill it, or when there is nothing to show. The guild
is named in OUR terms — core maps its own Team from these two. */}
<Slot name="uo.guild.detail" externalId={String(id)} moduleId="uo" />
{/* And the Team forum, in its own place below the feed. Core resolves
who may read it — membership and manual grants are core's rules —
so this module renders the room and never its door policy. */}
<Slot name="uo.guild.forum" externalId={String(id)} moduleId="uo" />
</>
)}
</div>
</PublicLayout>
)
}

View File

@@ -1,4 +1,5 @@
import { useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { useShardFeed } from '../../lib/useShardFeed.js'
import api from '../../api.js'
import { ErrorState, Loading, PageHeader, PublicLayout, useAsync } from '../../core.js'
@@ -15,9 +16,12 @@ function Leader({ leader }) {
function GuildRow({ g }) {
return (
<div
// A link now, because the board gained a detail page: the roster and core's
// Team activity feed live there (docs/website/TEAMS.md Part 3).
<Link
to={`/uo/guilds/${encodeURIComponent(g.id)}`}
className="panel"
style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14 }}
style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14, textDecoration: 'none' }}
>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0 }}>
@@ -59,7 +63,7 @@ function GuildRow({ g }) {
<Leader leader={g.leader} />
</div>
</div>
</div>
</Link>
)
}

139
client/test/api.test.js Normal file
View File

@@ -0,0 +1,139 @@
// ── The URLs this module calls ─────────────────────────────────────────────
//
// `src/api.js` binds the paths whose routes live in `server/router/**`, and the
// interesting assertions about it are the ones that encode a DECISION rather
// than a spelling. Three of these came across from core's `apiClient.test.js`
// in slice 4: they had stayed behind when the bindings moved, still asserting
// UO URLs from inside core's suite, which is the boundary this phase removes.
//
// What is NOT re-tested here is the fetch wrapper itself — status mapping, empty
// bodies, FormData, cookie inclusion. That is `req`, core's primitive, and core
// tests it. A module asserting core's contract back at it is a second copy that
// drifts.
//
// The chunk reads its shared bindings off `window.__rg` at module scope
// (src/core.js), so the fake global has to be in place before `src/api.js` is
// imported — hence the dynamic import below rather than a static one.
import { test, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import * as react from 'react'
import * as reactDom from 'react-dom/client'
import * as router from 'react-router-dom'
import * as jsxRuntime from 'react/jsx-runtime'
const BASE = '/api/v1'
let calls = []
function reply({ status = 200, statusText = 'OK', body = '' } = {}) {
return {
ok: status >= 200 && status < 300,
status,
statusText,
text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),
}
}
// Core's `req`, close enough for a path assertion: the only property this file
// cares about is the URL it was handed. Recording it here rather than mocking
// global.fetch keeps the test honest about the boundary — a module never sees
// fetch, it sees the primitive.
function request(path, opts = {}) {
calls.push({ url: BASE + path, opts })
return Promise.resolve(reply({ body: {} }).text().then(() => ({})))
}
// The REAL react/react-dom/router go in, not stubs: `src/core.js` compares the
// bindings it imported against the ones here and logs a "bundled its own copy"
// error when they differ. With stubs that error fires on every run of this file
// — a false alarm in the exact words of a real defect, which is how a check
// gets ignored.
globalThis.window = globalThis.window || {}
globalThis.window.__rg = {
react, reactDom, router, jsxRuntime,
api: { request, BASE },
ui: {},
registry: { registerRoutes() {}, registerNav() {}, registerFeatureProvider() {}, registerExtension() {} },
}
const { shard, atlas, admin } = await import('../src/api.js')
beforeEach(() => {
calls = []
})
afterEach(() => {
calls = []
})
// ── spawn atlas (Protocol 3.0 Part C) ───────────────────────────────────────
// The atlas lives at /public/atlas, NOT under /public/shard: it is static shard
// content parsed from the shard's own files, so it must not look sidecar-backed.
// Asserted because the split is a design decision, not an accident of spelling.
test('atlas reads hit /public/atlas, not /public/shard', async () => {
await atlas.creatures()
assert.equal(calls[0].url, '/api/v1/public/atlas/creatures')
})
test('atlas.creatures() sends only the filters that are set', async () => {
await atlas.creatures({ q: 'lizard man', facet: 'Ter Mur', limit: 25 })
const url = new URL(calls[0].url, 'http://x')
assert.equal(url.pathname, '/api/v1/public/atlas/creatures')
assert.equal(url.searchParams.get('q'), 'lizard man')
assert.equal(url.searchParams.get('facet'), 'Ter Mur')
assert.equal(url.searchParams.get('limit'), '25')
assert.equal(url.searchParams.get('offset'), null) // 0 is not sent
})
test('atlas.creature() encodes the slug and carries the facet filter through', async () => {
await atlas.creature('lizardman/rare', { facet: 'Felucca' })
assert.match(calls[0].url, /\/public\/atlas\/creatures\/lizardman%2Frare\?facet=Felucca$/)
})
test('admin atlas actions use the right methods and bodies', async () => {
await admin.atlas.import(true)
assert.equal(calls[0].url, '/api/v1/admin/shard/atlas/import')
assert.equal(calls[0].opts.method, 'POST')
assert.deepEqual(calls[0].opts.body, { force: true })
await admin.atlas.setPath('/srv/servuo')
assert.equal(calls[1].opts.method, 'PUT')
assert.deepEqual(calls[1].opts.body, { path: '/srv/servuo' })
})
// ── path encoding ───────────────────────────────────────────────────────────
// A city name with an apostrophe and a space is the real case: "Serpent's Hold"
// is a governor city, and an unencoded one would break the route match rather
// than 404 cleanly.
test('path params are URL-encoded', async () => {
await shard.governorHistory('Serpent’s Hold', 5)
assert.match(calls[0].url, /\/governors\/Serpent%E2%80%99s%20Hold\/history\?limit=5/)
})
// ── the API surface §1.2 freezes ────────────────────────────────────────────
// The shipped Android app calls these seven by name (data/api/AdminApi.kt), which
// is why the extraction moved which repo declares them and not what they are. A
// rename here is a client break, not a refactor.
test('the seven admin URLs the Android app calls are unchanged', async () => {
const expected = [
['kick', '/api/v1/admin/shard/kick'],
['ban', '/api/v1/admin/shard/ban'],
['unban', '/api/v1/admin/shard/unban'],
['broadcast', '/api/v1/admin/shard/broadcast'],
]
for (const [fn, url] of expected) {
calls = []
await admin.shardOps[fn]({})
assert.equal(calls[0].url, url, fn)
}
calls = []
await admin.shardOps.pages()
assert.equal(calls[0].url, '/api/v1/admin/shard/pages')
calls = []
await admin.shardOps.respondPage('7', {})
assert.equal(calls[0].url, '/api/v1/admin/shard/pages/7/respond')
calls = []
await admin.shardOps.closePage('7')
assert.equal(calls[0].url, '/api/v1/admin/shard/pages/7/close')
})

View File

@@ -39,11 +39,18 @@ const CHUNK = path.resolve(HERE, '..', 'dist', 'entry.js')
// nothing here renders, so a named stub is enough to be imported and passed on.
const stub = (name) => Object.assign(() => null, { displayName: name })
// Core's contribution catalogue, as of MODULE_API 1.6.0. Written down rather than
// imported — this suite runs against the BUILT chunk with no core in the process
// — which means it is a claim about core that has to be re-read when core's list
// changes. That is the same trade the rest of this fake makes.
const CORE_CONTRIBUTIONS = ['team.activity', 'team.forum', 'team.notify']
function fakeRg() {
const routes = { public: [], admin: [], player: [] }
const nav = { public: [], admin: [], player: [] }
const providers = new Map()
const extensions = new Map()
const declaredSlots = new Map()
return {
version: '1.3.0',
react,
@@ -54,7 +61,7 @@ function fakeRg() {
// object, so the check compares against whatever is here.
reactDom: { createRoot: () => { throw new Error('not in a browser') } },
ui: Object.fromEntries(
['PublicLayout', 'PageHeader', 'Loading', 'ErrorState', 'EmptyState', 'useAsync', 'useAuth', 'useSite']
['PublicLayout', 'PageHeader', 'Loading', 'ErrorState', 'EmptyState', 'useAsync', 'useAuth', 'useSite', 'Slot']
.map((n) => [n, stub(n)]),
),
api: { request: async () => ({}), ApiError: Error, BASE: '/api/v1' },
@@ -72,10 +79,24 @@ function fakeRg() {
if (extensions.has(slot)) throw new Error(`slot "${slot}" already filled`)
extensions.set(slot, { id, Component })
},
// The INVERTED direction (core API 1.6.0): this module declares a place on
// its OWN page and core fills it. Core enforces the namespace and the
// contribution name, so the fake does too — a chunk that declared an
// unnamespaced slot, or asked for a contribution core does not offer, would
// pass here and throw in a browser.
declareModuleSlot(id, name, options = {}) {
if (!name.startsWith(`${id}.`)) throw new Error(`declareModuleSlot: "${name}" must be namespaced "${id}."`)
if (declaredSlots.has(name)) throw new Error(`extension slot "${name}" already declared`)
const wants = options.core ?? null
if (wants !== null && !CORE_CONTRIBUTIONS.includes(wants)) {
throw new Error(`declareModuleSlot: "${name}" asks for core contribution "${wants}", which core does not offer`)
}
declaredSlots.set(name, wants)
},
routesFor: (area) => routes[area],
navFor: (area) => nav[area],
},
_read: () => ({ routes, nav, providers, extensions }),
_read: () => ({ routes, nav, providers, extensions, declaredSlots }),
}
}
@@ -98,7 +119,7 @@ const it = (name, fn) => test(name, { skip: skip && 'no dist/entry.js — run np
it('registers routes in all three areas, namespaced under the module id', () => {
const { routes } = registered
assert.equal(routes.public.length, 12)
assert.equal(routes.public.length, 13)
assert.equal(routes.admin.length, 7)
assert.equal(routes.player.length, 2)
for (const area of ['public', 'admin', 'player']) {
@@ -166,7 +187,7 @@ it('a nav row that gates on a feature is gated by a namespace this module provid
assert.ok(registered.providers.has('uo'), 'rows carry feature gates but no provider was registered')
})
it('fills the three extension slots, each with a component', () => {
it('fills the three CORE extension slots, each with a component', () => {
const { extensions } = registered
assert.deepEqual(
[...extensions.keys()].sort(),
@@ -198,3 +219,34 @@ it('registers under exactly one module id, matching the manifest', () => {
])
assert.deepEqual([...owners], [manifest.id])
})
it('declares its own guild slots, each naming the core contribution it wants', () => {
// The inverted direction (TEAMS.md Part 3). Teams are a core primitive with no
// core page: core owns the activity feed and the forum, this module owns the
// word "guild", so this module declares the places and core puts them in.
//
// THREE slots rather than one because a slot holds one component: stacking the
// feed, the forum and the notification control into a single fill would take
// away this module's ability to place them separately on its own page — and it
// does place them separately, the control above the roster and the other two
// below it.
//
// The second argument is what actually gets core's content here. **Core offers
// a contribution and never names a slot** — the first cut of this reached only
// this module, because core filled the literal name `uo.guild.detail` and any
// other game's page went empty with no error.
assert.deepEqual([...registered.declaredSlots.entries()], [
['uo.guild.detail', 'team.activity'],
['uo.guild.forum', 'team.forum'],
['uo.guild.header', 'team.notify'],
])
})
it('every declared slot is rendered by the page that owns it', () => {
// A slot nothing renders is a slot core fills into the void. Asserted against
// the source rather than the chunk, since the chunk is minified.
const page = fs.readFileSync(path.resolve(HERE, '..', 'src', 'routes', 'public', 'Guild.jsx'), 'utf8')
for (const name of registered.declaredSlots.keys()) {
assert.match(page, new RegExp(`name="${name.replace(/\./g, '\.')}"`))
}
})

370
routes.manifest.json Normal file
View File

@@ -0,0 +1,370 @@
{
"$comment": "Generated inventory of the URLs module-uo 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 workflow; see server/scripts/frozenManifest.js.",
"routes": [
{
"method": "DELETE",
"path": "/api/v1/admin/uo-link/towncrier/:id",
"tier": "public"
},
{
"method": "DELETE",
"path": "/api/v1/admin/users/:id/shard/link/:account",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/accounts",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/atlas",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/audit",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/char/:serial",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/clilocs",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/houses",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/pages",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/roster/:account",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/sales",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/vendors/:account",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/shard/visibility",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/uo-link/config",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/uo-link/signup-mode",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/uo-link/stream",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/shard/accounts",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/shard/houses",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/shard/online",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/shard/sales",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/admin/users/:id/shard/standing",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/shard/accounts",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/shard/char/:serial",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/shard/houses",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/shard/roster/:account",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/shard/sales",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/player/shard/vendors/:account",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/atlas/champions",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/atlas/creatures",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/atlas/creatures/:slug",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/atlas/landmarks",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/atlas/meta",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/atlas/regions",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/champs",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/economy",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/features",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/feed",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/governors",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/governors/:city/history",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/guilds",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/guilds/:id",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/houses",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/idoc",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/market",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/market/meta",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/market/vendors/:serial",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/online",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/points",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/points/:system",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/presence",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/ruleset",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/status",
"tier": "public"
},
{
"method": "GET",
"path": "/api/v1/public/shard/stream",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/account",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/atlas/approve",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/atlas/import",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/atlas/reject",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/ban",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/broadcast",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/clilocs/import",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/kick",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/link",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/pages/:id/close",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/pages/:id/respond",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/shard/unban",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/admin/uo-link/towncrier",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/player/shard/account",
"tier": "public"
},
{
"method": "POST",
"path": "/api/v1/player/shard/link",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/shard/atlas/path",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/shard/clilocs/path",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/shard/visibility",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/uo-link/config",
"tier": "public"
},
{
"method": "PUT",
"path": "/api/v1/admin/uo-link/signup-mode",
"tier": "public"
}
]
}

View File

@@ -0,0 +1,64 @@
// Custom node:test reporter that emits SonarQube's Generic Test Execution XML.
//
// Node's built-in reporters give us coverage (`lcov`) and pass/fail output
// (`spec`/`tap`/`junit`), but SonarQube's "Unit Tests" measure is fed by a
// SEPARATE report in *its own* format via `sonar.testExecutionReportPaths` — the
// lcov report only populates Coverage, which is why the dashboard shows coverage
// while the Unit Tests tile stays "-". This reporter produces that missing report.
//
// Format: https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/test-coverage/generic-test-data/
// <testExecutions version="1">
// <file path="server/test/foo.test.js">
// <testCase name="..." duration="12"/> <!-- duration = integer ms -->
// </file>
// </testExecutions>
//
// Paths are emitted repo-root-relative (POSIX separators) so they match the
// `sonar.tests` roots; the workflow runs `node --test` from the repo root, so the
// absolute `file` on each event strips cleanly against process.cwd().
import path from 'node:path'
function xmlEscape(s) {
return String(s).replace(/[<>&"']/g, (c) => ({
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;',
"'": '&apos;',
})[c])
}
export default async function* sonarTestReporter(source) {
const byFile = new Map()
const cwd = process.cwd()
for await (const event of source) {
if (event.type !== 'test:pass' && event.type !== 'test:fail') continue
const d = event.data
// Skip the container events (a `describe` suite) and anything without a file
// — only real test cases go in the report, so the count matches the runner's.
if (!d.file || (d.details && d.details.type === 'suite')) continue
const rel = path.relative(cwd, d.file).split(path.sep).join('/')
if (!byFile.has(rel)) byFile.set(rel, [])
byFile.get(rel).push({
name: d.name,
duration: Math.max(0, Math.round(d.details?.duration_ms ?? 0)),
failed: event.type === 'test:fail',
skipped: Boolean(d.skip || d.todo),
})
}
yield '<?xml version="1.0" encoding="UTF-8"?>\n<testExecutions version="1">\n'
for (const [file, cases] of byFile) {
yield ` <file path="${xmlEscape(file)}">\n`
for (const c of cases) {
const attrs = `name="${xmlEscape(c.name)}" duration="${c.duration}"`
if (c.failed) yield ` <testCase ${attrs}><failure message="test failed"/></testCase>\n`
else if (c.skipped) yield ` <testCase ${attrs}><skipped/></testCase>\n`
else yield ` <testCase ${attrs}/>\n`
}
yield ' </file>\n'
}
yield '</testExecutions>\n'
}

View File

@@ -0,0 +1,201 @@
// ── `/guild` — the first chat command through the module contract ──────────
//
// Registered with `api.registerSlashCommands` (MODULE_API 1.6.0, TEAMS.md §7.1).
// The definition and this handler live here; the bot pulls the definition over
// the app's internal API and runs nothing of ours. Nothing in this file knows
// what Discord is — it is handed an `actor` and returns an envelope, and the
// same handler would serve a second platform unchanged.
//
// **Why `/guild` and not `/team`.** Teams are core's primitive and "guild" is
// this module's word for one; core does not own the word, so it does not publish
// the noun in a channel either. That is the same correction that deleted core's
// Team pages in phase 3, applied to the chat surface.
//
// **The audience rungs are enforced here, exactly as they are on the website.**
// A shard whose `guilds` feature is gated to staff does not become public
// because the question arrived over Discord — this handler resolves the caller's
// rung through the same `shardVisibility` config the routes use. It is the one
// piece of this file that is a security boundary rather than presentation.
const core = require('../core')
const db = require('../model/teamProvider/teamProvider.db')
const provider = require('../model/teamProvider/teamProvider.model')
const visibility = require('../utils/shardVisibility')
const log = core.logger('guild-command')
// How many guilds the no-argument form lists. A Discord embed takes 25 fields;
// ten is a summary a person reads rather than a table they scroll past.
const LIST_LIMIT = 10
/**
* Where the caller sits on this module's ladder.
*
* The same resolution `projectRoster` does, and it is duplicated in shape rather
* than shared because the inputs differ: that one is handed a viewer core
* described, this one an actor. Both end at `viewerLevel`, and both answer
* `anonymous` DIRECTLY for a caller with no site account — handing `viewerLevel`
* a synthetic empty request makes it fall through to `auth.getUserFromRequest`,
* which expects real cookies and throws (the phase 3 bug).
*/
async function levelFor(actor) {
if (!actor || !actor.userId) return 'anonymous'
return visibility.viewerLevel({ user: { id: actor.userId, role: actor.role } })
}
// The nudge §9 answer 5 asks for, and only when it is TRUE.
//
// **Linking reaches exactly two rungs and no further.** Signing in gets a caller
// to `logged_in` and linking a game account to `player`; `staff` and `admin` are
// roles an operator grants and no amount of linking will earn. So a shard that
// gates guilds to staff refuses an unlinked caller WITHOUT the invitation —
// telling them to link would be telling them to do something that changes
// nothing, which is worse than saying no.
//
// The live walk found this: gated to `staff`, the refusal still read "this shard
// shows guild information to linked players".
const LINKING_REACHES = new Set(['logged_in', 'player'])
function linkPrompt(actor, audience) {
if (actor.isLinked) return null
if (!LINKING_REACHES.has(audience)) return null
return 'Link your account on the site to see more — this shard shows guild information to linked players.'
}
const pageUrl = (externalId) =>
`${core.baseUrl}${provider.pageUrlTemplate.replace('{externalId}', externalId)}`
// Match on abbreviation first, then an exact name, then a unique prefix. Players
// type the abbreviation — it is what appears over a character's head — and a
// wrong-guild answer is worse than "say which one".
function findByName(rows, wanted) {
const needle = wanted.trim().toLowerCase()
const byAbbr = rows.filter((r) => (r.abbr || '').toLowerCase() === needle)
if (byAbbr.length === 1) return { guild: byAbbr[0] }
const exact = rows.filter((r) => r.name.toLowerCase() === needle)
if (exact.length === 1) return { guild: exact[0] }
const partial = rows.filter((r) => r.name.toLowerCase().includes(needle))
if (partial.length === 1) return { guild: partial[0] }
if (partial.length > 1) return { ambiguous: partial.slice(0, LIST_LIMIT) }
return {}
}
/** The counts for one guild, from the roster rather than the board's assertions. */
async function summarise(guild) {
const members = await db.listGuildMembers(guild.id)
const leaders = members
.filter((m) => Number(m.rank) >= db.LEADER_RANK)
.map((m) => m.name)
// The board's founder-leader is folded in as a floor, the same way
// getTeamLeaders does it: it arrives on a different frame, and a shard whose
// roster predates the rank amendment has no other leadership signal.
if (guild.leader_name && !leaders.includes(guild.leader_name)) leaders.push(guild.leader_name)
return {
// `members`/`online` are the BOARD's counts, which is what the shard asserts;
// the roster is what it enumerated, and the two legitimately disagree for the
// moment between a membership change and the sweep that reports it. The
// assertion is the more current of the two, so it is what is shown.
members: guild.members,
online: guild.online,
linked: members.filter((m) => provider.resolveUserId(m) !== null).length,
leaders,
}
}
async function detail(guild, actor, audience) {
const counts = await summarise(guild)
const fields = [
{ name: 'Members', value: String(counts.members ?? '—'), inline: true },
{ name: 'Online', value: String(counts.online ?? 0), inline: true },
{ name: 'Linked accounts', value: String(counts.linked), inline: true },
]
if (counts.leaders.length) {
fields.push({ name: 'Leaders', value: counts.leaders.join(', ') })
}
return {
title: guild.abbr ? `${guild.name} [${guild.abbr}]` : guild.name,
text: guild.alliance ? `Alliance: ${guild.alliance}` : undefined,
fields,
url: pageUrl(guild.id),
notice: linkPrompt(actor, audience),
}
}
/**
* `/guild [name]` — one guild's summary, or the shard's largest guilds.
*
* Never throws for an ordinary miss: "no such guild" and "the shard is offline"
* are answers, and letting either become an exception would turn a routine
* question into "that command failed" with nothing an operator could act on.
*/
async function handler({ options, actor }) {
const config = await visibility.getConfig()
const feature = config.guilds
// An admin turned guilds off. The switch means "this shard does not publish
// guild data" — over any surface, to anyone, staff included.
if (!feature || !feature.enabled) {
return { text: 'This shard does not publish guild information.', ephemeral: true }
}
const level = await levelFor(actor)
if (!visibility.meets(level, feature.audience)) {
return {
text: 'Guild information on this shard is not shown to your account.',
ephemeral: true,
notice: linkPrompt(actor, feature.audience),
}
}
// The provider's own staleness guard, asked before any board read: an
// unreachable sidecar means the board is a snapshot of unknown age, and
// reporting it as current here would contradict what every other surface says.
const ready = await provider.boardIsCurrent()
if (!ready.ok) {
log.info('guild command answered offline', { reason: ready.reason })
return { text: 'The shard is not connected right now, so guild information may be out of date.', ephemeral: true }
}
const rows = await db.listGuilds()
if (!rows.length) return { text: 'No guilds are on the board yet.', ephemeral: true }
const wanted = options && typeof options.name === 'string' ? options.name : null
if (!wanted) {
const top = [...rows].sort((a, b) => (b.members || 0) - (a.members || 0)).slice(0, LIST_LIMIT)
return {
// Not "Guilds on <host>": `ctx.site` carries a base URL and no brand name,
// so naming the deployment here can only mean printing its hostname into
// an embed title, which is noise on a shard's own Discord server.
title: 'Guilds on this shard',
fields: top.map((g) => ({
name: g.abbr ? `${g.name} [${g.abbr}]` : g.name,
value: `${g.members || 0} members · ${g.online || 0} online`,
inline: true,
})),
notice: linkPrompt(actor, feature.audience),
}
}
const { guild, ambiguous } = findByName(rows, wanted)
if (ambiguous) {
return {
text: `Several guilds match “${wanted}”: ${ambiguous.map((g) => g.name).join(', ')}`,
ephemeral: true,
}
}
if (!guild) return { text: `No guild matches “${wanted}”.`, ephemeral: true }
return detail(guild, actor, feature.audience)
}
module.exports = {
name: 'guild',
description: 'Show a guild on this shard — members, who is online, and its leaders',
options: [
{ name: 'name', type: 'string', description: 'Guild name or abbreviation', required: false },
],
// Everyone, deliberately. The gate that matters is the shard's own audience
// rung, resolved inside the handler — `access: 'linked'` would hide the command
// from exactly the unlinked members §9 answer 5 wants to invite to link.
access: 'everyone',
handler,
}

View File

@@ -21,7 +21,11 @@
-- `notification_subs` rows for `shard.*` streams and `announce_job_legs` rows
-- with leg `towncrier` belong to core's tables, and a module does not delete
-- from those — core prunes them when it drops the registrations, which it can
-- do because it knows which registrant owned what.
-- do because it knows which registrant owned what. The two `settings` rows
-- schema.sql seeds (`game_account_signup`, `uo_link_protocol_3_migrated`) are
-- the same case with an extra reason: the second is a one-shot MIGRATION
-- marker, and deleting it would re-arm a protocol bump against tables this
-- file has just dropped.
DROP TABLE IF EXISTS `shard_atlas_pending`;
DROP TABLE IF EXISTS `shard_atlas_meta`;
@@ -41,6 +45,7 @@ DROP TABLE IF EXISTS `shard_ruleset`;
DROP TABLE IF EXISTS `shard_presence`;
DROP TABLE IF EXISTS `shard_governor_terms`;
DROP TABLE IF EXISTS `shard_governors`;
DROP TABLE IF EXISTS `shard_guild_members`;
DROP TABLE IF EXISTS `shard_guilds`;
DROP TABLE IF EXISTS `shard_pages`;
DROP TABLE IF EXISTS `shard_champs`;

View File

@@ -220,6 +220,52 @@ CREATE TABLE IF NOT EXISTS shard_guilds (
INDEX idx_shard_guilds_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Guild membership (Protocol 4). One row per member per guild, replaced on
-- guild.roster and thinned by guild.leave. Protocol 2 could only say HOW MANY
-- members a guild had, so this table has no pre-4 equivalent and the Guilds page
-- could show a count but never a roster.
--
-- `acct` / `web_id` are the site-identity fields and are stored because the
-- sidecar forwards them; they are NOT public. shardVisibility locks any key that
-- is or ends in acct/webId to `admin` and recurses into arrays, so a projected
-- roster loses them below that rung — storing them here is what lets a linked
-- member be matched to a site user at all.
--
-- A roster over the shard's per-frame cap arrives in several frames, so rows are
-- keyed on (guild_id, serial) and the frame carrying seq 0 clears the guild first;
-- see upsertGuildRoster.
CREATE TABLE IF NOT EXISTS shard_guild_members (
guild_id INT NOT NULL,
serial VARCHAR(20) NOT NULL, -- in-game mobile serial, "0x1F5"
name VARCHAR(120) NULL,
acct VARCHAR(120) NULL, -- absent for a mobile with no account
web_id INT NULL, -- set only when the account is linked
is_player TINYINT(1) NOT NULL DEFAULT 1,
-- Guild rank, 0-4, with 4 being Leader (ServUO RankDefinition.Ranks). NULL means
-- "not known", which is a real state and not a demotion: the shard omits the rank
-- for a staff account, because PlayerMobile.GuildRank reports Leader for anyone at
-- GameMaster or above whatever their actual rank, and publishing that would put a
-- staff member on a public roster as a guild leader.
-- Backticked, like `int` on shard_online: RANK is a reserved word in MySQL 8 and
-- a non-reserved keyword in MariaDB, so it parses here bare but must not be
-- written that way anywhere it might not.
`rank` TINYINT NULL,
-- The rank's NAME, as the game states it: a cliloc id for the five standard ranks
-- (1062959-1062963, which ship with no text), or a literal string when a shard has
-- replaced the rank table with custom definitions. Resolving one to a label is this
-- module's job -- it owns the cliloc table and the game vocabulary.
rank_cliloc INT NULL,
rank_name VARCHAR(64) NULL,
t BIGINT NULL, -- roster event time, epoch ms
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (guild_id, serial),
INDEX idx_shard_guild_members_acct (acct),
INDEX idx_shard_guild_members_web (web_id),
-- Leadership is "rank >= 4", asked per guild, which is the query the Team provider
-- runs on every reconcile.
INDEX idx_shard_guild_members_rank (guild_id, rank)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Town-governor board (Protocol 2.0, City Loyalty). One row per city, upserted on
-- city.update (full-state, emitted only on change; there is no remove event since
-- the set of cities is fixed). governor / governorElect are actor objects
@@ -614,4 +660,41 @@ ALTER TABLE uo_link_config MODIFY COLUMN protocol INT NOT NULL DEFAULT 3;
-- uo_link_config row yet) it is simply written with nothing to update.
UPDATE uo_link_config SET protocol = 3
WHERE id = 1 AND protocol < 3
AND NOT EXISTS (SELECT 1 FROM settings WHERE `key` = 'uo_link_protocol_3_migrated');
AND NOT EXISTS (SELECT 1 FROM settings WHERE `key` = 'uo_link_protocol_3_migrated');
-- **The marker must be written HERE, not in core.** These two statements were
-- adjacent in core's schema.sql before the extraction; slice 1 moved the UPDATE
-- and left the INSERT behind, and the two files do not run at the same time —
-- core's schema is replayed in full BEFORE any module fragment (MODULE_API.md
-- §2.6). So the marker existed before the UPDATE ever read it, the NOT EXISTS
-- was true on the first boot of a fresh install and false on every boot of an
-- upgraded one, and the one-shot could never fire. An install carrying a
-- protocol-2 row would have stayed pinned at 2 against a v3 sidecar — every
-- REST call 409, which is precisely the failure this migration exists to
-- prevent. Latent rather than live: it only bites an install that first boots a
-- post-slice-1 build while already holding a uo_link_config row, and `edge` has
-- not cut over yet.
INSERT IGNORE INTO settings (`key`, value) VALUES ('uo_link_protocol_3_migrated', '1');
-- ── Settings rows this module owns ─────────────────────────────────────────
--
-- Both keys predate the module system and both name a game concept, so core
-- seeding them made core's schema declare a module's settings — the structural
-- half of what Phase 3 removes (MODULE_SYSTEM.md §2.7.1, slice 4). The KEYS are
-- deliberately unchanged: they are live rows on every existing install, and
-- renaming one would silently reset an operator's choice to the default.
--
-- INSERT IGNORE, so an install that already carries the row keeps its value and
-- only a database that has never seen the key gets the default. Nothing in core
-- reads either one; `game_account_signup` is read through ctx.settings by
-- server/utils/gameSignup.js, which owns the policy.
INSERT IGNORE INTO settings (`key`, value) VALUES ('game_account_signup', 'disabled');
-- Protocol 4 guild rank, added to databases that already have shard_guild_members.
--
-- The table itself is new in Protocol 4 and unreleased, so no production install has
-- it — but `edge` deployments do, from the roster work that landed before the rank
-- amendment, and CREATE TABLE IF NOT EXISTS adds a table and never a column. This is
-- the same gap the sidecar's own store hit when `guilds.members` was added.
ALTER TABLE shard_guild_members ADD COLUMN IF NOT EXISTS `rank` TINYINT NULL;
ALTER TABLE shard_guild_members ADD COLUMN IF NOT EXISTS rank_cliloc INT NULL;
ALTER TABLE shard_guild_members ADD COLUMN IF NOT EXISTS rank_name VARCHAR(64) NULL;
ALTER TABLE shard_guild_members ADD INDEX IF NOT EXISTS idx_shard_guild_members_rank (guild_id, `rank`);

View File

@@ -45,6 +45,8 @@ module.exports = function register(ctx, api) {
const shardStreams = require('./config/shardStreams')
const townCrierLeg = require('./utils/shardAnnounce')
const teamProvider = require('./model/teamProvider/teamProvider.model')
const guildCommand = require('./commands/guild.command')
const boot = require('./boot')
/* eslint-enable global-require */
@@ -86,6 +88,25 @@ module.exports = function register(ctx, api) {
api.registerNotificationStreams(shardStreams.STREAMS)
api.registerAnnounceLeg(townCrierLeg.leg)
// Teams: a UO guild is a Team, and this module is the authoritative source of
// them for this deployment (MODULE_API 1.6.0). Core asks the three questions;
// everything about what a guild IS stays here.
//
// Registration is a claim, not a call — nothing below runs until core
// reconciles, which is after `onBoot`. That matters because every method reads
// the database, and registration must not.
api.registerTeamProvider(teamProvider)
// `/guild` — the chat surface for the same guilds (MODULE_API 1.6.0, TEAMS.md
// §7.1). The definition travels to the bot; the handler stays here and runs in
// the website process, because the bot container has no `modules` volume and
// cannot load a line of this module's code.
//
// Core registers NO commands of its own. "Guild" is this module's word — core
// does not own it on a page (phase 3) and does not publish it in a channel
// either.
api.registerSlashCommands([guildCommand])
api.onBoot(boot.onBoot)
api.onShutdown(boot.onShutdown)

View File

@@ -171,6 +171,50 @@ const removeGuild = (id) => query('DELETE FROM shard_guilds WHERE id = ?', [id])
const clearGuilds = () => query('DELETE FROM shard_guilds')
const listGuilds = () => query(`SELECT ${GUILD_COLS} FROM shard_guilds ORDER BY name ASC`)
// ── Guild membership (Protocol 4) ──────────────────────────────────────────
// `rank` is backticked wherever it is written, like `int` on shard_online: it is a
// reserved word in MySQL 8 and merely a keyword in MariaDB, so it parses bare here
// and must not be relied on to.
const MEMBER_COLS = 'guild_id, serial, name, acct, web_id, is_player, `rank`, rank_cliloc, rank_name, t'
// Upsert rather than plain insert: a roster frame can be redelivered (the /history
// backfill replays stored frames on every reconnect), and a redelivery must be a
// no-op rather than a duplicate-key error.
//
// The rank columns are assigned unconditionally, NULL included. A member whose rank
// the shard withheld — a staff account, whose GuildRank getter reports Leader
// regardless of the truth — must go back to "not known" rather than keeping a rank
// from before they were promoted.
const upsertGuildMembers = (rows) => {
if (!rows.length) return Promise.resolve()
const values = rows.map(() => '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').join(', ')
const params = rows.flatMap((r) => [
r.guild_id, r.serial, r.name, r.acct, r.web_id, r.is_player,
r.rank, r.rank_cliloc, r.rank_name, r.t,
])
return query(
`INSERT INTO shard_guild_members (${MEMBER_COLS}) VALUES ${values}
ON DUPLICATE KEY UPDATE name = VALUES(name), acct = VALUES(acct),
web_id = VALUES(web_id), is_player = VALUES(is_player),
\`rank\` = VALUES(\`rank\`), rank_cliloc = VALUES(rank_cliloc),
rank_name = VALUES(rank_name), t = VALUES(t)`,
params,
)
}
const clearGuildMembers = (guildId) =>
query('DELETE FROM shard_guild_members WHERE guild_id = ?', [guildId])
const removeGuildMember = (guildId, serial) =>
query('DELETE FROM shard_guild_members WHERE guild_id = ? AND serial = ?', [guildId, serial])
const clearAllGuildMembers = () => query('DELETE FROM shard_guild_members')
const listGuildMembers = (guildId) =>
query(`SELECT ${MEMBER_COLS} FROM shard_guild_members WHERE guild_id = ? ORDER BY name ASC`, [
guildId,
])
// The guild an actor LEADS — matched on the current board (leader_serial or the
// linked leader_acct), so it reflects live state. Guild MEMBERSHIP for non-leaders
// is not modelled (the board carries only counts + leader), so we don't guess it.
@@ -342,6 +386,11 @@ module.exports = {
removeGuild,
clearGuilds,
listGuilds,
upsertGuildMembers,
clearGuildMembers,
removeGuildMember,
clearAllGuildMembers,
listGuildMembers,
findGuildLedByActor,
listGuildsLedByAccounts,
upsertGovernor,

View File

@@ -340,8 +340,88 @@ async function upsertGuild(ev) {
})
}
const removeGuild = (id) => (id == null ? Promise.resolve() : db.removeGuild(id))
const clearGuilds = () => db.clearGuilds()
const removeGuild = async (id) => {
if (id == null) return
await db.removeGuild(id)
await db.clearGuildMembers(id)
}
const clearGuilds = async () => {
await db.clearGuilds()
await db.clearAllGuildMembers()
}
// ── Guild membership (Protocol 4) ──────────────────────────────────────────
// Apply one guild.roster frame.
//
// A roster larger than the shard's per-frame cap arrives as several frames
// carrying seq/more/total. The sidecar reassembles them for its OWN board, but the
// live WebSocket feed and the /history backfill both carry the individual frames,
// so this ingest sees them unreassembled and has to cope.
//
// It copes without buffering, because a table can express what a single JSON column
// could not: the frame carrying seq 0 clears the guild first and every frame then
// upserts its own rows. Rows are keyed on (guild_id, serial), so a redelivered frame
// — the /history backfill replays stored frames on every reconnect — is idempotent
// rather than a duplicate-key error.
//
// The cost is a brief window during a multi-frame update where the table holds part
// of a roster. That is acceptable for a projection that is already only as fresh as
// a 60s sweep, and the frames arrive back-to-back in one burst; buffering to close
// it would duplicate the sidecar's reassembly for a sub-second inconsistency.
async function upsertGuildRoster(ev) {
if (!ev || ev.id == null) return
const seq = Number.isFinite(ev.seq) ? ev.seq : 0
const members = Array.isArray(ev.members) ? ev.members : []
// seq 0 begins a roster and supersedes whatever was held for this guild.
if (seq === 0) await db.clearGuildMembers(ev.id)
const rows = members
.filter((m) => m && m.serial)
.map((m) => ({
guild_id: ev.id,
serial: m.serial,
name: m.name ?? null,
acct: m.acct ?? null,
web_id: Number.isFinite(m.webId) ? m.webId : null,
is_player: m.player ? 1 : 0,
// Guild rank (Protocol 4). ABSENT is a real state and is stored as NULL: the
// shard withholds the rank for a staff account, because ServUO's GuildRank
// getter reports Leader for anyone at GameMaster or above whatever their
// actual rank. Defaulting a missing rank to 0 here would turn "we were not
// told" into "rank 0", which is a demotion invented by this line.
rank: Number.isInteger(m.rank) ? m.rank : null,
rank_cliloc: Number.isInteger(m.rankCliloc) ? m.rankCliloc : null,
rank_name: typeof m.rankName === 'string' && m.rankName ? m.rankName.slice(0, 64) : null,
t: Number.isFinite(ev.t) ? ev.t : null,
}))
await db.upsertGuildMembers(rows)
}
// A single departure (guild.leave). Advisory: the shard re-emits the full roster
// whenever the member set changes, so the table would converge on the next frame
// even if this were dropped. Applying it makes the change visible immediately
// instead of at the end of the sweep that produced it.
async function removeGuildMember(ev) {
if (!ev || ev.id == null || !ev.who) return
await db.removeGuildMember(ev.id, ev.who)
}
// The membership roster for one guild, in the wire shape the projection expects
// (an array of actor objects), so shardVisibility strips acct/webId by the same
// rule it applies to guild.leader.
async function listGuildMembers(guildId) {
const rows = await db.listGuildMembers(guildId)
return rows.map((r) => ({
serial: r.serial,
name: r.name,
...(r.acct == null ? {} : { acct: r.acct }),
...(r.web_id == null ? {} : { webId: r.web_id }),
player: !!r.is_player,
}))
}
function shapeGuild(r) {
const payload = typeof r.payload === 'string' ? safeJson(r.payload) : r.payload
@@ -620,6 +700,9 @@ module.exports = {
removeGuild,
clearGuilds,
listGuilds,
upsertGuildRoster,
removeGuildMember,
listGuildMembers,
replaceGuilds,
findGuildForActor,
listGuildsLedForAccounts,

View File

@@ -0,0 +1,87 @@
// SQL behind the Team provider — three questions core asks, answered from the
// guild board and the roster Protocol 4 put there.
//
// Every statement reads only THIS module's tables. Core's Team tables are
// core-internal (docs/website/TEAMS.md §10.3) and this module must never name
// one, even though it is what fills them.
// `query` is destructured from the core facade at require time, like every other
// *.db.js here. The facade resolves `ctx` per call, so taking it now is safe even
// though `ctx` does not exist yet when this file is first required.
const { query } = require('../../core')
/** ServUO's `RankDefinition.Ranks[4]` is Leader, and 4 is the top of the ladder. */
const LEADER_RANK = 4
/**
* The guild board — one row per guild the shard has told us about.
*
* `members`/`online` here are the COUNTS `guild.update` carries; the roster is a
* separate table (Protocol 4). Both are read, because a count is what the shard
* asserts and a roster is what it enumerated, and they can legitimately disagree
* for the moment between a membership change and the sweep that reports it.
*/
const listGuilds = () =>
query(
`SELECT id, name, abbr, alliance, members, online, leader_serial, leader_name, leader_acct
FROM shard_guilds ORDER BY name ASC`,
)
const findGuild = (id) =>
query(
`SELECT id, name, abbr, alliance, members, online, leader_serial, leader_name, leader_acct
FROM shard_guilds WHERE id = ? LIMIT 1`,
[id],
)
/**
* One guild's roster, with the site link and live presence folded in.
*
* Two LEFT JOINs, both deliberate:
*
* - `shard_account_links` resolves `user_id` HERE rather than in core, because
* this module owns that table and a core that read it would be core naming a
* module's table by name (§2.3). It is also why a freshly linked account
* appears as linked on the next reconcile rather than needing core to know
* anything about linking.
* - `shard_online` is how a member's `online` is answered at all. The roster
* frame does not carry it — the wire's member is the standard actor object
* (`serial`, `name`, `player`, `acct?`, `webId?`), and the board's `online` is
* a count, not a set. Presence therefore comes from the online table, which
* is the same source the public "who's online" surface already uses.
*
* `web_id` on the roster row is preferred over the link table when present: it is
* what the shard itself asserted at roster time, and the join is the fallback for
* a member whose row predates their link.
*/
const listGuildMembers = (guildId) =>
query(
"SELECT m.serial, m.name, m.acct, m.web_id, m.is_player, m.`rank`, m.rank_cliloc, m.rank_name, " +
` l.user_id AS linked_user_id,
(o.serial IS NOT NULL) AS is_online
FROM shard_guild_members m
LEFT JOIN shard_account_links l ON l.account = m.acct
LEFT JOIN shard_online o ON o.serial = m.serial
WHERE m.guild_id = ?
ORDER BY m.name ASC`,
[guildId],
)
/**
* Every member at leader rank — rank 4, the top of ServUO's `RankDefinition.Ranks`.
*
* A set, not a single row, and that is the whole reason Protocol 4 grew a per-member
* rank: the guild board carries one `leader_serial`, so before this the website could
* only ever be told about one leader, while a UO guild routinely has several.
*
* A NULL rank is excluded by the comparison, which is correct — the shard withholds
* the rank for a staff account rather than publishing the Leader its getter falsely
* reports, and "not known" must not be read as "leads this guild".
*/
const listGuildLeaders = (guildId) =>
query(
'SELECT serial FROM shard_guild_members WHERE guild_id = ? AND `rank` >= ? ORDER BY name ASC',
[guildId, LEADER_RANK],
)
module.exports = { listGuilds, findGuild, listGuildMembers, listGuildLeaders, LEADER_RANK }

View File

@@ -0,0 +1,339 @@
// ── module-uo's Team provider ──────────────────────────────────────────────
//
// The three questions core asks this module about Teams
// (docs/website/MODULE_API.md — `api.registerTeamProvider`, and TEAMS.md §2.3).
// A UO guild is a Team; this file is the whole of the translation.
//
// **Every method returns an envelope, and answering `{ ok: false }` is a normal
// outcome, not a failure to handle.** Core's contract is that module
// unavailability becomes staleness and never emptiness, and the only way this
// module can say "I cannot answer" is to say so — an empty array would be read as
// an authoritative "there are none", which during a cold start is how every
// roster on the site gets emptied. So the guard below is the most important code
// in the file, and it is deliberately conservative: **an unreachable or
// never-connected sidecar refuses, rather than reporting the board it happens to
// still hold.**
//
// The board IS durable and would survive a sidecar outage, which is exactly what
// makes this tempting to get wrong. The reason to refuse anyway: core cannot tell
// a board that is five minutes stale from one that is five days stale, and it
// makes destructive decisions — archiving Teams, departing members — from a
// complete answer. Reporting a stale board as authoritative would license those.
const core = require('../../core')
const db = require('./teamProvider.db')
const uoLinkConfig = require('../uoLinkConfig/uoLinkConfig.model')
const uoLinkSocket = require('../../utils/uoLinkSocket')
const clilocs = require('../shardClilocs/shardClilocs.model')
const visibility = require('../../utils/shardVisibility')
const log = core.logger('teams')
/**
* ServUO's five stock rank names, by the cliloc id the game names them with.
*
* A fallback, not the source of truth: the operator's own cliloc table is consulted
* first, and a shard with custom rank definitions sends a literal string that beats
* both. This exists because the cliloc table is populated only if someone ran the
* client-file extraction, and a roster on a shard that has not should still say
* "Warlord" rather than nothing.
*/
const STANDARD_RANK_NAMES = {
1062959: 'Leader',
1062960: 'Warlord',
1062961: 'Emissary',
1062962: 'Member',
1062963: 'Ronin',
}
/** A refusal, in the shape core reads (§2.3). */
const refuse = (reason) => ({ ok: false, reason })
/**
* Is the bridge in a state where the board can be trusted as current?
*
* The board is only as good as the socket that fills it. Three states refuse, and
* they are asked in this order because each is a different thing being wrong:
*
* - **no uo-link configured** — there is no shard behind this website at all;
* - **the integration is disabled** — an admin turned it off, and the board is
* frozen at whatever it held;
* - **the socket is not connected** — the board is a snapshot of unknown age.
*
* The in-process socket state is preferred over the persisted status column,
* which is written on transitions: a process that has just started has not
* transitioned yet, so the column can still say `connected` from the last run
* while this process has never opened a socket.
*/
async function boardIsCurrent() {
const config = await uoLinkConfig.getSafe()
if (!config || !config.baseUrl) return { ok: false, reason: 'no uo-link configured' }
if (!config.enabled) return { ok: false, reason: 'the uo-link integration is disabled' }
const state = uoLinkSocket.getState()
if (!state || !state.connected) {
return { ok: false, reason: 'the uo-link socket is not connected; the guild board may be stale' }
}
return { ok: true }
}
/**
* `getTeams()` — every guild on the board.
*
* `externalId` is the ServUO `Guild.Id`, which survives a rename: renaming a
* guild in-game keeps the id, so core sees "an id whose name changed" and applies
* its rename rule (archive plus create). That mapping is this module's to make —
* only the game knows what identity survives what (§10.5).
*
* `meta` carries the alliance, opaquely. Core stores and displays it and never
* branches on it, which is what lets a UO concept reach a Team page without core
* acquiring an opinion about alliances.
*/
async function getTeams() {
const ready = await boardIsCurrent()
if (!ready.ok) return refuse(ready.reason)
try {
const rows = await db.listGuilds()
return {
ok: true,
complete: true,
teams: rows.map((row) => ({
externalId: String(row.id),
name: row.name,
abbr: row.abbr || null,
meta: row.alliance ? { alliance: row.alliance } : null,
})),
}
} catch (err) {
log.warn('getTeams failed', { message: err.message })
return refuse(`guild board unreadable: ${err.message}`)
}
}
/**
* `getTeamMembers(externalId)` — one guild's roster.
*
* **A guild with no roster rows is refused, not reported empty**, unless the board
* itself says the guild has no members. Protocol 4's roster arrives on its own
* frames, separately from the `guild.update` that creates the board row, so there
* is a real window — a fresh guild, or a website that connected between the two —
* where core would otherwise be told authoritatively that a 155-member guild has
* nobody in it. The board's own `members` count is what distinguishes the two,
* and it is the only thing that can.
*/
async function getTeamMembers(externalId) {
const ready = await boardIsCurrent()
if (!ready.ok) return refuse(ready.reason)
try {
const [guild] = await db.findGuild(externalId)
if (!guild) return refuse(`guild ${externalId} is not on the board`)
const rows = await db.listGuildMembers(externalId)
if (!rows.length && guild.members > 0) {
return refuse(`roster for guild ${externalId} has not arrived yet (board says ${guild.members} members)`)
}
const labels = await rankLabels(rows)
return {
ok: true,
complete: true,
members: rows.map((row) => ({
memberKey: row.serial,
displayName: row.name || null,
rankLabel: labels.get(row.serial) || null,
// Rank 4 is Leader, and several members can hold it. A NULL rank is not a
// leader: the shard withholds the rank for a staff account rather than
// publishing the Leader its getter falsely reports, and "not known" must
// never be read as "leads this guild".
leader: Number.isInteger(row.rank) && row.rank >= db.LEADER_RANK,
online: Boolean(row.is_online),
userId: resolveUserId(row),
})),
}
} catch (err) {
log.warn('getTeamMembers failed', { externalId, message: err.message })
return refuse(`roster unreadable: ${err.message}`)
}
}
/**
* `getTeamLeaders(externalId)` — everyone at leader rank.
*
* **All of them, which is why Protocol 4 grew a per-member rank.** The guild board
* carries one `leader_serial`, so before the rank amendment this could only ever
* name a single member, while a UO guild routinely has several at rank 4 and
* TEAMS.md §2.5 treats multiple leaders as the normal case.
*
* The board's own `leader_serial` is folded in as a floor. It is the guild's
* founder-leader and it comes from a different frame (`guild.update`), so on a
* shard whose roster has not been re-emitted since the amendment it is the only
* leadership signal there is — and it should never be *lost* by moving to ranks.
*/
async function getTeamLeaders(externalId) {
const ready = await boardIsCurrent()
if (!ready.ok) return refuse(ready.reason)
try {
const [guild] = await db.findGuild(externalId)
if (!guild) return refuse(`guild ${externalId} is not on the board`)
const rows = await db.listGuildLeaders(externalId)
const leaders = rows.map((r) => r.serial)
if (guild.leader_serial && !leaders.includes(guild.leader_serial)) {
leaders.push(guild.leader_serial)
}
return { ok: true, leaders }
} catch (err) {
log.warn('getTeamLeaders failed', { externalId, message: err.message })
return refuse(`leadership unreadable: ${err.message}`)
}
}
/**
* Resolve each member's rank to a display label, keyed by serial.
*
* The shard sends the rank's NAME as the game states it — a cliloc id for the five
* standard ranks, or a literal string for a custom rank definition — and never a
* resolved label, because ServUO ships no text for those clilocs. This module does
* have a cliloc table, which is why the resolution belongs here.
*
* Three sources, in order: a custom string wins, then the operator's cliloc table,
* then the five standard names. The last exists because the cliloc table is
* populated only if someone ran the client extraction, and a shard that has not
* should still read "Warlord" rather than nothing.
*
* Never throws: a rank label is decoration on a roster, and a lookup failure must
* not turn a good roster into a refusal.
*/
async function rankLabels(rows) {
const out = new Map()
const wanted = []
for (const row of rows) {
if (row.rank_name) {
out.set(row.serial, row.rank_name)
} else if (Number.isInteger(row.rank_cliloc)) {
wanted.push(row.rank_cliloc)
}
}
let resolved = new Map()
if (wanted.length) {
try {
resolved = await clilocs.resolveMany(wanted)
} catch (err) {
log.warn('rank cliloc lookup failed; falling back to the standard names', { message: err.message })
}
}
for (const row of rows) {
if (out.has(row.serial) || !Number.isInteger(row.rank_cliloc)) continue
const label = resolved.get(row.rank_cliloc) || STANDARD_RANK_NAMES[row.rank_cliloc] || null
if (label) out.set(row.serial, label)
}
return out
}
/**
* The site account behind a character, or null.
*
* `web_id` is what the shard itself asserted when it emitted the roster; the
* account-link join is the fallback for a member whose roster row predates their
* link. Both are coerced through the same check, because `web_id` arrives from
* the wire as a string.
*/
function resolveUserId(row) {
const fromRoster = Number.parseInt(row.web_id, 10)
if (Number.isInteger(fromRoster) && fromRoster > 0) return fromRoster
const fromLink = Number.parseInt(row.linked_user_id, 10)
return Number.isInteger(fromLink) && fromLink > 0 ? fromLink : null
}
/**
* Which roster rows a viewer may see (TEAMS.md §3.3, MODULE_API 1.6.0).
*
* The optional fourth provider method, and the only one core calls on a REQUEST
* path rather than from the reconciler. Core holds the roster and its public
* shape; the question that is this module's is "who is allowed to look", because
* the audience rungs and their configuration live here (`utils/shardVisibility`)
* and core does not know what a rung is.
*
* **The answer is all-or-nothing, and that is correct rather than a shortcut.**
* A rung is a property of the FEATURE, not of a member: `guilds` is either
* visible to this viewer or it is not, and there is no configuration in which
* some members of a guild are public and others are not. Returning every key or
* none is the honest translation of the model this module actually has.
*
* **A refusal here costs visibility, not staleness.** Core fails closed on this
* one call — an unanswered visibility question serves an empty roster rather than
* an unprojected one — so every path below that cannot reach a confident answer
* refuses deliberately, and the catch does too. That is the opposite of the rule
* governing the other three methods, and it is the right way round: for a roster
* SYNC an unanswered call must change nothing, and for a roster READ it must
* publish nothing.
*
* Note what this does NOT do: strip fields. `acct` and `webId` are the leak this
* module's projection exists to prevent on the live feed, and neither is in
* core's roster shape at all — core withholds the member key and the site account
* id from every public roster whatever this returns. So there is nothing here to
* redact, only rows to withhold.
*/
async function projectRoster(externalId, members, viewer) {
try {
const config = await visibility.getConfig()
const feature = config.guilds
// An admin turned guilds off. Nobody sees a roster, including staff — the
// switch means "this shard does not publish guild data", not "publish it
// quietly".
if (!feature || !feature.enabled) return { ok: true, members: [] }
// `viewerLevel` reads a REQUEST; core hands over a described viewer instead,
// which is deliberate — it keeps the `users` row out of the contract.
//
// The no-viewer case is answered here rather than by handing `viewerLevel` an
// empty object: given a request with no `req.user` it falls through to
// `auth.getUserFromRequest`, which expects real cookies and headers and
// throws on a synthetic one. That throw would land in the catch below and
// become a REFUSAL, so every anonymous visitor would have been served an
// empty roster on a shard whose guilds are public. Anonymous is a known
// answer, not a failed lookup.
const level = viewer
? await visibility.viewerLevel({ user: { id: viewer.userId, role: viewer.role } })
: 'anonymous'
if (!visibility.meets(level, feature.audience)) return { ok: true, members: [] }
return { ok: true, members: members.map((m) => m.member_key).filter(Boolean) }
} catch (err) {
// Core reads this as "withhold the roster". Saying so is the whole point: the
// alternative — answering with every key because the config read failed —
// publishes a roster an operator may have gated to staff.
log.warn('projectRoster could not resolve visibility; withholding the roster', {
externalId, message: err.message,
})
return refuse(`visibility could not be resolved: ${err.message}`)
}
}
// Where core should point a link at a guild (MODULE_API 1.6.0, TEAMS.md §6.4).
//
// **Core cannot work this out for itself, and it is not supposed to.** Teams are
// a contract primitive with no core surface — this module owns the guild page,
// because core does not own the word "guild" — so the one thing core needs back
// is where the page it does not own actually lives. A notification email that
// cannot link to the thread it is about is most of the way to useless.
//
// A relative path with `{externalId}` substituted, matching `Guild.jsx`'s route
// (`/uo/guilds/:id`). Core does the substitution and nothing else with it; a
// template naming its own host is refused at registration, which is why this is
// data and not a callback.
const pageUrlTemplate = '/uo/guilds/{externalId}'
// `resolveUserId` is exported for the `/guild` chat command, which counts linked
// members and must decide "linked" by the same rule the roster does — a second
// copy of that two-source check is a copy that drifts.
module.exports = {
getTeams, getTeamMembers, getTeamLeaders, projectRoster, boardIsCurrent, pageUrlTemplate, resolveUserId,
}

158
server/package-lock.json generated
View File

@@ -13,7 +13,8 @@
},
"devDependencies": {
"express": "^4.19.2",
"express-validator": "^7.2.0"
"express-validator": "^7.2.0",
"swagger-autogen": "^2.23.7"
},
"engines": {
"node": ">=20"
@@ -33,6 +34,19 @@
"node": ">= 0.6"
}
},
"node_modules/acorn": {
"version": "7.4.1",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz",
"integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
@@ -40,6 +54,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.6",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz",
@@ -65,6 +86,17 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/brace-expansion": {
"version": "1.1.18",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@@ -106,6 +138,13 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true,
"license": "MIT"
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@@ -156,6 +195,16 @@
"ms": "2.0.0"
}
},
"node_modules/deepmerge": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -359,6 +408,13 @@
"node": ">= 0.6"
}
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"dev": true,
"license": "ISC"
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@@ -408,6 +464,28 @@
"node": ">= 0.4"
}
},
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
"dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -481,6 +559,18 @@
"node": ">=0.10.0"
}
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
"dev": true,
"license": "ISC",
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@@ -498,6 +588,19 @@
"node": ">= 0.10"
}
},
"node_modules/json5": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true,
"license": "MIT",
"bin": {
"json5": "lib/cli.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
@@ -581,6 +684,19 @@
"node": ">= 0.6"
}
},
"node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
@@ -624,6 +740,16 @@
"node": ">= 0.8"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dev": true,
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -634,6 +760,16 @@
"node": ">= 0.8"
}
},
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
@@ -867,6 +1003,19 @@
"node": ">= 0.8"
}
},
"node_modules/swagger-autogen": {
"version": "2.23.7",
"resolved": "https://registry.npmjs.org/swagger-autogen/-/swagger-autogen-2.23.7.tgz",
"integrity": "sha512-vr7uRmuV0DCxWc0wokLJAwX3GwQFJ0jwN+AWk0hKxre2EZwusnkGSGdVFd82u7fQLgwSTnbWkxUL7HXuz5LTZQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"acorn": "^7.4.1",
"deepmerge": "^4.2.2",
"glob": "^7.1.7",
"json5": "^2.2.3"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -931,6 +1080,13 @@
"node": ">= 0.8"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"dev": true,
"license": "ISC"
},
"node_modules/ws": {
"version": "8.21.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",

View File

@@ -7,7 +7,9 @@
"main": "index.js",
"scripts": {
"test": "node --test --require ./test/_setup.js",
"check:imports": "node scripts/checkImports.js"
"check:imports": "node scripts/checkImports.js",
"swagger": "node scripts/swaggerFragment.js",
"check:swagger": "node scripts/swaggerFragment.js --check"
},
"engines": {
"node": ">=20"
@@ -15,10 +17,11 @@
"//dependencies": "The ONE runtime dependency, and it ships inside the release tarball: CI runs npm ci --omit=dev and packs server/node_modules, because an operator never builds (MODULE_SYSTEM.md 1.14). Node resolves it by walking up from modules/uo/server/. Everything else the shipped half needs arrives on ctx (MODULE_API.md 2.3) - express, express-validator, the database, the logger, the middleware and the rate-limit factory are all core-owned and handed over.",
"devDependencies": {
"express": "^4.19.2",
"express-validator": "^7.2.0"
"express-validator": "^7.2.0",
"swagger-autogen": "^2.23.7"
},
"dependencies": {
"ws": "^8.21.0"
},
"//devDependencies": "Test-only. test/_fakes.js builds a REAL express router - a fake Router would test the fake."
"//devDependencies": "Test-only and build-only, never shipped. test/_fakes.js builds a REAL express router - a fake Router would test the fake. swagger-autogen is the same generator core uses, pinned to the same major so the fragment and the spec it merges into come out of one tool (MODULE_API.md 2.8)."
}

View File

@@ -47,8 +47,8 @@ shardRouter.post(
// #swagger.tags = ['Admin · Account']
// #swagger.summary = 'Link an in-game account with a one-time code (self)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkRequest" } } } } */
/* #swagger.responses[200] = { description: 'Linked', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkResult" } } } } */
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardLinkRequest" } } } } */
/* #swagger.responses[200] = { description: 'Linked', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardLinkResult" } } } } */
/* #swagger.responses[400] = { description: 'Unknown or expired code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
body('code').isString().trim().isLength({ min: 4, max: 32 }),
validate,
@@ -59,7 +59,7 @@ shardRouter.get(
// #swagger.tags = ['Admin · Account']
// #swagger.summary = 'List the caller’s linked game accounts (self)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardLink" } } } } } */
/* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardLink" } } } } } */
selfShard.listAccounts,
)
shardRouter.get(
@@ -103,7 +103,7 @@ shardRouter.get(
// #swagger.tags = ['Admin · Account']
// #swagger.summary = 'Recent player-vendor sales for the caller’s linked accounts (self)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardVendorSale" } } } } } */
/* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardVendorSale" } } } } } */
selfShard.getSales,
)
shardRouter.post(
@@ -112,7 +112,7 @@ shardRouter.post(
// #swagger.summary = 'Create a game account and link it to the caller (staff self-service)'
// #swagger.description = 'Same as POST /player/shard/account but for a signed-in staff user — provisions a game account (own username + password) and links it. Gated by game_account_signup + the shard’s mode; the password is never stored or logged.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["account","password"], properties: { account: { type: "string" }, password: { type: "string" } } } } } */
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["account","password"], properties: { account: { type: "string" }, password: { type: "string" } } } } } } */
/* #swagger.responses[201] = { description: 'Account created and linked', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[403] = { description: 'Game-account signup unavailable (site or shard)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[409] = { description: 'Account name already taken', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
@@ -223,7 +223,7 @@ shardRouter.get(
// #swagger.tags = ['Admin · Shard']
// #swagger.summary = 'Recent in-game moderation audit events (admin/moderator)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'admin.audit events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEvent" } } } } } */
/* #swagger.responses[200] = { description: 'admin.audit events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardEvent" } } } } } */
modAccess,
shardOps.listAudit,
)
@@ -233,7 +233,7 @@ shardRouter.get(
// #swagger.summary = 'Full house registry — owner, price, decay (admin/moderator)'
// #swagger.description = 'The complete house registry. The public endpoint shows only IDOC houses with location; this staff view carries owner/price/co-owner/decay detail.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
/* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardHouse" } } } } } */
modAccess,
shardOps.listHouses,
)
@@ -253,7 +253,7 @@ shardRouter.get(
// #swagger.summary = 'Spawn atlas status: path, drift, counts, pending review (admin only)'
// #swagger.description = 'Where the ServUO tree is, whether it can be read, whether its source files have drifted from the loaded atlas, and any refresh staged for approval. The public /atlas/meta route reports the game world only; the filesystem detail is here.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Atlas status', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasStatus" } } } } */
/* #swagger.responses[200] = { description: 'Atlas status', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasStatus" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
shardAtlas.getStatus,
@@ -265,7 +265,7 @@ shardRouter.post(
// #swagger.description = 'Applies a map change without a restart. `force` reimports even when the source hashes match what is loaded. A refresh that would REMOVE a facet is still staged for approval rather than applied — that decision is never taken implicitly. An unreadable tree answers 200 with status "unavailable" rather than 500: the refresh contract reports outcomes instead of throwing, and the admin needs to be told what is wrong with the path.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: false, content: { "application/json": { schema: { type: "object", properties: { force: { type: "boolean", description: "Reimport even if the tree is unchanged." } } } } } } */
/* #swagger.responses[200] = { description: 'What happened', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasRefreshResult" } } } } */
/* #swagger.responses[200] = { description: 'What happened', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasRefreshResult" } } } } */
adminOnly,
body('force').optional().isBoolean(),
validate,
@@ -277,7 +277,7 @@ shardRouter.post(
// #swagger.summary = 'Approve a staged atlas refresh that removes a facet (admin only)'
// #swagger.description = 'Re-parses the tree and applies it, facet loss included. Only the decision was stored, never the parsed world, so what lands matches the tree at approval time — an operator who has since fixed a half-copied mount gets the corrected import.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'What happened', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasRefreshResult" } } } } */
/* #swagger.responses[200] = { description: 'What happened', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasRefreshResult" } } } } */
adminOnly,
shardAtlas.approve,
)
@@ -287,7 +287,7 @@ shardRouter.post(
// #swagger.summary = 'Reject a staged atlas refresh (admin only)'
// #swagger.description = 'Keeps the current atlas and remembers the decision against those exact source hashes, so a declined refresh does not re-prompt on every restart. Changing the tree asks again.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Rejected', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasRefreshResult" } } } } */
/* #swagger.responses[200] = { description: 'Rejected', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasRefreshResult" } } } } */
/* #swagger.responses[404] = { description: 'Nothing is awaiting review', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
shardAtlas.reject,
@@ -299,7 +299,7 @@ shardRouter.put(
// #swagger.description = 'Persisted as a setting, which wins over the SERVUO_PATH deploy default so the mount can move without a redeploy. Blank clears it and the atlas is simply skipped on the next boot. Deliberately does not import as a side effect — the response carries the refreshed status so the panel can offer that as the next step.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["path"], properties: { path: { type: "string", description: "Absolute path to the ServUO server root. Blank disables the atlas." } } } } } } */
/* #swagger.responses[200] = { description: 'Atlas status after the change', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasStatus" } } } } */
/* #swagger.responses[200] = { description: 'Atlas status after the change', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasStatus" } } } } */
adminOnly,
body('path').isString().isLength({ max: 512 }),
validate,
@@ -322,7 +322,7 @@ shardRouter.get(
// #swagger.summary = 'Cliloc table status: sources, drift, entry count (admin only)'
// #swagger.description = 'Where the cliloc sources are, whether they can be read, how many entries are loaded, and whether the files on disk have drifted from them. The table is built from a SET of sources — the converted client table plus every operator-maintained overlay under `custom/`, which is how shard-added and shard-edited items get names. `missingSources` lists any source that was loaded before and is now gone; an import refuses that without `approve`. A shard with nothing configured is a supported state — item names simply render as ids.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Cliloc status', content: { "application/json": { schema: { $ref: "#/components/schemas/ClilocStatus" } } } } */
/* #swagger.responses[200] = { description: 'Cliloc status', content: { "application/json": { schema: { $ref: "#/components/schemas/UoClilocStatus" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
shardClilocs.getStatus,
@@ -331,10 +331,10 @@ shardRouter.post(
'/clilocs/import',
// #swagger.tags = ['Admin · Shard']
// #swagger.summary = 'Re-import the cliloc table from its source files (admin only)'
// #swagger.description = 'Applies a client patch, or a change to the shard\'s own overlay files, without a restart. `force` reimports even when the source hashes match what is loaded. `approve` accepts a refresh in which a previously-loaded source has VANISHED — refused by default, because an unmounted volume and a deliberate deletion are indistinguishable from the server, and the wrong guess silently drops every name that file contributed. A missing path — or the common mistake of pointing at the client\'s own COMPRESSED Cliloc.enu — answers 200 with status "unavailable" and the reason, rather than 500: the refresh contract reports outcomes instead of throwing, and the admin needs to be told which file to convert.'
// #swagger.description = 'Applies a client patch, or a change to the shard’s own overlay files, without a restart. `force` reimports even when the source hashes match what is loaded. `approve` accepts a refresh in which a previously-loaded source has VANISHED — refused by default, because an unmounted volume and a deliberate deletion are indistinguishable from the server, and the wrong guess silently drops every name that file contributed. A missing path — or the common mistake of pointing at the client’s own COMPRESSED Cliloc.enu — answers 200 with status "unavailable" and the reason, rather than 500: the refresh contract reports outcomes instead of throwing, and the admin needs to be told which file to convert.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: false, content: { "application/json": { schema: { type: "object", properties: { force: { type: "boolean", description: "Reimport even if the sources are unchanged." }, approve: { type: "boolean", description: "Accept a refresh in which a previously-loaded source has vanished." } } } } } } */
/* #swagger.responses[200] = { description: 'What happened', content: { "application/json": { schema: { $ref: "#/components/schemas/ClilocRefreshResult" } } } } */
/* #swagger.responses[200] = { description: 'What happened', content: { "application/json": { schema: { $ref: "#/components/schemas/UoClilocRefreshResult" } } } } */
adminOnly,
body('force').optional().isBoolean(),
body('approve').optional().isBoolean(),
@@ -348,7 +348,7 @@ shardRouter.put(
// #swagger.description = 'Accepts either the converted base file itself or a directory to search. Overlays are read from a `custom/` directory beside it either way — pointing at a file does not forfeit them. Persisted as a setting, which wins over the UO_CLIENT_PATH deploy default so the mount can move without a redeploy. Blank clears it and resolution is skipped on the next boot. Deliberately does not import as a side effect — the response carries the refreshed status so the panel can offer that as the next step.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["path"], properties: { path: { type: "string", description: "Path to the converted cliloc file, or a directory containing one. Blank disables resolution." } } } } } } */
/* #swagger.responses[200] = { description: 'Cliloc status after the change', content: { "application/json": { schema: { $ref: "#/components/schemas/ClilocStatus" } } } } */
/* #swagger.responses[200] = { description: 'Cliloc status after the change', content: { "application/json": { schema: { $ref: "#/components/schemas/UoClilocStatus" } } } } */
adminOnly,
body('path').isString().isLength({ max: 512 }),
validate,
@@ -364,7 +364,7 @@ shardRouter.get(
// #swagger.summary = 'Get per-feature shard visibility config (admin only)'
// #swagger.description = 'The effective config (compiled defaults merged with stored overrides) plus the vocabulary the admin UI renders from: the audience ladder and the always-locked fields. Defaults reproduce pre-v3 behavior.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Visibility config', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardVisibilityConfig" } } } } */
/* #swagger.responses[200] = { description: 'Visibility config', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardVisibilityConfig" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
shardVisibility.getVisibility,
@@ -375,8 +375,8 @@ shardRouter.put(
// #swagger.summary = 'Update per-feature shard visibility config (admin only)'
// #swagger.description = 'Patch one or more features. Unknown feature names, unknown rungs, and any attempt to configure a locked field (acct / webId — admin-only always) are rejected with 400 rather than silently dropped.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ShardVisibilityUpdate" } } } } */
/* #swagger.responses[200] = { description: 'Updated config', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardVisibilityConfig" } } } } */
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardVisibilityUpdate" } } } } */
/* #swagger.responses[200] = { description: 'Updated config', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardVisibilityConfig" } } } } */
/* #swagger.responses[400] = { description: 'Unknown feature, rung, or a locked field', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
body('features').isObject(),

View File

@@ -70,7 +70,7 @@ uoLinkRouter.get(
'/signup-mode',
// #swagger.tags = ['Admin · Shard']
// #swagger.summary = 'Get the game-account signup mode (admin only)'
// #swagger.description = 'Whether the site offers game-account creation, and in which direction. The shard\'s own SignupMode (Bridge.cfg) must agree: website/hybrid accept site-created accounts, game refuses them.'
// #swagger.description = 'Whether the site offers game-account creation, and in which direction. The shard’s own SignupMode (Bridge.cfg) must agree: website/hybrid accept site-created accounts, game refuses them.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The configured mode and the legal values', content: { "application/json": { schema: { type: "object", properties: { mode: { type: "string" }, modes: { type: "array", items: { type: "string" } } } } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
@@ -100,7 +100,7 @@ uoLinkRouter.post(
// #swagger.tags = ['Admin · Shard']
// #swagger.summary = 'Publish / replace a town-crier message (admin only)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/TownCrierRequest" } } } } */
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/UoTownCrierRequest" } } } } */
/* #swagger.responses[200] = { description: 'Posted', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[400] = { description: 'Rejected (over caps)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[503] = { description: 'Shard unavailable', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */

View File

@@ -39,7 +39,7 @@ shardRouter.get(
// #swagger.summary = 'A user’s linked game accounts (admin only)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
// #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'User id.' }
/* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardLink" } } } } } */
/* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardLink" } } } } } */
/* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('id').isInt(),
validate,
@@ -51,7 +51,7 @@ shardRouter.get(
// #swagger.summary = 'Recent vendor sales on a user’s accounts (admin only)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
// #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'integer' }, description: 'User id.' }
/* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardVendorSale" } } } } } */
/* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardVendorSale" } } } } } */
/* #swagger.responses[404] = { description: 'Not found', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('id').isInt(),
validate,

View File

@@ -30,8 +30,8 @@ shardRouter.post(
// #swagger.summary = 'Link an in-game account with a one-time code'
// #swagger.description = 'The player runs [link in game to get a code, then submits it here. The server confirms it with the sidecar and mirrors the link.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkRequest" } } } } */
/* #swagger.responses[200] = { description: 'Linked', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardLinkResult" } } } } */
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardLinkRequest" } } } } */
/* #swagger.responses[200] = { description: 'Linked', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardLinkResult" } } } } */
/* #swagger.responses[400] = { description: 'Unknown or expired code', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[503] = { description: 'Shard unavailable — retry', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
body('code').isString().trim().isLength({ min: 4, max: 32 }),
@@ -44,7 +44,7 @@ shardRouter.post(
// #swagger.summary = 'Create a game account (hybrid signup) and link it to the caller'
// #swagger.description = 'Provisions a new game account with its own username + password and auto-links it to the signed-in website user. Available only when game_account_signup is enabled and the shard accepts website signups. The password is hashed on the shard and never stored or logged by the site.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["account","password"], properties: { account: { type: "string" }, password: { type: "string" } } } } } */
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", required: ["account","password"], properties: { account: { type: "string" }, password: { type: "string" } } } } } } */
/* #swagger.responses[201] = { description: 'Account created and linked', content: { "application/json": { schema: { type: "object", properties: { account: { type: "string" }, linked: { type: "boolean" } } } } } } */
/* #swagger.responses[400] = { description: 'Validation error or rejected name/password', content: { "application/json": { schema: { $ref: "#/components/schemas/ValidationError" } } } } */
/* #swagger.responses[403] = { description: 'Game-account signup unavailable (site or shard)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
@@ -62,7 +62,7 @@ shardRouter.get(
// #swagger.tags = ['Player · Shard']
// #swagger.summary = 'List the caller’s linked game accounts'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardLink" } } } } } */
/* #swagger.responses[200] = { description: 'Linked accounts', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardLink" } } } } } */
shard.listAccounts,
)
shardRouter.get(
@@ -109,7 +109,7 @@ shardRouter.get(
// #swagger.tags = ['Player · Shard']
// #swagger.summary = 'Recent player-vendor sales for the caller’s linked accounts'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardVendorSale" } } } } } */
/* #swagger.responses[200] = { description: 'Vendor sales', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardVendorSale" } } } } } */
shard.getSales,
)
shardRouter.get(
@@ -118,7 +118,7 @@ shardRouter.get(
// #swagger.summary = 'The caller’s own houses (home status)'
// #swagger.description = 'Houses owned by the caller’s linked accounts, with decay/IDOC status. Only the caller’s own houses — never anyone else’s.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'The caller’s houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
/* #swagger.responses[200] = { description: 'The caller’s houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardHouse" } } } } } */
shard.getHouses,
)

View File

@@ -38,12 +38,12 @@ atlasRouter.get(
requireFeature('atlas'),
// #swagger.tags = ['Public · Atlas']
// #swagger.summary = 'Search the bestiary (paginated)'
// #swagger.description = 'Every creature the shard spawns, most numerous first. `total` is how many can be alive at once across all spawners; `points` is how many spawners mention it; `facets` maps facet name to that creature\'s share on it. Static content parsed from the shard\'s ServUO tree — unaffected by the shard being offline.'
// #swagger.description = 'Every creature the shard spawns, most numerous first. `total` is how many can be alive at once across all spawners; `points` is how many spawners mention it; `facets` maps facet name to that creature’s share on it. Static content parsed from the shard’s ServUO tree — unaffected by the shard being offline.'
// #swagger.parameters['q'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Substring match on the creature name (max 60 chars).' }
// #swagger.parameters['facet'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to creatures spawning on this facet. Facet names come from the shard\'s own files; an unknown one returns an empty page.' }
// #swagger.parameters['facet'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to creatures spawning on this facet. Facet names come from the shard’s own files; an unknown one returns an empty page.' }
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Page size, 1..100 (default 50).' }
// #swagger.parameters['offset'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Rows to skip (default 0).' }
/* #swagger.responses[200] = { description: 'A page of creatures plus the unpaginated total', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasCreaturePage" } } } } */
/* #swagger.responses[200] = { description: 'A page of creatures plus the unpaginated total', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasCreaturePage" } } } } */
/* #swagger.responses[403] = { description: 'The atlas feature is gated above this caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[404] = { description: 'The atlas feature is disabled', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
query('q').optional({ values: 'falsy' }).isString().isLength({ max: 60 }),
@@ -59,11 +59,11 @@ atlasRouter.get(
requireFeature('atlas'),
// #swagger.tags = ['Public · Atlas']
// #swagger.summary = 'One creature: where it spawns, and what spawns with it'
// #swagger.description = 'The answer the atlas exists to give. `places` is the aggregate — "lizardman → Shrines, Isamu-Jima, Yew" — resolved by point-in-rect against the shard\'s own region rectangles, falling back to the nearest landmark, else "Wilderness". `spawners` lists the individual spawn points (bounded; `spawnersTruncated` says when the list was cut), and `alsoHere` is what shares those spawners.'
// #swagger.description = 'The answer the atlas exists to give. `places` is the aggregate — "lizardman → Shrines, Isamu-Jima, Yew" — resolved by point-in-rect against the shard’s own region rectangles, falling back to the nearest landmark, else "Wilderness". `spawners` lists the individual spawn points (bounded; `spawnersTruncated` says when the list was cut), and `alsoHere` is what shares those spawners.'
// #swagger.parameters['slug'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'Creature slug, e.g. lizardman.' }
// #swagger.parameters['facet'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Restrict places and spawners to one facet.' }
// #swagger.parameters['points'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max spawners to return, 1..1000 (default 200).' }
/* #swagger.responses[200] = { description: 'The creature', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasCreature" } } } } */
/* #swagger.responses[200] = { description: 'The creature', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasCreature" } } } } */
/* #swagger.responses[404] = { description: 'No such creature in this atlas (or the feature is disabled)', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
param('slug').isString().isLength({ min: 1, max: 120 }),
facetParam,
@@ -77,10 +77,10 @@ atlasRouter.get(
requireFeature('atlas'),
// #swagger.tags = ['Public · Atlas']
// #swagger.summary = 'Named regions and their rectangles'
// #swagger.description = 'Flattened out of the shard\'s nested Regions.xml. `priority` and the rectangles are what placed each spawn point, kept so the placement can be re-derived rather than taken on trust.'
// #swagger.description = 'Flattened out of the shard’s nested Regions.xml. `priority` and the rectangles are what placed each spawn point, kept so the placement can be re-derived rather than taken on trust.'
// #swagger.parameters['facet'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to one facet.' }
// #swagger.parameters['q'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Substring match on the region name.' }
/* #swagger.responses[200] = { description: 'Regions, by facet then name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/AtlasRegion" } } } } } */
/* #swagger.responses[200] = { description: 'Regions, by facet then name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoAtlasRegion" } } } } } */
facetParam,
query('q').optional({ values: 'falsy' }).isString().isLength({ max: 60 }),
validate,
@@ -92,10 +92,10 @@ atlasRouter.get(
requireFeature('atlas'),
// #swagger.tags = ['Public · Atlas']
// #swagger.summary = 'Points of interest (dungeon levels, town markers)'
// #swagger.description = 'From the shard\'s Data/Locations files. `group` is the innermost enclosing parent ("Covetous"), which is the label worth showing over the individual marker ("Level 1").'
// #swagger.description = 'From the shard’s Data/Locations files. `group` is the innermost enclosing parent ("Covetous"), which is the label worth showing over the individual marker ("Level 1").'
// #swagger.parameters['facet'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to one facet.' }
// #swagger.parameters['q'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Substring match on the landmark name or its group.' }
/* #swagger.responses[200] = { description: 'Landmarks, by facet then group', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/AtlasLandmark" } } } } } */
/* #swagger.responses[200] = { description: 'Landmarks, by facet then group', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoAtlasLandmark" } } } } } */
facetParam,
query('q').optional({ values: 'falsy' }).isString().isLength({ max: 60 }),
validate,
@@ -109,7 +109,7 @@ atlasRouter.get(
// #swagger.summary = 'Configured champion altars (the roster, not the live board)'
// #swagger.description = 'Where the altars are and what each one summons — "there is an Unholy Terror altar in Deceit". `randomType` marks altars whose champion is drawn at activation. Do not conflate this with GET /public/shard/champs, which is the live sidecar-fed board ("it is on level 3 right now").'
// #swagger.parameters['facet'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to one facet.' }
/* #swagger.responses[200] = { description: 'Altars, by facet then name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/AtlasChampion" } } } } } */
/* #swagger.responses[200] = { description: 'Altars, by facet then name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoAtlasChampion" } } } } } */
facetParam,
validate,
siteMode,
@@ -120,8 +120,8 @@ atlasRouter.get(
requireFeature('atlas'),
// #swagger.tags = ['Public · Atlas']
// #swagger.summary = 'What atlas is loaded: facets, counts, when it was imported'
// #swagger.description = 'Drives the facet filter and the "parsed from the shard\'s own files on <date>" line. Reports the game world only — the ServUO path, the per-file hashes and any pending refresh are operator detail and live on the admin status route.'
/* #swagger.responses[200] = { description: 'Atlas metadata', content: { "application/json": { schema: { $ref: "#/components/schemas/AtlasMeta" } } } } */
// #swagger.description = 'Drives the facet filter and the "parsed from the shard’s own files on <date>" line. Reports the game world only — the ServUO path, the per-file hashes and any pending refresh are operator detail and live on the admin status route.'
/* #swagger.responses[200] = { description: 'Atlas metadata', content: { "application/json": { schema: { $ref: "#/components/schemas/UoAtlasMeta" } } } } */
siteMode,
atlas.getMeta,
)

View File

@@ -177,6 +177,31 @@ async function getGuilds(req, res) {
}
}
// GET /public/shard/guilds/:id — one guild and its roster.
//
// The board endpoint above returns every guild WITHOUT its roster; this is the
// detail view, and it is the page that hosts core's Team activity feed through
// the `uo.guild.detail` slot (docs/website/TEAMS.md Part 3).
//
// Projected through the same `guilds` feature as the board, so an operator who
// gates guilds to staff gates this too, and `acct`/`webId` on the roster rows
// never survive below admin — those are LOCKED fields, and a roster is where they
// actually appear in bulk.
async function getGuild(req, res) {
try {
const guilds = await shardState.listGuilds()
const guild = guilds.find((g) => String(g.id) === String(req.params.id))
// 404 rather than an empty object: a guild that disbanded is gone, and the
// page needs to say so rather than render an empty shell.
if (!guild) return res.status(404).json({ message: 'Not Found' })
const members = await shardState.listGuildMembers(guild.id)
return res.json(await visibility.project('guilds', { ...guild, roster: members }, req))
} catch (err) {
log.error('shard.getGuild', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// GET /public/shard/governors — the current town-governor board (empty on shards
// without City Loyalty). Live via city.update on the public SSE stream. Projected
// for the same reason as getGuilds: `governor` / `governorElect` are actors.
@@ -421,6 +446,7 @@ module.exports = {
getIdoc,
getChamps,
getGuilds,
getGuild,
getGovernors,
getGovernorHistory,
getPresence,

View File

@@ -37,7 +37,7 @@ shardRouter.get(
requireFeature('status'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Shard connection state, online count and latest economy'
/* #swagger.responses[200] = { description: 'Shard status', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardStatus" } } } } */
/* #swagger.responses[200] = { description: 'Shard status', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardStatus" } } } } */
shard.getStatus,
)
shardRouter.get(
@@ -45,10 +45,10 @@ shardRouter.get(
requireFeature('activity'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Recent notable shard events (from the ingested log)'
// #swagger.description = 'The stored-history twin of /shard/stream, and it reaches the same verdict: which kinds are returned is resolved against the caller\'s audience rung under the live visibility config, and each event\'s payload is field-projected against its own kind\'s feature. Kinds the caller may not read are omitted (an explicit ?kind= for one of them returns []), and acct/webId never appear below admin.'
// #swagger.description = 'The stored-history twin of /shard/stream, and it reaches the same verdict: which kinds are returned is resolved against the caller’s audience rung under the live visibility config, and each event’s payload is field-projected against its own kind’s feature. Kinds the caller may not read are omitted (an explicit ?kind= for one of them returns []), and acct/webId never appear below admin.'
// #swagger.parameters['kind'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Filter to a single event kind, e.g. vendor.sale. Returns [] if the caller may not read that kind.' }
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max rows (default 100, max 1000).' }
/* #swagger.responses[200] = { description: 'Events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEvent" } } } } } */
/* #swagger.responses[200] = { description: 'Events, newest first', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardEvent" } } } } } */
query('kind').optional({ values: 'falsy' }).isString().isLength({ max: 48 }),
query('limit').optional().isInt({ min: 1, max: 1000 }),
validate,
@@ -60,7 +60,7 @@ shardRouter.get(
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Gold-supply time series (oldest → newest)'
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Max samples (default 100, max 1000).' }
/* #swagger.responses[200] = { description: 'Economy samples', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardEconomyPoint" } } } } } */
/* #swagger.responses[200] = { description: 'Economy samples', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardEconomyPoint" } } } } } */
query('limit').optional().isInt({ min: 1, max: 1000 }),
validate,
shard.getEconomy,
@@ -70,7 +70,7 @@ shardRouter.get(
requireFeature('presence'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Staff online now (linked staff accounts; location is admin/moderator-only)'
/* #swagger.responses[200] = { description: 'Online players', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardOnlinePlayer" } } } } } */
/* #swagger.responses[200] = { description: 'Online players', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardOnlinePlayer" } } } } } */
shard.getOnline,
)
shardRouter.get(
@@ -78,8 +78,8 @@ shardRouter.get(
requireFeature('houses'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Houses currently in danger (IDOC)'
// #swagger.description = 'Location-level board of the houses about to collapse. Owner identity and price are gated by the `houses` feature\'s field rules (default `staff`), and the owner\'s game account is admin-only always — so an anonymous caller sees name, region and coordinates only.'
/* #swagger.responses[200] = { description: 'IDOC houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
// #swagger.description = 'Location-level board of the houses about to collapse. Owner identity and price are gated by the `houses` feature’s field rules (default `staff`), and the owner’s game account is admin-only always — so an anonymous caller sees name, region and coordinates only.'
/* #swagger.responses[200] = { description: 'IDOC houses', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardHouse" } } } } } */
shard.getIdoc,
)
shardRouter.get(
@@ -100,6 +100,17 @@ shardRouter.get(
/* #swagger.responses[200] = { description: 'Guilds, ordered by name', content: { "application/json": { schema: { type: "array", items: { type: "object", additionalProperties: true } } } } } */
shard.getGuilds,
)
shardRouter.get(
'/guilds/:id',
requireFeature('guilds'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'One guild and its roster'
// #swagger.description = 'The detail view behind the board. Gated and projected through the same `guilds` feature, so an operator who raises that audience raises this too, and the locked acct/webId fields never survive below admin — a roster is where they appear in bulk. This page is also where core renders the Team activity feed, through the `uo.guild.detail` extension slot.'
// #swagger.parameters['id'] = { in: 'path', required: true, schema: { type: 'string' }, description: 'The guild id.' }
/* #swagger.responses[200] = { description: 'The guild, with its roster', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[404] = { description: 'No such guild', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
shard.getGuild,
)
shardRouter.get(
'/governors',
requireFeature('governors'),
@@ -137,14 +148,14 @@ shardRouter.get(
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'House registry (owner, co-owners, price, decay)'
// #swagger.description = 'Every house seen via the house.update registry feed. `price` is the placement value, not a for-sale flag. Live via house.update / house.remove on /shard/stream.'
/* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardHouse" } } } } } */
/* #swagger.responses[200] = { description: 'Houses, ordered by name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardHouse" } } } } } */
shard.getHouses,
)
shardRouter.get(
'/ruleset',
requireFeature('ruleset'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'The shard\'s published ruleset (expansion, systems, caps, limits)'
// #swagger.summary = 'The shard’s published ruleset (expansion, systems, caps, limits)'
// #swagger.description = 'How this shard is actually configured, published by the shard itself as one world.ruleset frame: expansion, which optional systems are on, skill/stat caps, account and house limits, champion scroll rules and the save/restart schedule. Served from our own store, so it renders while the shard is down; live via world.ruleset on /shard/stream. Returns `null` if the shard has never published one (an older plugin, or Bridge.RulesetEnabled=false) — distinct from a published ruleset, and the page renders it differently.'
/* #swagger.responses[200] = { description: 'The ruleset, or null if never published', content: { "application/json": { schema: { type: "object", nullable: true, additionalProperties: true } } } } */
shard.getRuleset,
@@ -154,18 +165,18 @@ shardRouter.get(
requireFeature('leaderboards'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Points / loyalty leaderboards, one board per point system'
// #swagger.description = 'Every points/loyalty leaderboard the shard publishes (Queen\'s Loyalty, Void Pool, the nine city loyalties, Clean Up Britannia, …), each with its display name, max points, participant count and top N. Served from our own store, so it renders while the shard is down; live via points.board on /shard/stream. A board\'s display name may arrive as a literal (`nameString`) or a cliloc id (`nameNumber`) — resolve clilocs client-side.'
/* #swagger.responses[200] = { description: 'Boards, ordered by display name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/ShardPointsBoard" } } } } } */
// #swagger.description = 'Every points/loyalty leaderboard the shard publishes (Queen’s Loyalty, Void Pool, the nine city loyalties, Clean Up Britannia, …), each with its display name, max points, participant count and top N. Served from our own store, so it renders while the shard is down; live via points.board on /shard/stream. A board’s display name may arrive as a literal (`nameString`) or a cliloc id (`nameNumber`) — resolve clilocs client-side.'
/* #swagger.responses[200] = { description: 'Boards, ordered by display name', content: { "application/json": { schema: { type: "array", items: { $ref: "#/components/schemas/UoShardPointsBoard" } } } } } */
shard.getPointsBoards,
)
shardRouter.get(
'/points/:system',
requireFeature('leaderboards'),
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'One points system\'s leaderboard'
// #swagger.description = 'A single board by the shard\'s own PointsType name (e.g. `QueensLoyalty`, `CleanUpBritannia`). Returns 404 when the shard has never published that system — distinct from a published board that nobody has scored in yet, which returns 200 with an empty `top`.'
// #swagger.summary = 'One points system’s leaderboard'
// #swagger.description = 'A single board by the shard’s own PointsType name (e.g. `QueensLoyalty`, `CleanUpBritannia`). Returns 404 when the shard has never published that system — distinct from a published board that nobody has scored in yet, which returns 200 with an empty `top`.'
/* #swagger.parameters['system'] = { in: 'path', required: true, description: 'PointsType name, e.g. QueensLoyalty', schema: { type: 'string' } } */
/* #swagger.responses[200] = { description: 'The board', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardPointsBoard" } } } } */
/* #swagger.responses[200] = { description: 'The board', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardPointsBoard" } } } } */
/* #swagger.responses[400] = { description: 'Malformed system name' } */
/* #swagger.responses[404] = { description: 'The shard has never published that system' } */
shard.getPointsBoard,
@@ -181,17 +192,17 @@ shardRouter.get(
marketLimiter,
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Search the player-vendor marketplace'
// #swagger.description = 'Every priced listing on every player vendor the shard publishes — the same index the in-game Vendor Search gump reads, and it honours the same per-vendor opt-out, so a player who hid their shop in game is hidden here too. Results are LISTINGS, each carrying enough of its shop to be actionable. Served from the site\'s own tables (the sidecar is not touched), so it renders while the shard is down; `staleAt` is the oldest vendor row and the page must say how far behind the index can be — the shard sweeps vendors round-robin, so prices are inherently up to one full cycle old. Item names are resolved server-side against the cliloc table (docs/website/CLILOCS.md); on a shard that has not configured one, `displayName` is null and clients render the item id.'
// #swagger.parameters['q'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Substring match on the resolved item name or the item\'s own literal name (max 60 chars).' }
// #swagger.description = 'Every priced listing on every player vendor the shard publishes — the same index the in-game Vendor Search gump reads, and it honours the same per-vendor opt-out, so a player who hid their shop in game is hidden here too. Results are LISTINGS, each carrying enough of its shop to be actionable. Served from the site’s own tables (the sidecar is not touched), so it renders while the shard is down; `staleAt` is the oldest vendor row and the page must say how far behind the index can be — the shard sweeps vendors round-robin, so prices are inherently up to one full cycle old. Item names are resolved server-side against the cliloc table (docs/website/CLILOCS.md); on a shard that has not configured one, `displayName` is null and clients render the item id.'
// #swagger.parameters['q'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Substring match on the resolved item name or the item’s own literal name (max 60 chars).' }
// #swagger.parameters['minPrice'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Lowest price to include.' }
// #swagger.parameters['maxPrice'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Highest price to include.' }
// #swagger.parameters['itemId'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Exact ItemID (art id) match, for "more like this".' }
// #swagger.parameters['map'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to one facet. Facet names come from the shard\'s own data; an unknown one returns an empty page.' }
// #swagger.parameters['itemId'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Exact ItemID (art id) match — the more-like-this filter.' }
// #swagger.parameters['map'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to one facet. Facet names come from the shard’s own data; an unknown one returns an empty page.' }
// #swagger.parameters['region'] = { in: 'query', required: false, schema: { type: 'string' }, description: 'Limit to one named region.' }
// #swagger.parameters['sort'] = { in: 'query', required: false, schema: { type: 'string', enum: ['price_asc','price_desc','recent'] }, description: 'Default price_asc. `recent` orders by when the shop was last seen.' }
// #swagger.parameters['sort'] = { in: 'query', required: false, schema: { type: 'string', enum: ['price_asc','price_desc','recent'] }, description: 'Default price_asc. recent orders by when the shop was last seen.' }
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Page size, 1..100 (default 50).' }
// #swagger.parameters['offset'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Rows to skip (default 0).' }
/* #swagger.responses[200] = { description: 'A page of listings plus the unpaginated total and the staleness stamp', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardMarketPage" } } } } */
/* #swagger.responses[200] = { description: 'A page of listings plus the unpaginated total and the staleness stamp', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardMarketPage" } } } } */
/* #swagger.responses[403] = { description: 'The market feature is gated above this caller', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[404] = { description: 'The market feature is disabled', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[429] = { description: 'Rate limited', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
@@ -213,7 +224,7 @@ shardRouter.get(
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Marketplace size, staleness and filter options'
// #swagger.description = 'How many vendors and listings the index holds, how stale it may be (`staleAt` = the oldest vendor row, `freshAt` = the newest), and which facets and regions actually hold vendors — so a client can build its filters without running a search it will discard.'
/* #swagger.responses[200] = { description: 'Marketplace metadata', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardMarketMeta" } } } } */
/* #swagger.responses[200] = { description: 'Marketplace metadata', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardMarketMeta" } } } } */
shard.getMarketMeta,
)
shardRouter.get(
@@ -226,7 +237,7 @@ shardRouter.get(
/* #swagger.parameters['serial'] = { in: 'path', required: true, description: 'Vendor serial, e.g. 0x40001234', schema: { type: 'string' } } */
// #swagger.parameters['limit'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Listings to return, 1..500 (default 250).' }
// #swagger.parameters['offset'] = { in: 'query', required: false, schema: { type: 'integer' }, description: 'Listings to skip (default 0).' }
/* #swagger.responses[200] = { description: 'The vendor', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardMarketVendor" } } } } */
/* #swagger.responses[200] = { description: 'The vendor', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardMarketVendor" } } } } */
/* #swagger.responses[400] = { description: 'Malformed vendor serial' } */
/* #swagger.responses[404] = { description: 'No such vendor in the index' } */
param('serial').isString().isLength({ max: 20 }),
@@ -239,15 +250,15 @@ shardRouter.get(
'/features',
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Shard features visible to the caller (drives client nav)'
// #swagger.description = 'The caller\'s audience rung plus the shard features they may reach, so a client can hide nav entries instead of rendering links that 403. Reports only what the caller can see — the list itself does not disclose gated features.'
/* #swagger.responses[200] = { description: 'Visible features', content: { "application/json": { schema: { $ref: "#/components/schemas/ShardFeatures" } } } } */
// #swagger.description = 'The caller’s audience rung plus the shard features they may reach, so a client can hide nav entries instead of rendering links that 403. Reports only what the caller can see — the list itself does not disclose gated features.'
/* #swagger.responses[200] = { description: 'Visible features', content: { "application/json": { schema: { $ref: "#/components/schemas/UoShardFeatures" } } } } */
shard.getFeatures,
)
shardRouter.get(
'/stream',
// #swagger.tags = ['Public · Shard']
// #swagger.summary = 'Live shard event stream (Server-Sent Events, filtered by audience)'
// #swagger.description = 'text/event-stream of live events. The caller\'s audience rung is resolved once at subscribe time and frozen for the connection; each frame is then gated on its feature and field-projected, so sensitive kinds and fields (staff audit, cheat detection, login attempts, IPs, acct/webId) never reach a caller below their configured rung.'
// #swagger.description = 'text/event-stream of live events. The caller’s audience rung is resolved once at subscribe time and frozen for the connection; each frame is then gated on its feature and field-projected, so sensitive kinds and fields (staff audit, cheat detection, login attempts, IPs, acct/webId) never reach a caller below their configured rung.'
/* #swagger.responses[200] = { description: 'An SSE stream (Content-Type: text/event-stream).' } */
shard.stream,
)

View File

@@ -0,0 +1,189 @@
#!/usr/bin/env node
// ── §5.3 — this module's frozen route manifest ─────────────────────────────
//
// Core freezes its URL surface in `server/routes.manifest.json` by walking the
// live Express stack and committing the result; a PR that moves a URL has to
// commit the new manifest, which puts the change in front of a reviewer. After
// phase 3 the seventy URLs this module serves are no longer in that file. They
// are here, frozen the same way and by the same generator.
//
// **The module's routes are DERIVED, never listed.** This script is handed two
// manifests generated from the SAME core at the pinned ref — one without this
// module on the volume, one with — and the difference is what this module serves.
// Nothing here says "/api/v1/public/shard/*"; a mount prefix appears in exactly
// one place, `server/index.js`'s `registerRoutes` call, which is where an operator's
// core reads it from too.
//
// Taking the difference rather than filtering by prefix buys the other half of
// §5.3 for free, and it is the half that matters most: **no core URL may move.**
// A module that shadowed a core route, or whose mount displaced one, shows up
// here as a removal or a change, not merely as an addition somewhere else. That
// is the promise §1.2 makes to the shipped Android app and the Discord bot.
//
// The third thing it checks is the OpenAPI fragment (§2.8). `swagger-fragment.json`
// is generated from the module's own registrations against §2.4's stated tier
// bases — the one place a constant could be wrong. Here there is ground truth: a
// real core with this module loaded, reporting the URLs it actually serves. Every
// route must have a documented operation and every documented operation must be a
// route. That is the per-module form of core's standing rule, never ship a route
// that isn't in the spec — and it is what stops a wrong constant in the generator
// from producing a fragment that is internally consistent and describes nothing
// core will ever serve.
//
// Usage (the workflow does the cloning; see .gitea/workflows/frozen-manifest.yml):
// node scripts/frozenManifest.js --before core-only.json --after core-plus-uo.json
// node scripts/frozenManifest.js --before … --after … --check
const fs = require('fs')
const path = require('path')
const MODULE_ROOT = path.resolve(__dirname, '..', '..')
const MANIFEST = path.join(MODULE_ROOT, 'routes.manifest.json')
const FRAGMENT = path.join(MODULE_ROOT, 'swagger-fragment.json')
const COMMENT =
'Generated inventory of the URLs module-uo 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 workflow; see server/scripts/frozenManifest.js.'
const key = (r) => `${r.method} ${r.path}`
/**
* The module's routes, plus proof that core's own surface did not move.
*
* @param {object} before routes.manifest.json from core alone
* @param {object} after routes.manifest.json from the same core with this module
* @returns {{ added: object[], removed: string[] }}
*/
function diffManifests(before, after) {
const added = []
const removed = []
for (const tier of ['public', 'internal']) {
const was = new Set((before[tier] || []).map(key))
for (const route of after[tier] || []) {
if (!was.has(key(route))) added.push({ ...route, tier })
was.delete(key(route))
}
for (const gone of was) removed.push(`${tier} ${gone}`)
}
added.sort((a, b) => (key(a) < key(b) ? -1 : 1))
return { added, removed }
}
/**
* Which of the module's routes the fragment fails to document, and vice versa.
*
* Express `:id` is OpenAPI `{id}`; the fragment is already in OpenAPI's spelling
* because that is what core merges, so the manifest's paths are converted here
* rather than the other way round.
*/
function coverage(added, fragment) {
const documented = new Set()
for (const [p, item] of Object.entries(fragment.paths || {})) {
for (const method of Object.keys(item)) documented.add(`${method.toUpperCase()} ${p}`)
}
const undocumented = []
for (const route of added) {
const oas = `${route.method} ${route.path.replace(/:([A-Za-z0-9_]+)/g, '{$1}')}`
if (documented.has(oas)) documented.delete(oas)
else undocumented.push(oas)
}
// Whatever is left is documented and not served: a route that moved or was
// deleted while its annotation stayed behind. Core's spec has no equivalent
// check and grew four orphan tags and thirty-three orphan schemas because of it.
return { undocumented, unserved: [...documented].sort() }
}
function serialize(routes) {
return `${JSON.stringify(
{
$comment: COMMENT,
routes: routes.map(({ method, path: p, tier }) => ({ method, path: p, tier })),
},
null,
2,
)}\n`
}
function main() {
const arg = (name) => {
const i = process.argv.indexOf(name)
return i === -1 ? null : process.argv[i + 1]
}
const beforePath = arg('--before')
const afterPath = arg('--after')
if (!beforePath || !afterPath) {
process.stderr.write('usage: frozenManifest.js --before <manifest> --after <manifest> [--check]\n')
process.exit(2)
}
const before = JSON.parse(fs.readFileSync(beforePath, 'utf8'))
const after = JSON.parse(fs.readFileSync(afterPath, 'utf8'))
const { added, removed } = diffManifests(before, after)
let failed = false
if (removed.length > 0) {
process.stderr.write(
`\nLoading this module REMOVED or CHANGED ${removed.length} of core's own route(s):\n` +
`${removed.map((r) => ` - ${r}`).join('\n')}\n` +
'A module may only add. This is the frozen-URL promise (MODULE_SYSTEM.md §1.2) breaking.\n',
)
failed = true
}
if (added.length === 0) {
process.stderr.write(
'\nLoading this module added NO routes. Either it failed to load in the core checkout\n' +
'(check the boot log for a startup_failed line) or the two manifests are the same file.\n',
)
process.exit(1)
}
const fragment = JSON.parse(fs.readFileSync(FRAGMENT, 'utf8'))
const { undocumented, unserved } = coverage(added, fragment)
if (undocumented.length > 0) {
process.stderr.write(
`\n${undocumented.length} route(s) this module serves have no operation in swagger-fragment.json:\n` +
`${undocumented.map((r) => ` - ${r}`).join('\n')}\n` +
'Run `npm run swagger --prefix server` and commit the result (MODULE_API.md §2.8).\n',
)
failed = true
}
if (unserved.length > 0) {
process.stderr.write(
`\n${unserved.length} operation(s) in swagger-fragment.json are not routes this module serves:\n` +
`${unserved.map((r) => ` - ${r}`).join('\n')}\n` +
'A documented URL nobody serves is a client following the docs into a 404.\n',
)
failed = true
}
if (failed) process.exit(1)
const contents = serialize(added)
if (process.argv.includes('--check')) {
const current = fs.existsSync(MANIFEST) ? fs.readFileSync(MANIFEST, 'utf8').replace(/\r\n/g, '\n') : null
if (current !== contents) {
process.stderr.write(
'\nroutes.manifest.json is stale. The URLs this module serves changed — regenerate it and\n' +
'commit the result so the move is reviewed rather than merged as mechanical.\n',
)
process.exit(1)
}
process.stdout.write(`routes.manifest.json is current — ${added.length} routes, all documented\n`)
return
}
fs.writeFileSync(MANIFEST, contents)
process.stdout.write(`wrote routes.manifest.json — ${added.length} routes, all documented\n`)
}
if (require.main === module) main()
module.exports = { diffManifests, coverage, serialize, MANIFEST, FRAGMENT }

View File

@@ -0,0 +1,281 @@
#!/usr/bin/env node
// ── §2.8 — the OpenAPI fragment ────────────────────────────────────────────
//
// Generates (or checks) `swagger-fragment.json` in the bundle root: the paths,
// tags and schemas describing every route this module registers. Core merges the
// fragments of *started* modules over its own committed spec at request time and
// serves the result at `/api/docs.json` (docs/website/MODULE_API.md §6.1a).
//
// **Why a module ships a fragment at all.** Core's `npm run swagger` is STATIC
// analysis — swagger-autogen parses `src/app.js` as text and follows the literal
// `app.use(...)` chain. A module arrives on a volume after core was built, is
// required by a filesystem loop, and mounts through `api.registerRoutes()`. There
// is no literal mount for a parser to follow and core does not have our sources
// anyway, so nothing core can run will ever describe these routes. The failure
// mode is the dangerous one: swagger-autogen reports success and emits a spec
// with the routes simply absent (§6.1, and core hit it twice — the spike's atlas
// paths and PR 4's 407 deleted lines).
//
// ── Where the prefixes come from ───────────────────────────────────────────
//
// swagger-autogen is pointed at one router file at a time, so its paths come out
// relative to that router (`/status`, not `/api/v1/public/shard/status`) — nothing
// in the file says where it hangs. §6.1a requires fully-qualified paths, because
// core merges the fragment verbatim and never re-derives a prefix.
//
// So this script **runs the module's own `register()`** against a recording `api`
// and reads the mounts back out of it. The prefix of every router is therefore the
// prefix that router is actually registered under — the same call an operator's
// core will make, not a table beside it that drifts the first time a mount moves.
// Which router a recorded object came from is answered by `require.cache`: the
// file whose `module.exports` IS this router.
//
// The two things that cannot be derived here are the tier base paths and the
// extension slot's mount, because they are core's, not ours. They are §2.4's
// normative table, quoted below — and they are not taken on trust: the frozen
// route manifest (`scripts/frozenManifest.js`) generates the real URLs from a real
// core with this module loaded, and fails if a fragment path is not among them.
// That check is where a wrong constant here dies.
const fs = require('fs')
const os = require('os')
const path = require('path')
const swaggerAutogen = require('swagger-autogen')({ openapi: '3.0.0' })
const { fakeCtx, fakeApi } = require('../test/_fakes')
const doc = require('../swagger/doc')
const MODULE_ROOT = path.resolve(__dirname, '..', '..')
const SERVER_ROOT = path.join(MODULE_ROOT, 'server')
const FRAGMENT = path.join(MODULE_ROOT, 'swagger-fragment.json')
// MODULE_API.md §2.4. A router registered under a tier sits inside that tier's
// router in core, behind its gate; the tier's own base path is core's and fixed
// by §1.2's frozen URL surface.
const TIER_BASE = {
public: '/api/v1/public',
admin: '/api/v1/admin',
player: '/api/v1/player',
}
// MODULE_API.md §2.4's slot table. Exactly one slot exists in v1, and only core
// may declare one — so a module filling it has to be told where it landed.
const SLOT_MOUNT = {
'admin.users.detail': '/api/v1/admin/users/:id',
}
/**
* Run `register()` with a recording api and return `[{ file, prefix }]`.
*
* The ctx is the test fakes' — the same one the suite proves the module runs
* against — because registration must not touch a database (§2.2 rule 1) and this
* script is exactly the kind of no-database caller that rule exists for.
*/
function mountedRouters() {
const register = require('../index')
const api = fakeApi()
register(fakeCtx(), api)
const fileOf = (router) => {
for (const mod of Object.values(require.cache)) {
if (mod && mod.exports === router) return mod.filename
}
return null
}
const mounts = []
for (const [tier, byPrefix] of Object.entries(api.record.routes || {})) {
const base = TIER_BASE[tier]
if (!base) throw new Error(`swagger: registered under unknown tier "${tier}" — §2.4 has three`)
for (const [prefix, router] of Object.entries(byPrefix)) {
mounts.push({ router, prefix: base + prefix, what: `${tier}${prefix}` })
}
}
for (const { slot, router } of api.record.extensions) {
const mount = SLOT_MOUNT[slot]
if (!mount) throw new Error(`swagger: filled slot "${slot}", which §2.4's table does not list`)
mounts.push({ router, prefix: mount, what: `slot ${slot}` })
}
return mounts.map(({ router, prefix, what }) => {
const file = fileOf(router)
if (!file) {
// A router built inline in index.js rather than required from its own file.
// swagger-autogen needs a file to read, so there is nothing to generate from.
throw new Error(`swagger: cannot find the source file of the router for ${what}`)
}
return { file, prefix, what }
})
}
/**
* Run swagger-autogen over one router file. Paths come out router-relative.
*
* **swagger-autogen reports a broken annotation and then succeeds anyway** — it
* `console.error`s "Syntax error" or "out of structure", drops that one
* annotation, and prints `Success` in green. Four of the annotations that came
* across in slice 1 were broken that way and had been for as long as they had
* existed in core: two `requestBody` literals a brace short, and two descriptions
* whose inner quoting the tool cannot survive (it re-quotes `"` and a backtick to
* `'` before evaluating, so either inside a single-quoted description ends the
* string early). The visible result was a documented route missing its body, or a
* typed query parameter demoted to an untyped one.
*
* So its diagnostics are captured and made fatal. This is the same class as every
* other failure in this seam — a generator that reports success while silently
* dropping what it was asked to describe (§6.1) — and the only difference is that
* here the tool does say something. Nothing was listening.
*/
async function fragmentFor(file) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'uo-swagger-'))
const out = path.join(dir, 'fragment.json')
const complaints = []
const realError = console.error
console.error = (...args) => {
const line = args.map(String).join(' ')
if (/syntax error|out of structure/i.test(line)) complaints.push(line.trim())
else realError(...args)
}
try {
// A DEEP COPY per call, and that is not defensive style. swagger-autogen
// renders `components.schemas` from an EXAMPLE object rather than treating it
// as OpenAPI — `{ type: 'object' }` comes back as `{ type: 'object',
// properties: { type: { type: 'string', example: 'object' } } }`, a
// meta-description of itself. That shape is uniform across core's committed
// spec and is the house shape, so it is matched rather than fought. What is
// NOT survivable is that it writes the result back into the object it was
// handed: reusing one `doc` across six routers re-wraps the previous pass's
// output five more times, and the fragment came out at 484 MB.
await swaggerAutogen(out, [path.relative(SERVER_ROOT, file).split(path.sep).join('/')], {
...JSON.parse(JSON.stringify(doc)),
info: { title: 'module-uo fragment', version: '0' },
})
} finally {
console.error = realError
}
if (complaints.length > 0) {
throw new Error(
`swagger: ${path.relative(MODULE_ROOT, file)} has ${complaints.length} annotation(s) ` +
`swagger-autogen could not parse — it drops them and reports success:\n ${complaints.join('\n ')}`,
)
}
const fragment = JSON.parse(fs.readFileSync(out, 'utf8'))
fs.rmSync(dir, { recursive: true, force: true })
return fragment
}
/**
* Re-root a router-relative fragment under the prefix it is mounted at.
*
* Express path params (`:id`) become OpenAPI's (`{id}`), and the prefix's own
* params are moved to the FRONT of each operation's parameter list: swagger-autogen
* orders parameters by where they appeared in the path it saw, which was only the
* tail, so `/{id}/shard/link/{account}` would otherwise document (account, id).
*/
function prefixPaths(fragment, prefix) {
const oas = prefix.replace(/:([A-Za-z0-9_]+)/g, '{$1}').replace(/\/+$/, '')
const outer = [...oas.matchAll(/\{([A-Za-z0-9_]+)\}/g)].map((m) => m[1])
const paths = {}
for (const [p, item] of Object.entries(fragment.paths || {})) {
for (const operation of Object.values(item)) {
const params = operation && operation.parameters
if (!Array.isArray(params)) continue
const rank = (q) => {
const i = outer.indexOf(q && q.name)
return i === -1 ? outer.length : i
}
operation.parameters = params
.map((q, i) => ({ q, i }))
.sort((a, b) => rank(a.q) - rank(b.q) || a.i - b.i)
.map(({ q }) => q)
}
// `router.get('/')` under a prefix concatenates to `/api/v1/public/shard/`,
// a URL no client calls. Core's swagger.js normalizes the same way.
paths[`${oas}${p}`.replace(/\/$/, '')] = item
}
return paths
}
/**
* Build the whole fragment: every mounted router, re-rooted and merged.
*
* Only `paths`, `tags` and `components.schemas` — the three sections §6.1a allows
* a fragment to carry. `info`, `servers` and the security schemes are the merged
* document's, which is to say core's.
*/
async function build() {
const spec = { paths: {}, tags: [], components: { schemas: {} } }
let shared = false
for (const { file, prefix, what } of mountedRouters()) {
const generated = await fragmentFor(file)
// The tags and schemas are the SAME on every pass — each was handed the same
// `doc` — so they are taken from whichever ran first rather than from `doc`
// itself. What lands in the fragment has to be what swagger-autogen produced,
// not what it was given: those two differ (see fragmentFor), and core merges
// this file verbatim into a spec whose own schemas went through the same mill.
if (!shared) {
spec.tags = generated.tags || []
spec.components.schemas = (generated.components || {}).schemas || {}
shared = true
}
const paths = prefixPaths(generated, prefix)
const count = Object.keys(paths).length
if (count === 0) {
// An empty fragment is precisely what the silent drop looks like, so it is
// a hard failure rather than a router that happens to declare no routes.
throw new Error(`swagger: ${what} (${path.relative(MODULE_ROOT, file)}) generated NO paths`)
}
for (const [p, item] of Object.entries(paths)) {
if (spec.paths[p]) {
throw new Error(`swagger: two of this module's routers both document ${p}`)
}
spec.paths[p] = item
}
process.stdout.write(` ${String(count).padStart(3)} path(s) ${prefix} ← ${what}\n`)
}
// Sorted, for the reason core sorts: swagger-autogen emits router-traversal
// order, so moving a route between files would rewrite most of this committed
// artifact even when the API is provably unchanged.
spec.paths = Object.fromEntries(Object.entries(spec.paths).sort(([a], [b]) => (a < b ? -1 : 1)))
return spec
}
async function main() {
const check = process.argv.includes('--check')
const spec = await build()
const json = `${JSON.stringify(spec, null, 2)}\n`
if (!check) {
fs.writeFileSync(FRAGMENT, json)
process.stdout.write(`\nwrote ${path.relative(MODULE_ROOT, FRAGMENT)} — ${Object.keys(spec.paths).length} paths\n`)
return
}
if (!fs.existsSync(FRAGMENT)) {
process.stderr.write('\nswagger-fragment.json is missing. Run `npm run swagger`.\n')
process.exit(1)
}
if (fs.readFileSync(FRAGMENT, 'utf8') !== json) {
process.stderr.write(
'\nswagger-fragment.json is STALE — the routes or their annotations changed and it was not\n' +
'regenerated. Run `npm run swagger` and commit the result. Core merges this file verbatim,\n' +
'so a stale one documents a URL surface this module does not serve.\n',
)
process.exit(1)
}
process.stdout.write(`\nswagger-fragment.json is current — ${Object.keys(spec.paths).length} paths\n`)
}
if (require.main === module) {
main().catch((err) => {
process.stderr.write(`${err.stack}\n`)
process.exit(1)
})
}
module.exports = { mountedRouters, prefixPaths, build, TIER_BASE, SLOT_MOUNT, FRAGMENT }

621
server/swagger/doc.js Normal file
View File

@@ -0,0 +1,621 @@
// ── module-uo's OpenAPI fragment: the shared half ──────────────────────────
//
// The tags and component schemas every `#swagger.*` annotation under
// `server/router/**` refers to. `scripts/swaggerFragment.js` feeds this to
// swagger-autogen; the per-endpoint detail lives beside each route, exactly as
// it does in core.
//
// These 31 schemas were core's until phase 3 — they sat in
// `website/server/swagger/swagger.js` describing routes core no longer serves,
// which is what an extraction leaves behind if nobody looks (the inert-leaf
// class slice 4 found in `api/client.js`). They moved with the routes.
//
// **Two rules about names, and both are the merged document's, not this file's**
// (docs/website/MODULE_API.md §6.1a):
//
// • **What this module DEFINES is namespaced `Uo…`.** Core merges started
// modules' fragments into one `/api/docs.json`, and core wins every key
// collision — so an un-namespaced `ShardStatus` from a second game's module
// would silently lose to, or clobber, this one. The prefix is what makes two
// modules able to describe the same idea.
// • **What core defines is referenced by CORE's name.** The annotations point
// at `#/components/schemas/Error` and `ValidationError` and this file does
// not redefine them: they resolve in the merged spec, where core's
// definitions are. Shipping our own copy would be a collision core drops,
// which is the correct outcome arrived at the expensive way.
//
// Tag NAMES are core's originals (`Public · Shard`, not `Uo · Shard`). A tag is
// how the docs UI groups operations, and core stopped declaring these four in
// the same slice this file started — nothing collides, and renaming them would
// churn every reader's bookmark for no gain.
module.exports = {
tags: [
{ name: 'Public · Shard', description: 'Live shard data ingested from the uo-link sidecar (status, feed, economy, IDOC, characters)' },
{ name: 'Public · Atlas', description: 'Spawn atlas / bestiary — static shard content parsed from the shard\'s own ServUO tree, independent of the sidecar' },
{ name: 'Player · Shard', description: 'Link an in-game account and read its roster / vendors (uo-link)' },
{ name: 'Admin · Shard', description: 'uo-link sidecar connection config, live status and town crier (admin only)' },
],
components: {
schemas: {
// ── uo-link shard data ──────────────────────────────────────────────
UoShardStatus: {
type: 'object',
description: 'Public shard status (GET /public/shard/status).',
properties: {
enabled: { type: 'boolean', example: true },
status: { type: 'string', example: 'connected', description: 'connected | reconnecting | disconnected | error' },
pluginConnected: { type: 'boolean', description: 'Is the shard link up right now?', example: true },
lastEventAt: { type: 'string', format: 'date-time', nullable: true },
onlineCount: { type: 'integer', example: 12 },
economy: { $ref: '#/components/schemas/UoShardEconomyPoint' },
},
},
UoShardEvent: {
type: 'object',
description: 'A logged shard event.',
properties: {
id: { type: 'integer', example: 4821 },
kind: { type: 'string', example: 'vendor.sale' },
t: { type: 'integer', description: 'Event time, epoch ms.', example: 1783720195626 },
bootId: { type: 'string', nullable: true, example: 'boot-abc123' },
payload: { type: 'object', additionalProperties: true, description: 'The full event object.' },
createdAt: { type: 'string', format: 'date-time' },
},
},
UoShardEconomyPoint: {
type: 'object',
nullable: true,
description: 'One gold-supply sample.',
properties: {
accounts: { type: 'integer', nullable: true, example: 240 },
gold: { type: 'integer', nullable: true, example: 1028983421 },
t: { type: 'integer', description: 'Sample time, epoch ms.', example: 1783720000000 },
},
},
UoShardOnlinePlayer: {
type: 'object',
description: 'A LINKED player online now (only accounts linked to a website user are listed).',
properties: {
serial: { type: 'string', example: '0x24C' },
name: { type: 'string', example: 'Darrow' },
map: { type: 'string', nullable: true, example: 'Trammel' },
x: { type: 'integer', nullable: true, example: 1402 },
y: { type: 'integer', nullable: true, example: 1604 },
z: { type: 'integer', nullable: true, example: 0 },
},
},
UoShardVendorSale: {
type: 'object',
description: 'A player-vendor sale (visible only to the linked owner).',
properties: {
t: { type: 'integer', description: 'Sale time, epoch ms.', example: 1783720195626 },
itemType: { type: 'string', example: 'Longsword' },
amount: { type: 'integer', example: 1 },
price: { type: 'integer', example: 100 },
commission: { type: 'integer', nullable: true, example: 5 },
ownerAcct: { type: 'string', example: 'whitlocktech' },
},
},
UoShardHouse: {
type: 'object',
description: 'A house at its current decay stage.',
properties: {
serial: { type: 'string', example: '0x4004705F' },
stage: { type: 'string', example: 'IDOC' },
map: { type: 'string', nullable: true, example: 'Trammel' },
x: { type: 'integer', nullable: true },
y: { type: 'integer', nullable: true },
z: { type: 'integer', nullable: true },
region: { type: 'string', nullable: true },
name: { type: 'string', nullable: true, example: 'An Unnamed House' },
ownerSerial: { type: 'string', nullable: true },
ownerAcct: { type: 'string', nullable: true },
builtOn: { type: 'string', format: 'date-time', nullable: true },
lastRefreshed: { type: 'string', format: 'date-time', nullable: true },
isIdoc: { type: 'boolean', example: true },
updatedAt: { type: 'string', format: 'date-time' },
},
},
UoShardPointsBoard: {
type: 'object',
description:
"One point system's leaderboard (Protocol 3.0 points.board). The shard carries ~25 separate point currencies; each publishes its own board. The display name may arrive as a literal string, a cliloc id, or both — resolve clilocs client-side.",
properties: {
system: { type: 'string', example: 'QueensLoyalty', description: "The shard's PointsType name; the board's stable key." },
nameString: { type: 'string', nullable: true, example: "Queen's Loyalty" },
nameNumber: { type: 'integer', nullable: true, example: 1114938, description: 'Cliloc id, 0 when the name is a literal.' },
maxPoints: { type: 'integer', nullable: true, example: 30000 },
players: { type: 'integer', nullable: true, example: 842, description: 'Players actually holding points in this system.' },
showOnGump: { type: 'boolean', example: true, description: "The shard's own 'is this player-facing?' flag." },
top: {
type: 'array',
description: 'The ranked players, best first. Capped by the shard (10 by default). Empty when nobody has scored yet.',
items: {
type: 'object',
properties: {
rank: { type: 'integer', example: 1 },
serial: { type: 'string', example: '0x1A2B' },
name: { type: 'string', example: 'Darrow', description: 'Omitted when the leaderboards `name` field is gated above the caller.' },
points: { type: 'integer', example: 29500 },
},
},
},
t: { type: 'integer', nullable: true, description: 'Frame time, epoch ms.' },
updatedAt: { type: 'string', format: 'date-time' },
},
},
UoShardMarketLocation: {
type: 'object',
nullable: true,
description:
"Where a vendor is standing. ONE nested object rather than flat map/x/y/region because it is one admin-configurable field (`market.location`) — the whole object is omitted when that field is gated above the caller.",
properties: {
map: { type: 'string', nullable: true, example: 'Trammel' },
x: { type: 'integer', nullable: true, example: 1421 },
y: { type: 'integer', nullable: true, example: 1699 },
z: { type: 'integer', nullable: true, example: 0 },
region: { type: 'string', nullable: true, example: 'Britain' },
house: { type: 'string', nullable: true, example: "Darrow's Villa", description: "The house SIGN's name, not the house type. Null for a vendor standing outside one." },
},
},
UoShardMarketListing: {
type: 'object',
description:
'One priced listing on a player vendor, carrying enough of its shop to be actionable without a second request.',
properties: {
serial: { type: 'string', example: '0x40012ABC' },
itemId: { type: 'integer', example: 3922, description: 'ItemID (the art/graphic id).' },
hue: { type: 'integer', example: 0 },
amount: { type: 'integer', example: 1 },
price: { type: 'integer', example: 25000 },
name: { type: 'string', nullable: true, description: "The item's own literal name, set by a player. Null for most items." },
cliloc: { type: 'integer', nullable: true, example: 1023721, description: "The item's LabelNumber." },
displayName: {
type: 'string',
nullable: true,
example: 'quarter staff',
description: 'Resolved server-side from `name` (preferred, being player-set and more specific) else `cliloc`. Null on a shard with no cliloc table configured — render the item id.',
},
child: { type: 'boolean', example: false, description: 'Priced by an enclosing container rather than itself, exactly as the in-game Vendor Search reports it.' },
vendor: {
type: 'object',
properties: {
serial: { type: 'string', example: '0x40001234' },
shopName: { type: 'string', nullable: true, example: "Darrow's Bargains" },
ownerSerial: { type: 'string', nullable: true, example: '0x1A2B', description: 'Omitted when the market `ownerSerial` field is gated above the caller.' },
ownerName: { type: 'string', nullable: true, example: 'Darrow', description: 'Omitted when the market `ownerName` field is gated above the caller.' },
location: { $ref: '#/components/schemas/UoShardMarketLocation' },
updatedAt: { type: 'string', format: 'date-time', description: 'When the shard last published this shop.' },
},
},
},
},
UoShardMarketPage: {
type: 'object',
description: 'A page of marketplace listings plus the unpaginated total and the staleness stamp.',
properties: {
listings: { type: 'array', items: { $ref: '#/components/schemas/UoShardMarketListing' } },
total: { type: 'integer', example: 1284, description: 'Matching listings, ignoring paging.' },
limit: { type: 'integer', example: 50 },
offset: { type: 'integer', example: 0 },
vendors: { type: 'integer', example: 137, description: 'Vendors in the whole index.' },
staleAt: {
type: 'string',
format: 'date-time',
nullable: true,
description: 'The OLDEST vendor row. The shard sweeps vendors round-robin, so the index can be a full cycle behind and a client must say so rather than implying live prices.',
},
},
},
UoShardMarketVendor: {
type: 'object',
description: 'One player vendor and its listings.',
properties: {
serial: { type: 'string', example: '0x40001234' },
shopName: { type: 'string', nullable: true, example: "Darrow's Bargains" },
ownerSerial: { type: 'string', nullable: true },
ownerName: { type: 'string', nullable: true, example: 'Darrow' },
location: { $ref: '#/components/schemas/UoShardMarketLocation' },
count: { type: 'integer', example: 250, description: 'Listings the shard published for this shop.' },
total: { type: 'integer', example: 3104, description: 'Listings the shop actually holds.' },
truncated: { type: 'boolean', example: true, description: '`total` exceeds `count` — the shop holds more than the shard publishes per frame.' },
updatedAt: { type: 'string', format: 'date-time' },
items: { type: 'array', items: { $ref: '#/components/schemas/UoShardMarketListing' } },
},
},
UoShardMarketMeta: {
type: 'object',
description: 'Marketplace size, staleness and the filter options a client needs to build its UI.',
properties: {
vendors: { type: 'integer', example: 137 },
items: { type: 'integer', example: 18422 },
staleAt: { type: 'string', format: 'date-time', nullable: true },
freshAt: { type: 'string', format: 'date-time', nullable: true },
maps: { type: 'array', items: { type: 'string' }, example: ['Felucca', 'Trammel'], description: "Facets that actually hold vendors. From the shard's own data — never a hardcoded list." },
regions: { type: 'array', items: { type: 'string' }, example: ['Britain', 'Luna'] },
},
},
UoShardFeatures: {
type: 'object',
description:
"The shard features the caller may reach, plus the audience rung they resolved to. Drives client nav so it never renders a link that would 403.",
properties: {
level: {
type: 'string',
enum: ['anonymous', 'logged_in', 'player', 'staff', 'admin'],
example: 'anonymous',
},
features: {
type: 'array',
items: { type: 'string' },
example: ['status', 'activity', 'champs', 'guilds', 'governors', 'houses', 'presence'],
},
},
},
UoShardFeatureVisibility: {
type: 'object',
description: 'Visibility settings for one shard feature.',
properties: {
enabled: { type: 'boolean', example: true },
audience: {
type: 'string',
enum: ['anonymous', 'logged_in', 'player', 'staff', 'admin'],
description: 'Minimum rung that may reach this feature. Each rung implies the ones below it.',
example: 'anonymous',
},
stream: {
type: 'boolean',
description: "Whether this feature's event kinds fan out over SSE at all.",
example: true,
},
fieldRules: {
type: 'object',
additionalProperties: { type: 'string' },
description:
'Per-field rung overrides for the sensitive fields this feature exposes. acct / webId are admin-only always and are rejected here.',
example: { location: 'staff' },
},
},
},
UoShardVisibilityConfig: {
type: 'object',
properties: {
ladder: {
type: 'array',
items: { type: 'string' },
example: ['anonymous', 'logged_in', 'player', 'staff', 'admin'],
},
lockedFields: { type: 'array', items: { type: 'string' }, example: ['acct', 'webId'] },
defaults: {
type: 'object',
additionalProperties: { $ref: '#/components/schemas/UoShardFeatureVisibility' },
},
features: {
type: 'object',
additionalProperties: { $ref: '#/components/schemas/UoShardFeatureVisibility' },
},
},
},
UoShardVisibilityUpdate: {
type: 'object',
required: ['features'],
properties: {
features: {
type: 'object',
additionalProperties: { $ref: '#/components/schemas/UoShardFeatureVisibility' },
example: { market: { enabled: true, audience: 'player', stream: false, fieldRules: { ownerName: 'player' } } },
},
},
},
// ── Spawn atlas (Protocol 3.0 Part C) ────────────────────────────────
// Static shard content, parsed from the shard's own ServUO tree. Nothing
// here comes from the sidecar, so it stays populated while the shard is
// down. Facet names are whatever the shard's files declare — the examples
// below are stock ServUO, not a fixed list.
UoAtlasCreature: {
type: 'object',
description: 'A creature in the bestiary. `places`/`points`/`alsoHere` are present only on the single-creature route.',
properties: {
slug: { type: 'string', example: 'lizardman' },
name: { type: 'string', example: 'Lizardman' },
total: { type: 'integer', description: 'How many can be alive at once, summed across every spawner.', example: 214 },
points: { type: 'integer', description: 'How many spawners mention this creature.', example: 62 },
facets: {
type: 'object',
additionalProperties: { type: 'integer' },
description: "This creature's share per facet.",
example: { Felucca: 96, Trammel: 88, Tokuno: 30 },
},
art: { type: 'string', nullable: true, description: 'Operator-supplied art under uploads/atlas/. NULL on a fresh import — the repo ships no creature art.' },
places: {
type: 'array',
description: 'Where it spawns, aggregated by resolved place. The answer the atlas exists to give.',
items: {
type: 'object',
properties: {
facet: { type: 'string', example: 'Trammel' },
label: { type: 'string', description: 'Resolved region, else nearest landmark group, else "Wilderness".', example: 'Shrines' },
spawners: { type: 'integer', example: 7 },
maxAlive: { type: 'integer', example: 21 },
},
},
},
spawners: {
type: 'array',
description: 'The individual spawners. Named separately from `points` (the count) so one key never means two things.',
items: { $ref: '#/components/schemas/UoAtlasSpawner' },
},
spawnersTruncated: { type: 'boolean', description: 'True when the spawner list was cut at the requested bound.', example: false },
alsoHere: {
type: 'array',
description: 'Creatures sharing a spawner with this one.',
items: {
type: 'object',
properties: {
slug: { type: 'string', example: 'lizardman-warrior' },
name: { type: 'string', example: 'Lizardman Warrior' },
shared: { type: 'integer', example: 12 },
},
},
},
},
},
UoAtlasSpawner: {
type: 'object',
description: 'One ServUO spawner, with the place its coordinates resolved to.',
properties: {
id: { type: 'integer' },
facet: { type: 'string', example: 'Felucca' },
name: { type: 'string', nullable: true, description: "The spawner's own name in the ServUO file." },
x: { type: 'integer', example: 5411 },
y: { type: 'integer', example: 1234 },
width: { type: 'integer' },
height: { type: 'integer' },
range: { type: 'integer', description: 'Spawn radius.' },
maxCount: { type: 'integer', description: 'How many of THIS creature this spawner keeps alive.', example: 3 },
minDelay: { type: 'integer', description: 'Respawn window, in SECONDS. Normalised at parse time — the source stores minutes or seconds per record, decided by its own DelayInSec flag.', example: 300 },
maxDelay: { type: 'integer', example: 600 },
todStart: { type: 'integer', description: 'Meaningless unless todMode is non-zero.' },
todEnd: { type: 'integer' },
todMode: { type: 'integer' },
region: { type: 'string', nullable: true, example: 'Despise' },
landmark: { type: 'string', nullable: true, example: 'Covetous' },
label: { type: 'string', description: 'Region, else landmark group, else "Wilderness".', example: 'Despise' },
},
},
UoAtlasCreaturePage: {
type: 'object',
properties: {
total: { type: 'integer', description: 'Matching creatures before pagination.', example: 800 },
limit: { type: 'integer', example: 50 },
offset: { type: 'integer', example: 0 },
creatures: { type: 'array', items: { $ref: '#/components/schemas/UoAtlasCreature' } },
},
},
UoAtlasRegion: {
type: 'object',
description: 'A named region, flattened out of the shard\'s nested Regions.xml.',
properties: {
facet: { type: 'string', example: 'Felucca' },
name: { type: 'string', example: 'Despise' },
type: { type: 'string', nullable: true, description: 'ServUO region class.', example: 'DungeonRegion' },
priority: { type: 'integer', example: 50 },
parent: { type: 'string', nullable: true, example: 'Britain' },
rects: {
type: 'array',
description: 'The rectangles that placed each spawn point.',
items: { type: 'object', additionalProperties: true },
},
},
},
UoAtlasLandmark: {
type: 'object',
properties: {
facet: { type: 'string', example: 'Trammel' },
name: { type: 'string', example: 'Level 1' },
group: { type: 'string', nullable: true, description: 'Innermost enclosing parent — the label worth showing.', example: 'Covetous' },
x: { type: 'integer', example: 5411 },
y: { type: 'integer', example: 1234 },
z: { type: 'integer', example: 0 },
},
},
UoAtlasChampion: {
type: 'object',
description: 'A CONFIGURED champion altar. Not the live board — see GET /public/shard/champs for that.',
properties: {
slug: { type: 'string', example: 'felucca-deceit' },
name: { type: 'string', example: 'Deceit' },
group: { type: 'string', nullable: true, description: 'Spawn group; one altar active per group.', example: 'Dungeons' },
type: { type: 'string', nullable: true, description: 'NULL when the champion is drawn at activation.', example: 'UnholyTerror' },
randomType: { type: 'boolean', example: false },
facet: { type: 'string', example: 'Felucca' },
x: { type: 'integer' },
y: { type: 'integer' },
z: { type: 'integer' },
radius: { type: 'integer', example: 60 },
label: { type: 'string', nullable: true, example: 'Deceit' },
},
},
UoAtlasMeta: {
type: 'object',
description: 'What atlas is loaded. Game-world facts only: the ServUO path, source hashes and any pending refresh are operator detail and live on the admin status route.',
properties: {
importedAt: { type: 'string', format: 'date-time', nullable: true },
generatedAt: { type: 'string', format: 'date-time', nullable: true },
counts: {
type: 'object',
nullable: true,
additionalProperties: true,
example: { facets: 6, points: 6455, creatures: 800, regions: 387, landmarks: 558, champions: 25, unresolvedPoints: 1086 },
},
facets: { type: 'array', items: { type: 'string' }, example: ['Felucca', 'Ilshenar', 'Malas', 'TerMur', 'Tokuno', 'Trammel'] },
},
},
UoAtlasStatus: {
type: 'object',
description: 'Admin view of atlas state: where the tree is, whether it is readable, whether it has drifted from what is loaded, and any refresh staged for review.',
properties: {
configured: { type: 'boolean', example: true },
path: { type: 'string', example: '/srv/servuo' },
treeReadable: { type: 'boolean', example: true },
drift: { type: 'boolean', nullable: true, description: 'True when the tree\'s source hashes differ from the loaded atlas. NULL when the tree could not be read.', example: false },
facets: { type: 'array', items: { type: 'string' } },
importedAt: { type: 'string', format: 'date-time', nullable: true },
counts: { type: 'object', nullable: true, additionalProperties: true },
pending: {
type: 'object',
nullable: true,
description: 'A refresh that was parsed but NOT applied because it would remove a facet. `status` is pending or rejected.',
additionalProperties: true,
},
},
},
UoAtlasRefreshResult: {
type: 'object',
description: 'Outcome of a refresh. Reported rather than thrown, so an unreadable tree is an answer and not a 500.',
properties: {
status: {
type: 'string',
enum: ['skipped', 'unavailable', 'unchanged', 'imported', 'needsReview', 'failed', 'rejected', 'none'],
example: 'imported',
},
reason: { type: 'string', nullable: true },
path: { type: 'string', nullable: true },
counts: { type: 'object', nullable: true, additionalProperties: true },
addedFacets: { type: 'array', items: { type: 'string' } },
removedFacets: { type: 'array', items: { type: 'string' } },
},
},
UoClilocStatus: {
type: 'object',
description:
'Admin view of cliloc state: where the converted file is, whether it is readable, how many entries are loaded, and whether the file has drifted from them. `configured: false` is a supported state — item names then render as ids.',
properties: {
configured: { type: 'boolean', example: true },
path: { type: 'string', example: '/srv/uo-client' },
file: { type: 'string', nullable: true, description: 'The file actually resolved, when the path is a directory.', example: '/srv/uo-client/clilocs.tsv' },
fileReadable: { type: 'boolean', example: true },
problem: { type: 'string', nullable: true, description: 'Why the file cannot be used, when it cannot. Set (with code COMPRESSED) for a readable-but-unconverted client file.', example: null },
code: { type: 'string', nullable: true, description: 'Machine-readable cause of `problem`.', enum: ['NO_PATH', 'NOT_FOUND', 'NO_FILE', 'UNREADABLE', 'COMPRESSED'] },
drift: { type: 'boolean', nullable: true, description: 'True when any source hash differs from the loaded table. NULL when the sources could not be read or are not usable.', example: false },
count: { type: 'integer', description: 'Entries currently loaded.', example: 67496 },
sources: {
type: 'array',
items: { type: 'string' },
description: 'Every source found now, root-relative, base first then overlays in merge order.',
example: ['clilocs.plain', 'custom/uomysticmoon.tsv'],
},
loadedSources: {
type: 'array',
nullable: true,
description: 'What each source contributed at the last import.',
items: {
type: 'object',
properties: {
label: { type: 'string', example: 'custom/uomysticmoon.tsv' },
kind: { type: 'string', enum: ['base', 'custom'], example: 'custom' },
entries: { type: 'integer', example: 37 },
added: { type: 'integer', description: 'Ids this source introduced.', example: 25 },
overrode: { type: 'integer', description: 'Ids it replaced from an earlier source.', example: 12 },
},
},
},
missingSources: {
type: 'array',
items: { type: 'string' },
description: 'Sources loaded previously and now absent. An import refuses these without `approve`.',
example: [],
},
importedAt: { type: 'string', format: 'date-time', nullable: true },
sourceBytes: { type: 'integer', nullable: true, example: 4973525 },
},
},
UoClilocRefreshResult: {
type: 'object',
description:
'Outcome of a cliloc refresh. Reported rather than thrown, so a missing or compressed file is an answer and not a 500.',
properties: {
status: {
type: 'string',
enum: ['skipped', 'unavailable', 'unchanged', 'imported', 'needsReview', 'failed'],
description: '`needsReview` means a previously-loaded source has vanished and nothing was applied; re-run with `approve` to accept it.',
example: 'imported',
},
reason: { type: 'string', nullable: true },
code: {
type: 'string',
nullable: true,
description: 'Machine-readable cause. `COMPRESSED` means the client\'s own Cliloc.enu was supplied instead of a converted one.',
enum: ['NO_PATH', 'NOT_FOUND', 'NO_FILE', 'UNREADABLE', 'COMPRESSED', 'TRUNCATED', 'EMPTY', 'NOT_BUFFER'],
},
path: { type: 'string', nullable: true },
file: { type: 'string', nullable: true },
count: { type: 'integer', nullable: true, description: 'Entries stored (blank strings are dropped).', example: 67496 },
parsed: { type: 'integer', nullable: true, description: 'Entries read across every source before blanks were dropped.', example: 123527 },
blank: { type: 'integer', nullable: true, example: 55994 },
sources: {
type: 'array',
nullable: true,
description: 'Per-source breakdown: what each file contributed and how much of it overrode an earlier source.',
items: {
type: 'object',
properties: {
label: { type: 'string' },
kind: { type: 'string', enum: ['base', 'custom'] },
entries: { type: 'integer' },
added: { type: 'integer' },
overrode: { type: 'integer' },
},
},
},
missingSources: {
type: 'array',
nullable: true,
items: { type: 'string' },
description: 'On `needsReview`: the sources that vanished. Nothing was applied.',
},
acceptedMissing: {
type: 'array',
nullable: true,
items: { type: 'string' },
description: 'On `imported` with `approve`: the vanished sources the admin accepted.',
},
},
},
UoShardLinkRequest: {
type: 'object',
required: ['code'],
properties: {
code: { type: 'string', description: 'The one-time code shown by [link in game.', example: 'AB12CD' },
},
},
UoShardLinkResult: {
type: 'object',
properties: {
linked: { type: 'boolean', example: true },
account: { type: 'string', example: 'whitlocktech' },
},
},
UoShardLink: {
type: 'object',
description: 'A linked in-game account (GET /player/shard/accounts).',
properties: {
account: { type: 'string', example: 'whitlocktech' },
userId: { type: 'integer', example: 42 },
charName: { type: 'string', nullable: true, example: 'Darrow' },
linkedAt: { type: 'string', format: 'date-time' },
},
},
UoTownCrierRequest: {
type: 'object',
required: ['id', 'lines'],
properties: {
id: { type: 'string', maxLength: 64, description: 'Re-posting the same id replaces the prior entry.', example: 'news-42' },
lines: { type: 'array', items: { type: 'string', maxLength: 200 }, example: ['Hear ye!', 'Market tax is now 5%.'] },
durationSec: { type: 'integer', minimum: 1, maximum: 86400, example: 3600 },
},
},
},
},
}

View File

@@ -95,6 +95,8 @@ function fakeApi() {
extensions: [],
streams: null,
legs: [],
teamProvider: null,
slashCommands: [],
hooks: {},
}
const called = new Set()
@@ -107,6 +109,14 @@ function fakeApi() {
registerExtension(slot, router) { record.extensions.push({ slot, router }) },
registerNotificationStreams(streams) { once('registerNotificationStreams'); record.streams = streams },
registerAnnounceLeg(leg) { record.legs.push(leg) },
// MODULE_API 1.6.0. `once` because core holds a single provider per
// deployment — a second registration is a collision there, so it has to be
// one here too, or this suite would pass a shape core rejects at load.
registerTeamProvider(provider) { once('registerTeamProvider'); record.teamProvider = provider },
// MODULE_API 1.6.0, live since phase 7. `once` for the same reason core
// takes it: a second call is a module changing its mind halfway through
// register(), which core rejects.
registerSlashCommands(commands) { once('registerSlashCommands'); record.slashCommands = commands },
onBoot(fn) { once('onBoot'); record.hooks.onBoot = fn },
onShutdown(fn) { once('onShutdown'); record.hooks.onShutdown = fn },
}

View File

@@ -85,6 +85,35 @@ test('every registered stream is namespaced or grandfathered', () => {
}
})
test('registers a Team provider with all three methods', () => {
// Core requires all three: a provider that could list Teams but not their
// members would leave core holding Teams it can never populate, which is not
// the same as a call that fails. Asserted here so a refactor that drops one
// fails in this suite rather than at load on an operator's install.
const api = fakeApi()
register(fakeCtx(), api)
const provider = api.record.teamProvider
assert.ok(provider, 'a UO guild is a Team; something has to answer for them')
for (const method of ['getTeams', 'getTeamMembers', 'getTeamLeaders']) {
assert.strictEqual(typeof provider[method], 'function', `${method} is missing`)
}
})
test('registration does not call the provider, or touch the database', async () => {
// register() runs while core's app.js is still being required, with the pool
// pointed at a dead port — routeManifest.js and swagger.js both depend on that.
// Registration is a CLAIM; core does not ask anything until it reconciles,
// which is after onBoot.
const ctx = fakeCtx()
let queried = false
const frozen = Object.freeze({ ...ctx, db: Object.freeze({ query: async () => { queried = true; return [] } }) })
const api = fakeApi()
register(frozen, api)
assert.equal(queried, false, 'a query at registration time would hang the manifest and the spec build')
})
test('takes a frozen ctx and does not try to write to it', () => {
const ctx = fakeCtx()
assert.ok(Object.isFrozen(ctx))

View File

@@ -0,0 +1,170 @@
// The frozen manifest's derivation, checked.
//
// `scripts/frozenManifest.js` runs in one place — a CI job with a whole core
// checked out beside it — so it is the least-exercised piece of machinery in this
// repo, and it is the piece that decides whether the URLs this module claims are
// the URLs it serves (MODULE_API.md §5.3). Its three answers are pure functions of
// two manifests and a fragment, so all three are asked here, with fixtures rather
// than a clone.
//
// What is deliberately NOT asserted here: the numbers. `routes.manifest.json`'s
// 72 routes are proved by the job that generates them from a real core, and a
// copy of that count in this file would only ever be a second thing to update.
const test = require('node:test')
const assert = require('node:assert')
const fs = require('node:fs')
const path = require('node:path')
const { diffManifests, coverage, MANIFEST, FRAGMENT } = require('../scripts/frozenManifest')
const manifest = (public_ = [], internal = []) => ({ public: public_, internal })
const get = (p) => ({ method: 'GET', path: p })
test('the module\'s routes are the ones a core gains by loading it', () => {
const before = manifest([get('/api/v1/public/settings')])
const after = manifest([get('/api/v1/public/settings'), get('/api/v1/public/shard/status')])
const { added, removed } = diffManifests(before, after)
assert.deepStrictEqual(removed, [])
assert.deepStrictEqual(added, [{ method: 'GET', path: '/api/v1/public/shard/status', tier: 'public' }])
})
test('a route core loses to the module is reported, not quietly absorbed', () => {
// The failure this exists for: a module whose mount displaces a core route.
// It cannot show up as an addition — the URL is unchanged — so a check that
// only looked at what appeared would call this clean.
const before = manifest([get('/api/v1/public/settings'), get('/api/v1/public/status')])
const after = manifest([get('/api/v1/public/settings')])
const { removed } = diffManifests(before, after)
assert.deepStrictEqual(removed, ['public GET /api/v1/public/status'])
})
test('a route whose METHOD changed counts as removed and added', () => {
const { added, removed } = diffManifests(
manifest([{ method: 'POST', path: '/api/v1/admin/thing' }]),
manifest([{ method: 'PUT', path: '/api/v1/admin/thing' }]),
)
assert.deepStrictEqual(removed, ['public POST /api/v1/admin/thing'])
assert.strictEqual(added.length, 1)
})
test('the internal app is diffed too, and keeps its own tier', () => {
const { added } = diffManifests(
manifest([], [get('/internal/health')]),
manifest([], [get('/internal/health'), get('/internal/uo/thing')]),
)
assert.deepStrictEqual(added, [{ method: 'GET', path: '/internal/uo/thing', tier: 'internal' }])
})
test('added routes are sorted, so the committed file does not churn on traversal order', () => {
const { added } = diffManifests(
manifest([]),
manifest([get('/b'), get('/a'), { method: 'POST', path: '/a' }]),
)
assert.deepStrictEqual(added.map((r) => `${r.method} ${r.path}`), ['GET /a', 'GET /b', 'POST /a'])
})
// ── coverage: the route ⇄ fragment agreement ────────────────────────────────
const fragment = (paths) => ({ paths })
test('a served route with no documented operation is named', () => {
const { undocumented, unserved } = coverage(
[get('/api/v1/public/shard/status')],
fragment({}),
)
assert.deepStrictEqual(undocumented, ['GET /api/v1/public/shard/status'])
assert.deepStrictEqual(unserved, [])
})
test('a documented operation nobody serves is named too', () => {
// The direction core's own spec has no check for, which is how it accumulated
// four orphan tags and thirty-three orphan schemas describing routes that had
// moved to this repo. A documented URL nobody serves is a client following the
// docs into a 404.
const { undocumented, unserved } = coverage(
[],
fragment({ '/api/v1/public/shard/gone': { get: {} } }),
)
assert.deepStrictEqual(undocumented, [])
assert.deepStrictEqual(unserved, ['GET /api/v1/public/shard/gone'])
})
test('express :params and OpenAPI {params} are the same route', () => {
const { undocumented, unserved } = coverage(
[{ method: 'DELETE', path: '/api/v1/admin/users/:id/shard/link/:account' }],
fragment({ '/api/v1/admin/users/{id}/shard/link/{account}': { delete: {} } }),
)
assert.deepStrictEqual(undocumented, [])
assert.deepStrictEqual(unserved, [])
})
test('methods are matched, not just paths', () => {
const { undocumented, unserved } = coverage(
[{ method: 'POST', path: '/api/v1/admin/shard/kick' }],
fragment({ '/api/v1/admin/shard/kick': { get: {} } }),
)
assert.deepStrictEqual(undocumented, ['POST /api/v1/admin/shard/kick'])
assert.deepStrictEqual(unserved, ['GET /api/v1/admin/shard/kick'])
})
// ── the committed artifacts, against each other ─────────────────────────────
//
// These two files are generated together by a job that has a real core; here
// there is no core, so what can still be asked is whether they agree with each
// other. If they do not, one of them was committed without the other.
test('every route in the committed manifest has a committed operation', () => {
const routes = JSON.parse(fs.readFileSync(MANIFEST, 'utf8')).routes
const spec = JSON.parse(fs.readFileSync(FRAGMENT, 'utf8'))
const { undocumented, unserved } = coverage(routes, spec)
assert.deepStrictEqual(undocumented, [], 'routes.manifest.json lists routes swagger-fragment.json does not document')
assert.deepStrictEqual(unserved, [], 'swagger-fragment.json documents operations routes.manifest.json does not list')
})
test('the fragment carries only the three sections §6.1a allows', () => {
const spec = JSON.parse(fs.readFileSync(FRAGMENT, 'utf8'))
assert.deepStrictEqual(Object.keys(spec).sort(), ['components', 'paths', 'tags'])
assert.deepStrictEqual(Object.keys(spec.components), ['schemas'])
})
test('the fragment defines only namespaced schemas, and redefines none of core\'s', () => {
const spec = JSON.parse(fs.readFileSync(FRAGMENT, 'utf8'))
for (const name of Object.keys(spec.components.schemas)) {
assert.match(name, /^Uo[A-Z]/, `${name} is not namespaced — core wins the collision and drops it (§6.1a)`)
}
// Core's shared schemas are REFERENCED by their core names and not redefined;
// they resolve in the merged document, which is the whole point of a fragment.
const refs = JSON.stringify(spec.paths).match(/#\/components\/schemas\/([A-Za-z0-9_]+)/g) || []
const core = [...new Set(refs.map((r) => r.split('/').pop()))].filter((n) => !n.startsWith('Uo'))
assert.deepStrictEqual(core.sort(), ['Error', 'ValidationError'])
})
test('every path in the fragment is fully qualified', () => {
const spec = JSON.parse(fs.readFileSync(FRAGMENT, 'utf8'))
for (const p of Object.keys(spec.paths)) {
// §6.1a: core merges the fragment verbatim and never re-derives a prefix, so
// a router-relative path here is a path nothing serves.
assert.match(p, /^\/api\/v1\/(public|admin|player)\//, `${p} is not a fully-qualified URL`)
assert.doesNotMatch(p, /\/$/, `${p} has a trailing slash — no client calls that URL`)
}
})
test('the manifest and the module\'s declared mounts agree', () => {
const routes = JSON.parse(fs.readFileSync(MANIFEST, 'utf8')).routes
const { mounts } = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'module.json'), 'utf8'))
const declared = []
for (const [tier, prefixes] of Object.entries(mounts)) {
for (const prefix of prefixes) declared.push(`/api/v1/${tier}${prefix}/`)
}
// The extension slot is core's resource, not one of our mounts (§2.4).
const slot = '/api/v1/admin/users/'
for (const route of routes) {
const under = declared.some((d) => route.path.startsWith(d)) || route.path.startsWith(slot)
assert.ok(under, `${route.method} ${route.path} is served from outside every mount module.json declares`)
}
})

View File

@@ -0,0 +1,148 @@
// `/guild` — the chat command registered through `api.registerSlashCommands`
// (TEAMS.md §7.1, MODULE_API 1.6.0).
//
// The properties worth pinning are all about the ANSWER being the same answer
// the website gives, because that is the whole risk of a second surface: the
// audience rungs are re-resolved here rather than assumed, the shard's own
// offline guard is honoured, and the link prompt appears only when linking would
// actually change what the caller is told.
const { test, afterEach } = require('node:test')
const assert = require('node:assert/strict')
const command = require('../commands/guild.command')
const db = require('../model/teamProvider/teamProvider.db')
const provider = require('../model/teamProvider/teamProvider.model')
const visibility = require('../utils/shardVisibility')
const originals = {
getConfig: visibility.getConfig,
viewerLevel: visibility.viewerLevel,
boardIsCurrent: provider.boardIsCurrent,
listGuilds: db.listGuilds,
listGuildMembers: db.listGuildMembers,
}
afterEach(() => {
visibility.getConfig = originals.getConfig
visibility.viewerLevel = originals.viewerLevel
provider.boardIsCurrent = originals.boardIsCurrent
db.listGuilds = originals.listGuilds
db.listGuildMembers = originals.listGuildMembers
})
const GUILDS = [
{ id: 7, name: 'Knights of the Codex', abbr: 'KOC', alliance: 'The Accord', members: 12, online: 3, leader_name: 'Dain' },
{ id: 9, name: 'Knights Hospitaller', abbr: 'KH', alliance: null, members: 4, online: 0, leader_name: null },
]
const MEMBERS = [
{ serial: 1, name: 'Dain', rank: 4, web_id: '31', linked_user_id: null },
{ serial: 2, name: 'Elowen', rank: 4, web_id: null, linked_user_id: 44 },
{ serial: 3, name: 'Wat', rank: 2, web_id: null, linked_user_id: null },
]
function stub({ audience = 'anonymous', enabled = true, level = 'anonymous', current = true } = {}) {
visibility.getConfig = async () => ({ guilds: { enabled, audience } })
visibility.viewerLevel = async () => level
provider.boardIsCurrent = async () => (current ? { ok: true } : { ok: false, reason: 'socket down' })
db.listGuilds = async () => GUILDS
db.listGuildMembers = async () => MEMBERS
}
const anonymous = { platform: 'discord', platformUserId: '1', userId: null, role: null, isLinked: false, isStaff: false }
const linked = { platform: 'discord', platformUserId: '2', userId: 31, role: 'player', isLinked: true, isStaff: false }
test('the definition stays inside the option schema §7.1.1 allows', () => {
assert.equal(command.name, 'guild')
assert.equal(command.access, 'everyone')
for (const option of command.options) {
assert.ok(['string', 'integer', 'boolean', 'user'].includes(option.type))
assert.ok(option.description.length <= 100)
}
})
test('the guilds feature being off withholds everything, staff included', async () => {
stub({ enabled: false, level: 'admin' })
const res = await command.handler({ options: {}, actor: { ...linked, role: 'admin', isStaff: true } })
assert.match(res.text, /does not publish guild information/)
assert.equal(res.ephemeral, true)
})
// The reason this command is not a thin wrapper over a public route: a rung
// below the feature's audience must be refused HERE, or a shard that gates
// guilds to staff would publish them to a Discord channel.
test('a caller below the feature audience is refused', async () => {
stub({ audience: 'staff', level: 'anonymous' })
const res = await command.handler({ options: {}, actor: anonymous })
assert.match(res.text, /not shown to your account/)
assert.equal(res.ephemeral, true)
})
test('an unlinked caller is invited to link — but only when linking would change the answer', async () => {
stub({ audience: 'player', level: 'anonymous' })
const gated = await command.handler({ options: {}, actor: anonymous })
assert.match(gated.notice, /Link your account/)
// Public guilds: there is nothing more to see, so there is nothing to prompt.
stub({ audience: 'anonymous', level: 'anonymous' })
const open = await command.handler({ options: {}, actor: anonymous })
assert.equal(open.notice, null)
// Gated to staff: linking reaches `player` and stops there, so the invitation
// would be an instruction to do something that changes nothing. Found on the
// live rig, where a staff-gated shard still offered it.
stub({ audience: 'staff', level: 'anonymous' })
const unreachable = await command.handler({ options: {}, actor: anonymous })
assert.match(unreachable.text, /not shown to your account/)
assert.equal(unreachable.notice, null)
})
test('a stale board answers offline rather than reporting what it still holds', async () => {
stub({ current: false })
const res = await command.handler({ options: {}, actor: anonymous })
assert.match(res.text, /not connected right now/)
})
test('no argument lists the largest guilds', async () => {
stub()
const res = await command.handler({ options: {}, actor: anonymous })
assert.equal(res.title, 'Guilds on this shard')
assert.equal(res.fields.length, 2)
assert.match(res.fields[0].name, /Knights of the Codex/)
assert.match(res.fields[0].value, /12 members · 3 online/)
})
test('a name resolves by abbreviation, then exactly, then by unique prefix', async () => {
stub()
const byAbbr = await command.handler({ options: { name: 'koc' }, actor: anonymous })
assert.match(byAbbr.title, /Knights of the Codex/)
const exact = await command.handler({ options: { name: 'Knights Hospitaller' }, actor: anonymous })
assert.match(exact.title, /Hospitaller/)
// "knights" hits both, and answering with either would be worse than asking.
const ambiguous = await command.handler({ options: { name: 'knights' }, actor: anonymous })
assert.match(ambiguous.text, /Several guilds match/)
assert.equal(ambiguous.ephemeral, true)
})
test('a miss is an answer, not a failure', async () => {
stub()
const res = await command.handler({ options: { name: 'nobody' }, actor: anonymous })
assert.match(res.text, /No guild matches/)
})
// `linked` counts BOTH sources the roster uses — the shard's asserted web id and
// the link table — because that is what "linked" means everywhere else here.
test('the detail carries the counts, the leaders and a link to the module page', async () => {
stub({ level: 'player' })
const res = await command.handler({ options: { name: 'KOC' }, actor: linked })
const field = (name) => res.fields.find((f) => f.name === name).value
assert.equal(field('Members'), '12')
assert.equal(field('Online'), '3')
assert.equal(field('Linked accounts'), '2')
assert.equal(field('Leaders'), 'Dain, Elowen')
assert.match(res.url, /\/uo\/guilds\/7$/)
assert.equal(res.notice, null)
})

View File

@@ -0,0 +1,157 @@
// `schema.sql` is replayed by core on EVERY boot, and core validates it before
// anything mounts. The rules are core's (MODULE_API.md §2.6, loader.js), and are
// restated here for the same reason `manifest.test.js` restates the manifest
// rules: a mistake should fail in this repo's CI, which can say what is wrong,
// rather than on an install, where the symptom is a module that is simply absent.
//
// The test this file exists for is the ORDER one. Two statements that read each
// other were adjacent in core's schema.sql until slice 1 moved one of them here
// and left the other behind — and because core's schema is replayed in full
// before any module fragment, the marker was written before the migration that
// reads it and the one-shot could never fire. Nothing caught it: both files were
// individually valid SQL, both replayed cleanly, and the failure only shows on an
// upgraded install talking to a real sidecar. An assertion about order is the
// only thing that would have.
const test = require('node:test')
const assert = require('node:assert')
const fs = require('node:fs')
const path = require('node:path')
const SCHEMA = path.join(__dirname, '..', 'db', 'schema.sql')
const sql = fs.readFileSync(SCHEMA, 'utf8')
/**
* Split into statements the way core's `utils/sqlStatements.js` does: a
* character walk, not a regexp.
*
* Comments are stripped before quotes are considered, because a comment may
* contain quotes — line 508 of this very file is `-- '' when randomised per
* activation`, and a stripper that opened a string there would swallow the rest
* of the file. The reverse case (a `--` inside a string literal) is handled by
* the same walk, since a quote opened outside a comment stays open.
*/
function splitStatements(text) {
const out = []
let buf = ''
let quote = null
for (let i = 0; i < text.length; i++) {
const c = text[i]
if (quote) {
buf += c
if (c === '\\') {
buf += text[++i] ?? ''
} else if (c === quote) {
quote = null
}
continue
}
if (c === '-' && text[i + 1] === '-') {
while (i < text.length && text[i] !== '\n') i++
buf += '\n'
continue
}
if (c === "'" || c === '"' || c === '`') {
quote = c
buf += c
continue
}
if (c === ';') {
if (buf.trim()) out.push(buf.trim())
buf = ''
continue
}
buf += c
}
if (buf.trim()) out.push(buf.trim())
return out
}
const statements = splitStatements(sql)
// Core's leading-verb allowlist. Not a DROP denylist: this file replays on every
// boot, so a TRUNCATE or DELETE would empty a table at each restart.
const ALLOWED = ['CREATE', 'ALTER', 'INSERT', 'UPDATE']
test('the splitter survives a comment that contains quotes', () => {
const parts = splitStatements("SELECT 1; -- '' a quote in a comment\nSELECT 2;")
assert.deepEqual(
parts.map((s) => s.trim().split('\n')[0].trim()),
['SELECT 1', 'SELECT 2'],
)
})
test('the splitter does not treat a -- inside a string as a comment', () => {
const parts = splitStatements("INSERT INTO t VALUES ('a--b');")
assert.equal(parts.length, 1)
assert.match(parts[0], /'a--b'/)
})
test('every statement leads with a verb core allows', () => {
for (const statement of statements) {
const verb = statement.trim().split(/\s+/)[0].toUpperCase()
assert.ok(ALLOWED.includes(verb), `statement leads with "${verb}": ${statement.slice(0, 70)}`)
}
})
test('every CREATE TABLE is IF NOT EXISTS', () => {
for (const statement of statements) {
if (!/^CREATE\s+TABLE/i.test(statement)) continue
assert.match(statement, /^CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS/i, statement.slice(0, 70))
}
})
test('every table this fragment declares is prefixed shard_ or uo_link_', () => {
// The two prefixes core grandfathers to this module by name
// (loader.js LEGACY_TABLE_PREFIXES). A module written after this one prefixes
// with its own id instead.
const CREATE_TABLE = /CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+`?([A-Za-z0-9_]+)`?/gi
const tables = []
for (const statement of statements) {
for (const m of statement.matchAll(CREATE_TABLE)) tables.push(m[1].toLowerCase())
}
assert.ok(tables.length > 20, `expected the module's tables, found ${tables.length}`)
for (const table of tables) {
assert.ok(
table.startsWith('shard_') || table.startsWith('uo_link_'),
`table "${table}" carries neither grandfathered prefix`,
)
}
})
// ── The settings rows this module owns ──────────────────────────────────────
const SETTINGS_KEYS = ['game_account_signup', 'uo_link_protocol_3_migrated']
test('both settings seeds are INSERT IGNORE, so a replay never resets a value', () => {
for (const key of SETTINGS_KEYS) {
const seed = statements.find((s) => /^INSERT/i.test(s) && s.includes(`'${key}'`))
assert.ok(seed, `no seed for "${key}"`)
assert.match(seed, /^INSERT\s+IGNORE\s+INTO\s+settings/i, key)
}
})
test('the protocol-3 marker is written AFTER the update that reads it', () => {
const update = statements.findIndex(
(s) => /^UPDATE\s+uo_link_config/i.test(s) && s.includes('uo_link_protocol_3_migrated'),
)
const marker = statements.findIndex(
(s) => /^INSERT/i.test(s) && s.includes("'uo_link_protocol_3_migrated'"),
)
assert.ok(update >= 0, 'the protocol-3 migration is gone')
assert.ok(marker >= 0, 'the one-shot marker is gone')
assert.ok(
marker > update,
'the marker is written before the UPDATE reads it — the one-shot can never fire. ' +
'This is the shape of the defect slice 1 introduced by leaving the marker in core, ' +
'whose schema replays first.',
)
})
test('the migration is guarded on the marker, not on the column value alone', () => {
const update = statements.find((s) => /^UPDATE\s+uo_link_config/i.test(s))
assert.match(update, /NOT\s+EXISTS\s*\(\s*SELECT/i)
// Without the guard an operator who deliberately pins an older sidecar in
// Admin → Shard is silently re-bumped on the next restart.
assert.match(update, /uo_link_protocol_3_migrated/)
})

View File

@@ -0,0 +1,75 @@
// Protocol 4 membership routing: guild.roster (board state, possibly chunked) and
// guild.leave (a real-time departure, logged like its guild.join counterpart).
const { test, beforeEach } = require('node:test')
const assert = require('node:assert/strict')
const shardIngest = require('../utils/shardIngest')
function makeDeps() {
const calls = { roster: [], memberRemove: [], appended: [], broadcast: [] }
const noop = async () => {}
return {
calls,
shardEvents: { append: async (row) => { calls.appended.push(row); return true } },
shardState: {
upsertGuildRoster: async (ev) => { calls.roster.push(ev) },
removeGuildMember: async (ev) => { calls.memberRemove.push(ev) },
upsertGuild: noop, removeGuild: noop,
clearOnline: noop, upsertOnline: noop, setOffline: noop,
addEconomySample: noop,
},
shardLinks: { removeByAccount: noop },
uoLinkConfig: { recordStatus: noop },
broadcast: (ev) => { calls.broadcast.push(ev) },
pushDispatch: async () => {},
log: { warn() {}, info() {}, error() {} },
}
}
beforeEach(() => shardIngest.reset())
test('guild.roster routes to upsertGuildRoster and is NOT logged', async () => {
// It is board state like guild.update, and the one fat frame on the wire —
// logging it would put a full membership snapshot in shard_events on every
// membership change.
const deps = makeDeps()
const r = await shardIngest.ingest(
{ kind: 'guild.roster', id: 7, seq: 0, more: false, total: 2,
members: [{ serial: '0x1', name: 'Ada' }, { serial: '0x2', name: 'Bo' }], t: 1 },
deps,
)
assert.equal(deps.calls.roster.length, 1)
assert.equal(deps.calls.roster[0].id, 7)
assert.equal(deps.calls.roster[0].members.length, 2)
assert.equal(r.logged, false)
})
test('every frame of a chunked roster reaches the model, seq intact', async () => {
// The sidecar reassembles for its own board, but the live feed and the /history
// backfill both carry individual frames — so the model must see each one with its
// seq, which is what tells it whether to clear the guild first.
const deps = makeDeps()
for (const [seq, more, serial] of [[0, true, '0x1'], [1, true, '0x2'], [2, false, '0x3']]) {
await shardIngest.ingest(
{ kind: 'guild.roster', id: 7, seq, more, total: 3, members: [{ serial, name: serial }], t: 1 },
deps,
)
}
assert.deepEqual(deps.calls.roster.map((e) => e.seq), [0, 1, 2])
assert.deepEqual(deps.calls.roster.map((e) => e.more), [true, true, false])
})
test('guild.leave is logged and broadcast, like guild.join', async () => {
const deps = makeDeps()
const r = await shardIngest.ingest(
{ kind: 'guild.leave', id: 7, name: 'The Cartographers', who: '0x2', t: 2 }, deps)
assert.equal(r.logged, true)
assert.equal(deps.calls.appended.length, 1)
assert.equal(deps.calls.appended[0].kind, 'guild.leave')
assert.equal(deps.calls.broadcast.length, 1)
assert.deepEqual(deps.calls.memberRemove.map((e) => e.who), ['0x2'])
})

View File

@@ -116,6 +116,52 @@ test('acct and webId are stripped below admin regardless of feature config', ()
assert.equal(asAdmin.leader.webId, '42')
})
test('acct and webId are stripped from every member of a guild roster (Protocol 4)', () => {
// A roster is the first frame where the locked fields appear inside an ARRAY of
// actors rather than one nested actor. The walker recurses into arrays, so this
// should already hold — this test is here because it is the difference between a
// public Guilds page listing character names and one publishing 150 account names.
const config = visibility.compileDefaults()
const frame = {
kind: 'guild.roster',
id: 7,
total: 3,
seq: 0,
more: false,
members: [
{ serial: '0x1', name: 'Ada', acct: 'ada_acct', webId: '11', player: true },
{ serial: '0x2', name: 'Bo', acct: 'bo_acct', player: true },
{ serial: '0x3', name: 'Cy', player: true }, // a mobile with no account at all
],
}
for (const level of ['anonymous', 'logged_in', 'player', 'staff']) {
const out = visibility.projectFeature('guilds', frame, level, config)
assert.equal(out.members.length, 3, `${level} still sees every member`)
assert.deepEqual(out.members.map((m) => m.name), ['Ada', 'Bo', 'Cy'])
for (const m of out.members) {
assert.equal('acct' in m, false, `${level} must not see a member's acct`)
assert.equal('webId' in m, false, `${level} must not see a member's webId`)
}
}
const asAdmin = visibility.projectFeature('guilds', frame, 'admin', config)
assert.equal(asAdmin.members[0].acct, 'ada_acct')
assert.equal(asAdmin.members[0].webId, '11')
})
test('guild.roster and guild.leave are mapped, so neither falls closed to admin-only', () => {
// Rule 2 fails an unmapped kind closed. That is the right default, but for these
// two it would silently keep the public Guilds page from ever seeing a roster.
const config = visibility.compileDefaults()
for (const kind of ['guild.roster', 'guild.leave']) {
assert.equal(
visibility.kindVisibleTo(kind, 'anonymous', config), true,
`${kind} should reach an anonymous viewer under the default guilds config`,
)
}
})
test('a stored rule trying to loosen a locked field is ignored', async () => {
withRows([
{ feature: 'guilds', enabled: true, audience: 'anonymous', stream: true, fieldRules: { acct: 'anonymous', webId: 'anonymous' } },
@@ -308,10 +354,16 @@ const PRE_V3_PUBLIC_KINDS = [
// pointedly not among them (its feature ships with stream off).
const V3_ADDED_PUBLIC_KINDS = ['world.ruleset', 'points.board']
test('derived PUBLIC_KINDS is exactly the pre-v3 allowlist plus the v3 additions', () => {
// v4 adds guild membership. Both ride the existing `guilds` feature, which is
// already anonymous, so they join the public set — carrying character names and
// serials, never acct/webId, which the locked-field rules strip by suffix even
// inside the roster's member array (see the roster test above).
const V4_ADDED_PUBLIC_KINDS = ['guild.roster', 'guild.leave']
test('derived PUBLIC_KINDS is exactly the pre-v3 allowlist plus the v3 and v4 additions', () => {
assert.deepEqual(
[...visibility.PUBLIC_KINDS].sort(),
[...PRE_V3_PUBLIC_KINDS, ...V3_ADDED_PUBLIC_KINDS].sort(),
[...PRE_V3_PUBLIC_KINDS, ...V3_ADDED_PUBLIC_KINDS, ...V4_ADDED_PUBLIC_KINDS].sort(),
)
})

View File

@@ -0,0 +1,92 @@
// The fragment generator's derivation, checked.
//
// `scripts/swaggerFragment.js` decides the prefix of every path core will publish
// on this module's behalf, and it decides it from `server/index.js`'s own
// registration call rather than from a table. That derivation is what these
// assert. The generator's OUTPUT — whether those prefixes are the URLs a real
// core serves — is `frozenManifest.js`'s question, because answering it needs a
// core; here the question is whether the machinery reads the module correctly.
const test = require('node:test')
const assert = require('node:assert')
const { mountedRouters, prefixPaths, TIER_BASE, SLOT_MOUNT } = require('../scripts/swaggerFragment')
test('every registered mount is discovered, and resolved to a source file', () => {
const mounts = mountedRouters()
// Six: five `registerRoutes` prefixes plus the filled extension slot.
assert.strictEqual(mounts.length, 6)
for (const { file, prefix } of mounts) {
assert.match(file, /server[\\/]router[\\/]/, 'a mounted router resolved to a file outside router/')
assert.match(prefix, /^\/api\/v1\/(public|admin|player)\//)
}
})
test('the prefixes come from the registration, not from a list here', () => {
// Change `registerRoutes` in server/index.js and this list changes with it —
// which is the property being asserted. The manifest declares the same five
// prefixes and the loader rejects a mismatch between the two, so this is the
// third and last place they could disagree.
const byPrefix = mountedRouters().map((m) => m.prefix).sort()
assert.deepStrictEqual(byPrefix, [
'/api/v1/admin/shard',
'/api/v1/admin/uo-link',
'/api/v1/admin/users/:id',
'/api/v1/player/shard',
'/api/v1/public/atlas',
'/api/v1/public/shard',
])
})
test('the tier bases and the slot mount are §2.4\'s, spelled as core mounts them', () => {
assert.deepStrictEqual(TIER_BASE, {
public: '/api/v1/public',
admin: '/api/v1/admin',
player: '/api/v1/player',
})
assert.deepStrictEqual(SLOT_MOUNT, { 'admin.users.detail': '/api/v1/admin/users/:id' })
})
test('re-rooting converts express params to OpenAPI\'s', () => {
const paths = prefixPaths({ paths: { '/shard/link': { get: {} } } }, '/api/v1/admin/users/:id')
assert.deepStrictEqual(Object.keys(paths), ['/api/v1/admin/users/{id}/shard/link'])
})
test('re-rooting drops the trailing slash a collection route would produce', () => {
// `router.get('/')` under a prefix concatenates to `/api/v1/public/shard/`, a
// URL no client calls and the manifest does not record.
const paths = prefixPaths({ paths: { '/': { get: {} } } }, '/api/v1/public/shard')
assert.deepStrictEqual(Object.keys(paths), ['/api/v1/public/shard'])
})
test('the prefix\'s own parameters are ordered ahead of the route\'s', () => {
// swagger-autogen orders parameters by where they appeared in the path it saw,
// and it only ever saw the tail — so without this every slot route would churn
// the committed fragment by a reorder that means nothing.
const paths = prefixPaths(
{
paths: {
'/shard/link/{account}': {
delete: { parameters: [{ name: 'account', in: 'path' }, { name: 'id', in: 'path' }] },
},
},
},
'/api/v1/admin/users/:id',
)
const params = paths['/api/v1/admin/users/{id}/shard/link/{account}'].delete.parameters
assert.deepStrictEqual(params.map((p) => p.name), ['id', 'account'])
})
test('a parameter the prefix does not name keeps its position', () => {
const paths = prefixPaths(
{
paths: {
'/thing': { get: { parameters: [{ name: 'limit' }, { name: 'offset' }, { name: 'id' }] } },
},
},
'/api/v1/admin/users/:id',
)
const params = paths['/api/v1/admin/users/{id}/thing'].get.parameters
assert.deepStrictEqual(params.map((p) => p.name), ['id', 'limit', 'offset'])
})

View File

@@ -0,0 +1,406 @@
// module-uo's Team provider (docs/website/TEAMS.md §2.3, MODULE_API.md 1.6.0).
//
// The tests that matter here are the REFUSALS. Core's contract is that module
// unavailability becomes staleness and never emptiness, and this module is the
// only thing that can honour it — an empty array from here is read as an
// authoritative "there are none", and core makes destructive decisions from an
// authoritative answer. Every state where this module cannot honestly claim to
// know is asserted below, because each one is a plausible place for someone to
// later "simplify" the guard away and get a plausible-looking empty list.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const { test, beforeEach, afterEach } = require('node:test')
const assert = require('node:assert/strict')
const core = require('../core')
// The provider reaches the database through core, which is initialised with a ctx
// in production. A minimal one is enough here — the db layer is stubbed anyway.
core.init({
db: { query: async () => [] },
log: () => ({ error() {}, warn() {}, info() {}, debug() {} }),
moduleId: 'uo',
})
const db = require('../model/teamProvider/teamProvider.db')
const uoLinkConfig = require('../model/uoLinkConfig/uoLinkConfig.model')
const uoLinkSocket = require('../utils/uoLinkSocket')
const clilocs = require('../model/shardClilocs/shardClilocs.model')
const visibility = require('../utils/shardVisibility')
const provider = require('../model/teamProvider/teamProvider.model')
const saved = []
function patch(mod, name, fn) {
saved.push([mod, name, mod[name]])
mod[name] = fn
}
// The healthy default: configured, enabled, connected. Each test then breaks only
// the thing it is about.
function healthy() {
patch(uoLinkConfig, 'getSafe', async () => ({ baseUrl: 'http://127.0.0.1:7787', enabled: true }))
patch(uoLinkSocket, 'getState', () => ({ connected: true, running: true }))
// An operator who has never run the client extraction — the default. The standard
// rank names must still resolve from the fallback table.
patch(clilocs, 'resolveMany', async () => new Map())
patch(db, 'listGuildLeaders', async () => [])
}
const guild = (extra = {}) => ({
id: 1, name: 'The Silver Hand', abbr: 'TSH', alliance: null,
members: 2, online: 1, leader_serial: '0x1', leader_name: 'Aldric', leader_acct: 'aldric', ...extra,
})
const member = (extra = {}) => ({
serial: '0x1', name: 'Aldric', acct: 'aldric', web_id: null, is_player: 1,
rank: 1, rank_cliloc: 1062962, rank_name: null,
linked_user_id: null, is_online: 0, ...extra,
})
beforeEach(healthy)
afterEach(() => {
while (saved.length) {
const [mod, name, fn] = saved.pop()
mod[name] = fn
}
})
// ── The refusals ───────────────────────────────────────────────────────────
test('no uo-link configured refuses, on all three methods', async () => {
patch(uoLinkConfig, 'getSafe', async () => ({ baseUrl: null, enabled: false }))
patch(db, 'listGuilds', async () => { throw new Error('must not be read') })
for (const answer of [await provider.getTeams(), await provider.getTeamMembers('1'), await provider.getTeamLeaders('1')]) {
assert.equal(answer.ok, false)
assert.match(answer.reason, /no uo-link configured/)
assert.equal(answer.teams, undefined)
assert.equal(answer.members, undefined)
}
})
test('a disabled integration refuses rather than reporting a frozen board', async () => {
patch(uoLinkConfig, 'getSafe', async () => ({ baseUrl: 'http://x', enabled: false }))
const answer = await provider.getTeams()
assert.equal(answer.ok, false)
assert.match(answer.reason, /disabled/)
})
test('a disconnected socket refuses, even though the board is still there', async () => {
// The tempting mistake, stated as a test: the board is durable and survives an
// outage, so serving it looks harmless. Core cannot tell a board five minutes
// stale from one five days stale, and it archives Teams and departs members
// from a complete answer.
patch(uoLinkSocket, 'getState', () => ({ connected: false, running: true }))
patch(db, 'listGuilds', async () => [guild()])
const answer = await provider.getTeams()
assert.equal(answer.ok, false)
assert.match(answer.reason, /not connected/)
assert.equal(answer.teams, undefined, 'a stale board must not arrive as authoritative')
})
test('a database error refuses instead of throwing at core', async () => {
patch(db, 'listGuilds', async () => { throw new Error('table gone') })
const answer = await provider.getTeams()
assert.equal(answer.ok, false)
assert.match(answer.reason, /table gone/)
})
test('a guild absent from the board refuses rather than reporting an empty roster', async () => {
patch(db, 'findGuild', async () => [])
const members = await provider.getTeamMembers('99')
assert.equal(members.ok, false)
assert.match(members.reason, /not on the board/)
const leaders = await provider.getTeamLeaders('99')
assert.equal(leaders.ok, false)
})
test('a roster that has not arrived yet refuses — the board count is what tells us', async () => {
// Protocol 4's roster arrives on its own frames, separately from the
// guild.update that creates the board row, so there is a real window where a
// 155-member guild has no roster rows. Reporting that as an empty roster would
// depart every member.
patch(db, 'findGuild', async () => [guild({ members: 155 })])
patch(db, 'listGuildMembers', async () => [])
const answer = await provider.getTeamMembers('1')
assert.equal(answer.ok, false)
assert.match(answer.reason, /has not arrived yet/)
assert.match(answer.reason, /155/, 'the count is in the message, because it is the evidence')
})
test('a guild the board says is genuinely empty reports an empty roster', async () => {
// The other side of the same coin: when the board itself says zero, an empty
// roster is the truth and withholding it would freeze a disbanding guild's
// membership forever.
patch(db, 'findGuild', async () => [guild({ members: 0 })])
patch(db, 'listGuildMembers', async () => [])
const answer = await provider.getTeamMembers('1')
assert.equal(answer.ok, true)
assert.deepEqual(answer.members, [])
})
// ── The good answers ───────────────────────────────────────────────────────
test('a guild becomes a Team keyed on its persistent ServUO id', async () => {
// The id survives a rename, which is what lets core apply its rename rule
// instead of seeing an unrelated new guild.
patch(db, 'listGuilds', async () => [guild()])
const answer = await provider.getTeams()
assert.equal(answer.ok, true)
assert.equal(answer.complete, true)
assert.deepEqual(answer.teams, [
{ externalId: '1', name: 'The Silver Hand', abbr: 'TSH', meta: null },
])
})
test('an alliance rides along as opaque meta', async () => {
patch(db, 'listGuilds', async () => [guild({ alliance: 'The Concord' })])
const { teams } = await provider.getTeams()
assert.deepEqual(teams[0].meta, { alliance: 'The Concord' })
})
test('the external id is a string, so core never compares a number to one', async () => {
patch(db, 'listGuilds', async () => [guild({ id: 42 })])
const { teams } = await provider.getTeams()
assert.equal(teams[0].externalId, '42')
})
test('a roster maps to the member shape core expects', async () => {
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [
member({ serial: '0x1', name: 'Aldric', rank: 4, rank_cliloc: 1062959, is_online: 1 }),
member({ serial: '0x2', name: 'Bree', acct: null, rank: 1, is_online: 0 }),
])
const { members } = await provider.getTeamMembers('1')
assert.equal(members.length, 2)
assert.equal(members[0].memberKey, '0x1')
assert.equal(members[0].displayName, 'Aldric')
assert.equal(members[0].online, true)
assert.equal(members[0].leader, true, 'rank 4 is Leader')
assert.equal(members[1].leader, false)
assert.equal(members[1].online, false)
})
// ── Rank (the Protocol 4 amendment) ────────────────────────────────────────
test('several members can be leaders at once', async () => {
// The whole reason the wire grew a per-member rank: the board carries one
// leader_serial, so before this only a single leader could ever be reported.
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [
member({ serial: '0x1', rank: 4 }),
member({ serial: '0x2', rank: 4 }),
member({ serial: '0x3', rank: 3 }),
])
const { members } = await provider.getTeamMembers('1')
assert.deepEqual(members.filter((m) => m.leader).map((m) => m.memberKey), ['0x1', '0x2'])
})
test('getTeamLeaders returns everyone at rank 4, not just the board’s one', async () => {
patch(db, 'findGuild', async () => [guild({ leader_serial: '0x1' })])
patch(db, 'listGuildLeaders', async () => [{ serial: '0x1' }, { serial: '0x2' }])
assert.deepEqual((await provider.getTeamLeaders('1')).leaders, ['0x1', '0x2'])
})
test('the board’s leader is kept even when no roster row has rank yet', async () => {
// A shard whose roster has not been re-emitted since the amendment has no ranks
// stored. The founder-leader comes from a different frame and must not be lost
// by moving to ranks.
patch(db, 'findGuild', async () => [guild({ leader_serial: '0x9' })])
patch(db, 'listGuildLeaders', async () => [])
assert.deepEqual((await provider.getTeamLeaders('1')).leaders, ['0x9'])
})
test('the board’s leader is not duplicated when they also hold rank 4', async () => {
patch(db, 'findGuild', async () => [guild({ leader_serial: '0x1' })])
patch(db, 'listGuildLeaders', async () => [{ serial: '0x1' }, { serial: '0x2' }])
const { leaders } = await provider.getTeamLeaders('1')
assert.equal(new Set(leaders).size, leaders.length)
})
test('a NULL rank is not a leader — "not known" is not "leads this guild"', async () => {
// The shard withholds the rank for a staff account, because ServUO's GuildRank
// getter reports Leader for anyone at GameMaster or above whatever their real
// rank. Reading the absence as leadership would republish exactly that lie.
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [member({ serial: '0x1', rank: null, rank_cliloc: null })])
const { members } = await provider.getTeamMembers('1')
assert.equal(members[0].leader, false)
assert.equal(members[0].rankLabel, null)
})
test('a standard rank resolves to its name without a cliloc table', async () => {
// The operator may never have run the client extraction, and a roster should
// still read "Warlord" rather than nothing.
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [
member({ serial: '0x1', rank: 4, rank_cliloc: 1062959 }),
member({ serial: '0x2', rank: 3, rank_cliloc: 1062960 }),
member({ serial: '0x3', rank: 0, rank_cliloc: 1062963 }),
])
const { members } = await provider.getTeamMembers('1')
assert.deepEqual(members.map((m) => m.rankLabel), ['Leader', 'Warlord', 'Ronin'])
})
test('the operator’s cliloc table wins over the built-in names', async () => {
// A localised or edited client should name the ranks, not this module's English
// fallback.
patch(clilocs, 'resolveMany', async () => new Map([[1062960, 'Kriegsherr']]))
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [member({ serial: '0x1', rank: 3, rank_cliloc: 1062960 })])
assert.equal((await provider.getTeamMembers('1')).members[0].rankLabel, 'Kriegsherr')
})
test('a custom rank’s literal name beats both', async () => {
// A shard that replaced RankDefinition.Ranks sends a string instead of a cliloc,
// and its own naming has to survive.
patch(clilocs, 'resolveMany', async () => new Map([[1062960, 'Warlord']]))
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [
member({ serial: '0x1', rank: 3, rank_cliloc: 1062960, rank_name: 'Sword-Captain' }),
])
assert.equal((await provider.getTeamMembers('1')).members[0].rankLabel, 'Sword-Captain')
})
test('a failing cliloc lookup falls back rather than failing the roster', async () => {
patch(clilocs, 'resolveMany', async () => { throw new Error('cliloc table missing') })
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [member({ serial: '0x1', rank: 3, rank_cliloc: 1062960 })])
const answer = await provider.getTeamMembers('1')
assert.equal(answer.ok, true, 'a label is decoration; losing it must not lose the roster')
assert.equal(answer.members[0].rankLabel, 'Warlord')
})
test('an unknown cliloc leaves the label null rather than inventing one', async () => {
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [member({ serial: '0x1', rank: 2, rank_cliloc: 9999999 })])
assert.equal((await provider.getTeamMembers('1')).members[0].rankLabel, null)
})
test('a member with no account at all is fine and unlinked', async () => {
// §2.3 of the protocol spec: acct is genuinely optional — a PlayerMobile can
// have no Account, and the local test world contains such mobiles.
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [member({ acct: null, web_id: null, linked_user_id: null })])
const { members } = await provider.getTeamMembers('1')
assert.equal(members[0].userId, null)
})
test('userId comes from the roster’s web_id first, then the link table', async () => {
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [
member({ serial: '0xA', web_id: '7', linked_user_id: 99 }), // roster wins
member({ serial: '0xB', web_id: null, linked_user_id: 12 }), // fallback
member({ serial: '0xC', web_id: '0', linked_user_id: null }), // neither
])
const { members } = await provider.getTeamMembers('1')
assert.equal(members[0].userId, 7, 'what the shard itself asserted at roster time')
assert.equal(members[1].userId, 12, 'the fallback for a row that predates the link')
assert.equal(members[2].userId, null)
})
test('web_id arrives as a string from the wire and is coerced', async () => {
patch(db, 'findGuild', async () => [guild()])
patch(db, 'listGuildMembers', async () => [member({ web_id: '42' })])
const { members } = await provider.getTeamMembers('1')
assert.equal(members[0].userId, 42)
assert.equal(typeof members[0].userId, 'number')
})
test('a guild with no leader anywhere reports none rather than guessing', async () => {
patch(db, 'findGuild', async () => [guild({ leader_serial: null })])
patch(db, 'listGuildLeaders', async () => [])
const answer = await provider.getTeamLeaders('1')
assert.equal(answer.ok, true)
assert.deepEqual(answer.leaders, [])
})
test('an empty board is an authoritative empty list — the shard really has no guilds', async () => {
// Distinct from every refusal above: the socket is connected and the board is
// readable, so "no guilds" is a fact. Core still quarantines it before acting.
patch(db, 'listGuilds', async () => [])
const answer = await provider.getTeams()
assert.equal(answer.ok, true)
assert.deepEqual(answer.teams, [])
})
// ── projectRoster (TEAMS.md §3.3) ──────────────────────────────────────────
//
// The refusal semantics INVERT here and that is the point of these tests. For
// the three methods above, a refusal means "change nothing" and an empty array
// would be destructive. For this one, core fails CLOSED — a refusal withholds the
// roster — so the dangerous answer is the opposite: returning every key because
// the config could not be read would publish a roster an operator gated to staff.
const rows = [{ member_key: '0x1' }, { member_key: '0x2' }]
function guilds(feature) {
patch(visibility, 'getConfig', async () => ({ guilds: feature }))
}
test('a viewer at or above the audience sees every row', async () => {
guilds({ enabled: true, audience: 'anonymous' })
const answer = await provider.projectRoster('1', rows, null)
assert.equal(answer.ok, true)
assert.deepEqual(answer.members, ['0x1', '0x2'])
})
test('a viewer below the audience sees none — authoritatively, not as a refusal', async () => {
// `ok: true` with an empty list is the correct answer here: this module KNOWS
// the viewer may see nothing. Core renders an empty roster rather than an
// error, which is what a gated shard is supposed to look like.
guilds({ enabled: true, audience: 'staff' })
const answer = await provider.projectRoster('1', rows, { userId: 7, role: 'player' })
assert.equal(answer.ok, true)
assert.deepEqual(answer.members, [])
})
test('an admin clears every audience', async () => {
guilds({ enabled: true, audience: 'admin' })
const answer = await provider.projectRoster('1', rows, { userId: 1, role: 'admin' })
assert.deepEqual(answer.members, ['0x1', '0x2'])
})
test('a disabled guilds feature hides the roster from everyone, staff included', async () => {
// The switch means "this shard does not publish guild data", not "publish it
// quietly to staff".
guilds({ enabled: false, audience: 'anonymous' })
const answer = await provider.projectRoster('1', rows, { userId: 1, role: 'admin' })
assert.equal(answer.ok, true)
assert.deepEqual(answer.members, [])
})
test('an unreadable visibility config REFUSES rather than publishing', async () => {
// The inversion, stated. Core reads this as "withhold", which is the only safe
// reading of "I could not work out who is allowed to look".
patch(visibility, 'getConfig', async () => { throw new Error('pool down') })
const answer = await provider.projectRoster('1', rows, null)
assert.equal(answer.ok, false)
assert.match(answer.reason, /visibility could not be resolved/)
})
test('an absent viewer is anonymous, not an error', async () => {
guilds({ enabled: true, audience: 'logged_in' })
const answer = await provider.projectRoster('1', rows, null)
assert.equal(answer.ok, true)
assert.deepEqual(answer.members, [], 'anonymous does not meet logged_in')
})
test('rows with no member key are dropped rather than answered as blanks', async () => {
guilds({ enabled: true, audience: 'anonymous' })
const answer = await provider.projectRoster('1', [{ member_key: '0x1' }, { member_key: null }], null)
assert.deepEqual(answer.members, ['0x1'])
})

View File

@@ -45,6 +45,12 @@ const LOGGED_KINDS = new Set([
'server.crashed',
// Protocol 2.0: a real-time guild join (the board itself is state, not logged).
'guild.join',
// Protocol 4: the departure counterpart to guild.join, and logged for the same
// reason — it is what a "so-and-so left" feed reads. `guild.roster` deliberately
// stays out: it is board state like guild.update, and it is the one fat frame on
// the wire (~69 bytes per member), so logging it would bloat shard_events with
// a full membership snapshot on every membership change.
'guild.leave',
// Protocol 2.0 provisioning audit (admin channel only — not in PUBLIC_KINDS).
'account.audit',
'account.unlinked',
@@ -187,6 +193,16 @@ async function applyStateChange(event, deps) {
case 'guild.remove':
await shardState.removeGuild(event.id)
return
// Protocol 4: membership. A roster arrives in one frame for any realistic
// guild and in several for one over the shard's cap — upsertGuildRoster
// handles both. guild.leave is advisory; the next roster would converge
// anyway, but applying it shows the departure at once.
case 'guild.roster':
await shardState.upsertGuildRoster(event)
return
case 'guild.leave':
await shardState.removeGuildMember(event)
return
case 'city.update':
// Upserts the board AND captures term history (idempotent).
await shardState.upsertGovernor(event)

View File

@@ -163,6 +163,13 @@ const KIND_FEATURE = new Map(
'guild.update': 'guilds',
'guild.remove': 'guilds',
'guild.join': 'guilds',
// Protocol 4. Both carry actor data — a roster is an array of actor objects
// and guild.leave names a serial — so they ride the same `guilds` feature and
// the same locked-field rules: `acct`/`webId` inside a roster member are
// stripped below admin by suffix, exactly as `guild.leader.acct` already is.
// Without these two lines rule 2 would fail them closed to admin-only.
'guild.roster': 'guilds',
'guild.leave': 'guilds',
'city.update': 'governors',
'presence.online': 'presence',
'region.enter': 'presence',

54
sonar-project.properties Normal file
View File

@@ -0,0 +1,54 @@
# SonarQube analysis config for module-uo.
# Consumed by the scanner in .gitea/workflows/sonarqube.yml on push to main.
# The project key must match the one created in SonarQube (dashboard URL
# ?id=Module-uo).
sonar.projectKey=Module-uo
sonar.projectName=Module-uo
# Analysed application code.
#
# Unlike core's repo there is no `src/` directory to point at: the server half
# keeps its code at `server/` root (boot.js, core.js, index.js) beside its
# subdirectories, so the whole tree is included and the non-source parts are
# excluded below. That direction is deliberate — a new top-level server
# directory is scanned by default rather than silently unscanned, which is the
# safer way for this list to be wrong.
#
# `client/scripts` and `server/scripts` are in, not out: checkExternals.js and
# checkImports.js *are* the enforcement of MODULE_API.md §3.6 and §5.1, they
# each carry their own test suite, and both have already shipped defects that a
# reviewer missed (see MODULE_SYSTEM.md §2.7.1). Build code that decides whether
# a release is allowed out is not throwaway code.
sonar.sources=server,client/src,client/scripts
# Test code is analysed separately from sources so coverage/metrics attribute
# correctly. Both halves run on Node's built-in test runner (no browser/DOM):
# the server suite is CommonJS behind test/_setup.js, the client's is ESM.
sonar.tests=server/test,client/test
sonar.test.inclusions=server/test/**/*.test.js,client/test/**/*.test.js
# Coverage. The sonarqube.yml workflow runs both suites with Node's built-in
# test-coverage and writes an LCOV report for each BEFORE the scan runs; without
# them the dashboard shows 0% (the scanner never executes tests itself). Both
# suites are invoked from the repo root so the `SF:` paths come out
# repo-root-relative (server/..., client/src/...) and the scanner resolves them
# against the project base dir.
sonar.javascript.lcov.reportPaths=server/coverage/lcov.info,client/coverage/lcov.info
# Test execution ("Unit Tests" measure). A SEPARATE report from coverage: the
# lcov files above only populate Coverage, so without this the dashboard shows a
# coverage % but an empty "Unit Tests" tile. Written by scripts/sonar-test-reporter.mjs,
# a copy of core's — a pure leaf build helper, which is the side of the vendoring
# line that may be copied (MODULE_SYSTEM.md §2.7.1).
sonar.testExecutionReportPaths=server/coverage/test-execution.xml,client/coverage/test-execution.xml
# Never analyse dependencies, build output, generated artifacts, or fixtures.
#
# `client/dist` is the built chunk (gitignored, but the workflow builds it before
# scanning because client/test/{build,registration}.test.js import it).
# `server/swagger/doc.js` and the two committed generated artifacts at the repo
# root are inputs to and outputs of swagger-autogen, not hand-written code.
sonar.exclusions=**/node_modules/**,server/test/**,client/test/**,client/dist/**,server/swagger/**,server/data/**,server/coverage/**,client/coverage/**,**/*.min.js
sonar.sourceEncoding=UTF-8

8210
swagger-fragment.json Normal file

File diff suppressed because it is too large Load Diff