Expand Clash achievements to revision 2 and prepare faction artwork

This commit is contained in:
coyotte508 2026-11-14 01:26:16 +00:00
commit 61be734999
15 changed files with 1848 additions and 32 deletions

View file

@ -1,10 +1,11 @@
# Clash of Cultures achievements
Delivered engine release: `@boardgamers/clash-server` **0.4.150**, BGS `clash/1`
(Clash of Cultures: Monumental edition). Engine-only release; the hosted viewer
remains 0.1.217. See `web-client/release/engine-package.json` for package metadata
and [the delivery receipt](../web-client/docs/achievements-0.4.150-receipt.md) for
the exact reviewed artifact, source commit and activation evidence.
Prepared engine release: `@boardgamers/clash-server` **0.4.151**, BGS `clash/1`
(Clash of Cultures: Monumental edition). Revision 2 and its artwork await independent
review before any production upload or source push. No viewer release is planned;
the hosted viewer remains 0.1.217. See `web-client/release/engine-package.json`.
The [revision-1 delivery receipt](../web-client/docs/achievements-0.4.150-receipt.md)
records the previously delivered 0.4.150 artifact, not this prepared release.
The native Rust evaluator is the single source of truth. The WASM package exports
`achievementDefinitions()` and `achievements(serializedData)` directly, alongside
@ -12,14 +13,17 @@ its existing engine hooks. The web-client tests check the generated API against
`@boardgamers/protocol` **0.11.0** types and runtime schemas; there is no separate
JavaScript scoring implementation.
## Revision 1 catalog
## Revision 2 catalog — 41 definitions
Revision 2 removes `four-cities` and replaces it with a distinct `seven-cities` ID.
There is no migration, historical backfill, or repurposing of the old ID.
Each length has `complete-<length>` and `win-<length>` achievements:
| ID suffix | Explicit length | Rules |
| --- | --- | --- |
| `shorter` | Shorter | 4 ages, two starting settlers, two status-phase advances |
| `standard` | Standard (Normal) | 6 ages; also the legacy/default option |
| `standard` | Standard | 6 ages; also the legacy/default option |
| `roll-to-end` | Roll to End | 6–7 ages, end rolls from age 6 round 2 |
| `wonderful-ending` | Wonderful Ending | 6–7 ages, qualifying wonder ends after its round |
| `epic` | Epic | 8 ages |
@ -30,19 +34,84 @@ Additional feats are evaluated independently of victory:
| --- | --- |
| `score-30` | At least 30 victory points using engine scoring |
| `score-40` | At least 40 victory points using engine scoring |
| `four-cities` | At least four cities currently controlled |
| `seven-cities` | At least seven cities currently controlled, not cities founded over time |
| `twenty-advances` | At least 20 regular advances (not special advances) |
| `three-objectives` | At least three completed objective records |
| `two-wonders-built` | At least two recorded wonders built, not merely owned |
| `captured-leader` | At least one recorded captured leader |
The wonder feat deliberately uses the **final surviving `wonders_built` record**,
| `complete-builder` | Complete a game with `options.variant = Builder`, regardless of winning |
Seven cities is the normal legal capacity (`CITY_LIMIT = 7`); permanently destroyed
city centers reduce that capacity. The badge checks the final owned-city count,
not capacity or a historical counter. Builder disables military attacks between
human players, but retains ordinary game endings and scoring. Its completion badge
is additive to the relevant length-completion badge; it is not a Builder win badge.
### Civilization wins and symbols
Each of the 15 actual playable civilizations has a strict-win achievement. Full
score ties do not count. The match uses the canonical final civilization name:
| Civilization | Achievement ID | Asset key |
| --- | --- | --- |
| Rome | `win-rome` | `achievement-faction-rome` |
| Greece | `win-greece` | `achievement-faction-greece` |
| China | `win-china` | `achievement-faction-china` |
| Vikings | `win-vikings` | `achievement-faction-vikings` |
| Babylonia | `win-babylonia` | `achievement-faction-babylonia` |
| India | `win-india` | `achievement-faction-india` |
| Egypt | `win-egypt` | `achievement-faction-egypt` |
| Phoenicia | `win-phoenicia` | `achievement-faction-phoenicia` |
| Maya | `win-maya` | `achievement-faction-maya` |
| Persia | `win-persia` | `achievement-faction-persia` |
| Japan | `win-japan` | `achievement-faction-japan` |
| Huns | `win-huns` | `achievement-faction-huns` |
| Celts | `win-celts` | `achievement-faction-celts` |
| Aztecs | `win-aztecs` | `achievement-faction-aztecs` |
| Carthage | `win-carthage` | `achievement-faction-carthage` |
Barbarians, Pirates and the Choose Civilization placeholder are not playable
faction achievements. Icons use the viewer's existing civilization symbols, not
new logos. The manifest references named assets, not viewer-bundle URLs. After
independent code/artwork approval, upload the reviewed images through the named
asset admin API and verify public durable `achievements/clash/<key>/<hash>/...`
URLs **before** activating revision 2. Do not change bucket policy in this task;
report inaccessible artwork as a publication blocker.
### Individual wonder build records
All eight supported real wonders also have an individual feat, independent of
victory, using the exact engine `wonders_built` membership. `Hidden` is a redaction
placeholder and has no achievement. Names use the viewer's existing Monumental
Edition wording; saved enum IDs are unchanged.
| Saved wonder ID | Display name | Achievement ID |
| --- | --- | --- |
| `Colosseum` | Great Arena | `built-great-arena` |
| `Pyramids` | Great Pyramids | `built-great-pyramids` |
| `GreatGardens` | Great Gardens | `built-great-gardens` |
| `GreatLibrary` | Great Library | `built-great-library` |
| `GreatLighthouse` | Great Lighthouse | `built-great-lighthouse` |
| `GreatMausoleum` | Great Mausoleum | `built-great-mausoleum` |
| `GreatStatue` | Great Statue | `built-great-statue` |
| `GreatWall` | Great Wall | `built-great-wall` |
Each means **finish with that wonder recorded as built by your civilization**.
Ownership is not substituted for building: a captor without a built record does
not qualify, while the original builder can still qualify after capture if its
record survives. The two-wonder badge remains a separate requirement for at least
two surviving built records. Individual wonder badges use generic icon fallback;
no additional artwork or artwork provenance claims are introduced.
All wonder build feats deliberately use the **final surviving `wonders_built` record**,
not a lifetime construction count: `destroy_wonder` removes a destroyed wonder
from that record for every player. Two wonders built earlier do not qualify if
fewer than two remain recorded at completion. Merely capturing/owning a wonder
never substitutes for a built record. This is covered by a destruction regression.
Icons are omitted intentionally: the platform's generic fallback is sufficient.
Faction definitions include official optional `{type: "asset", key: ...}` icons.
Other definitions omit icons and use the platform's generic fallback.
IDs are permanent identities and must not be repurposed. This catalog is BGS
platform metadata, not text rendered by the game viewer, so the viewer localization
extractor excludes it. Protocol 0.11.0 also requires `openChat` and `undo` commands;
@ -66,8 +135,9 @@ seats from NPC factions, not account ownership. Do not run these hooks on arbitr
client submissions or use their results as proof of platform eligibility.
Evaluation does not advance play, consume randomness, change saves, or expose
hands, hidden cards, seeds, history, or account identifiers. No inferred combat
history or civilization-specific claims are awarded.
hands, hidden cards, seeds, history, or account identifiers. Civilization wins use
the final canonical civilization and engine outcome; no inferred combat history
or unrecorded historical civilization claims are awarded.
## Verification

View file

@ -1,6 +1,7 @@
//! Read-only, revisioned achievements derived from authoritative final game state.
use crate::game::{Game, GameLength, GameState};
use crate::game::{Game, GameLength, GameState, GameVariant};
use crate::victory_points::compare_score;
use crate::wonder::Wonder;
use serde::Serialize;
use std::cmp::Ordering;
@ -15,6 +16,14 @@ pub struct Definition {
pub id: String,
pub name: String,
pub description: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<Icon>,
}
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Icon {
Asset { key: String },
}
#[derive(Debug, PartialEq, Eq, Serialize)]
@ -26,7 +35,7 @@ pub struct SeatAchievements {
const LENGTHS: [(GameLength, &str, &str); 5] = [
(GameLength::Shorter, "shorter", "Shorter"),
(GameLength::Standard, "standard", "Standard (Normal)"),
(GameLength::Standard, "standard", "Standard"),
(GameLength::RollToEnd, "roll-to-end", "Roll to End"),
(
GameLength::WonderfulEnding,
@ -35,6 +44,41 @@ const LENGTHS: [(GameLength, &str, &str); 5] = [
),
(GameLength::Epic, "epic", "Epic"),
];
const FACTIONS: [(&str, &str); 15] = [
("Rome", "rome"),
("Greece", "greece"),
("China", "china"),
("Vikings", "vikings"),
("Babylonia", "babylonia"),
("India", "india"),
("Egypt", "egypt"),
("Phoenicia", "phoenicia"),
("Maya", "maya"),
("Persia", "persia"),
("Japan", "japan"),
("Huns", "huns"),
("Celts", "celts"),
("Aztecs", "aztecs"),
("Carthage", "carthage"),
];
const WONDERS: [(Wonder, &str, &str); 8] = [
(Wonder::Colosseum, "built-great-arena", "Great Arena"),
(Wonder::Pyramids, "built-great-pyramids", "Great Pyramids"),
(Wonder::GreatGardens, "built-great-gardens", "Great Gardens"),
(Wonder::GreatLibrary, "built-great-library", "Great Library"),
(
Wonder::GreatLighthouse,
"built-great-lighthouse",
"Great Lighthouse",
),
(
Wonder::GreatMausoleum,
"built-great-mausoleum",
"Great Mausoleum",
),
(Wonder::GreatStatue, "built-great-statue", "Great Statue"),
(Wonder::GreatWall, "built-great-wall", "Great Wall"),
];
const FEATS: [(&str, &str, &str); 7] = [
(
"score-30",
@ -47,9 +91,9 @@ const FEATS: [(&str, &str, &str); 7] = [
"Finish a game with at least 40 victory points in the final state.",
),
(
"four-cities",
"Four Cities",
"Finish a game owning at least 4 cities in the final state.",
"seven-cities",
"Seven Cities",
"Finish a game owning at least 7 cities in the final state.",
),
(
"twenty-advances",
@ -76,26 +120,47 @@ const FEATS: [(&str, &str, &str); 7] = [
/// The stable achievement catalogue. Array order also defines award order.
#[must_use]
pub fn definitions() -> Manifest {
let mut definitions = Vec::with_capacity(17);
let mut definitions = Vec::with_capacity(41);
for (_, id, name) in LENGTHS {
definitions.push(Definition {
id: format!("complete-{id}"),
name: format!("Complete {name}"),
description: format!("Finish a {name} game without dropping out."),
icon: None,
});
definitions.push(Definition {
id: format!("win-{id}"),
name: format!("Win {name}"),
description: format!("Finish a {name} game as the sole highest-ranked non-dropped human seat, including score tiebreakers; tied games do not count as wins."),
icon: None,
});
}
definitions.extend(FEATS.map(|(id, name, description)| Definition {
id: id.into(),
name: name.into(),
description: description.into(),
icon: None,
}));
definitions.extend(WONDERS.map(|(_, id, name)| Definition {
id: id.into(),
name: format!("{name}: Recorded as Built"),
description: format!("Finish with {name} recorded as built by your civilization. Destroyed wonders and merely owning captured wonders do not count."),
icon: None,
}));
definitions.push(Definition {
id: "complete-builder".into(),
name: "Complete Builder".into(),
description: "Finish a Builder variant game without dropping out.".into(),
icon: None,
});
definitions.extend(FACTIONS.map(|(name, slug)| Definition {
id: format!("win-{slug}"),
name: format!("Win as {name}"),
description: format!("Finish a game as {name} as the sole highest-ranked non-dropped human seat, including score tiebreakers; tied games do not count as wins."),
icon: Some(Icon::Asset { key: format!("achievement-faction-{slug}") }),
}));
Manifest {
revision: 1,
revision: 2,
achievements: definitions,
}
}
@ -132,7 +197,7 @@ pub fn achievements(game: &Game) -> Vec<SeatAchievements> {
let predicates = [
score >= 30.0,
score >= 40.0,
p.cities.len() >= 4,
p.cities.len() >= 7,
p.advances.len() >= 20,
p.completed_objectives.len() >= 3,
p.wonders_built.len() >= 2,
@ -143,6 +208,11 @@ pub fn achievements(game: &Game) -> Vec<SeatAchievements> {
awards.push((*id).into());
}
}
for (wonder, id, _) in &WONDERS {
if p.wonders_built.contains(wonder) {
awards.push((*id).into());
}
}
let outcome = if players
.iter()
.any(|other| compare_score(p, other, game) == Ordering::Less)
@ -155,6 +225,16 @@ pub fn achievements(game: &Game) -> Vec<SeatAchievements> {
} else {
"win"
};
if game.options.variant == GameVariant::Builder {
awards.push("complete-builder".into());
}
if outcome == "win"
&& let Some((_, slug)) = FACTIONS
.iter()
.find(|(name, _)| *name == p.civilization.name)
{
awards.push(format!("win-{slug}"));
}
SeatAchievements {
seat: p.index,
earned: awards,
@ -178,17 +258,21 @@ mod tests {
use crate::playing_actions::PlayingAction;
use crate::special_advance::SpecialAdvance;
use crate::victory_points::{SpecialVictoryPoints, VictoryPointAttribution};
use crate::wonder::Wonder;
use enumset::EnumSet;
use std::collections::HashSet;
fn setup(length: GameLength) -> Game {
setup_variant(length, GameVariant::Standard)
}
fn setup_variant(length: GameLength, variant: GameVariant) -> Game {
let mut game = setup_game(
&GameSetupBuilder::new(2)
.seed("achievements-tests".into())
.assigned_civilizations(vec!["Rome".into(), "Greece".into()])
.options(GameOptions {
length,
variant,
..GameOptions::default()
})
.build(),
@ -229,8 +313,8 @@ mod tests {
#[test]
fn manifest_and_real_end_turn_for_all_lengths() {
let manifest = definitions();
assert_eq!(manifest.revision, 1);
assert_eq!(manifest.achievements.len(), 17);
assert_eq!(manifest.revision, 2);
assert_eq!(manifest.achievements.len(), 41);
assert_eq!(
manifest
.achievements
@ -238,13 +322,13 @@ mod tests {
.map(|d| &d.id)
.collect::<HashSet<_>>()
.len(),
17
41
);
assert!(
manifest
.achievements
.iter()
.any(|d| d.name == "Complete Standard (Normal)")
.any(|d| d.name == "Complete Standard")
);
for (length, id, _) in LENGTHS {
let mut game = setup(length);
@ -318,10 +402,8 @@ mod tests {
#[test]
fn final_state_counts_not_special_advances_or_owned_wonders() {
let mut game = finish(setup(GameLength::Standard));
let pos = game.player(0).cities[0].position;
for count in [0, 1, 2] {
let p = game.player_mut(0);
p.cities = (0..3 + count).map(|_| City::new(0, pos)).collect();
p.advances = EnumSet::<Advance>::all().iter().take(19 + count).collect();
p.special_advances.insert(SpecialAdvance::Aqueduct);
p.completed_objectives = (0..2 + count)
@ -335,7 +417,6 @@ mod tests {
[Wonder::Colosseum, Wonder::Pyramids, Wonder::GreatGardens][..1 + count].to_vec();
p.captured_leaders = [Leader::Alexander, Leader::Caesar][..count].to_vec();
for id in [
"four-cities",
"twenty-advances",
"three-objectives",
"two-wonders-built",
@ -346,6 +427,199 @@ mod tests {
}
}
#[test]
fn faction_catalog_matches_every_playable_civilization_and_wire_shape() {
let playable: HashSet<_> = crate::content::civilizations::get_all_uncached()
.into_iter()
.filter(crate::civilization::Civilization::can_choose)
.map(|c| c.name)
.collect();
assert_eq!(
playable,
FACTIONS.iter().map(|(name, _)| (*name).into()).collect()
);
let manifest = serde_json::to_value(definitions()).unwrap();
assert_eq!(manifest["revision"], 2);
assert_eq!(manifest.as_object().unwrap().len(), 2);
let entries = manifest["achievements"].as_array().unwrap();
assert_eq!(entries.len(), 41);
for entry in entries {
let faction = FACTIONS
.iter()
.find(|(_, slug)| entry["id"] == format!("win-{slug}"));
if let Some((name, slug)) = faction {
assert_eq!(*slug, name.to_lowercase());
assert_eq!(entry["name"], format!("Win as {name}"));
assert_eq!(
entry["icon"],
serde_json::json!({
"type": "asset", "key": format!("achievement-faction-{slug}")
})
);
assert_eq!(entry.as_object().unwrap().len(), 4);
} else {
assert!(entry.get("icon").is_none());
assert_eq!(entry.as_object().unwrap().len(), 3);
}
}
assert!(!manifest.to_string().contains("four-cities"));
}
#[test]
fn every_faction_requires_exact_name_and_a_win_not_loss_or_draw() {
for civilization in crate::content::civilizations::get_all_uncached()
.into_iter()
.filter(crate::civilization::Civilization::can_choose)
{
let name = civilization.name.clone();
let mut game = finish(setup(GameLength::Standard));
game.player_mut(0).civilization = civilization;
for (score, outcome) in [(30.0, "win"), (10.0, "loss"), (20.0, "draw")] {
set_score(&mut game, 0, score);
set_score(&mut game, 1, 20.0);
let results = achievements(&game);
assert_eq!(results[0].outcome, outcome, "{name}");
for result in &results {
for (faction, slug) in FACTIONS {
assert_eq!(
result.earned.contains(&format!("win-{slug}")),
result.outcome == "win"
&& game.player(result.seat).civilization.name == faction,
"{name}, {outcome}, {slug}"
);
}
}
let json = serde_json::to_value(&results).unwrap();
assert_eq!(
json[0],
serde_json::json!({
"seat": 0, "earned": results[0].earned, "outcome": outcome
})
);
assert!(!json.to_string().contains("four-cities"));
}
set_score(&mut game, 0, 30.0);
game.player_mut(0).civilization.name = name.to_lowercase();
assert!(!has(&game, 0, &format!("win-{}", name.to_lowercase())));
}
}
#[test]
fn seven_current_cities_is_the_legal_capacity_boundary() {
let mut game = finish(setup(GameLength::Standard));
let positions: Vec<_> = game.map.tiles.keys().copied().take(7).collect();
assert_eq!(positions.len(), 7);
assert_eq!(game.player(0).city_limit(), 7);
for (count, earned) in [(6, false), (7, true), (6, false)] {
game.player_mut(0).cities = positions
.iter()
.take(count)
.map(|pos| City::new(0, *pos))
.collect();
assert_eq!(has(&game, 0, "seven-cities"), earned);
assert!(
!serde_json::to_string(&achievements(&game))
.unwrap()
.contains("four-cities")
);
}
}
#[test]
fn builder_real_end_turn_awards_losing_seat_but_not_unfinished_or_stripped() {
let mut game = setup_variant(GameLength::Standard, GameVariant::Builder);
set_score(&mut game, 0, 40.0);
assert!(achievements(&game).is_empty());
let mut game = finish(game);
let results = achievements(&game);
assert_eq!(results[1].outcome, "loss");
assert!(has(&game, 0, "complete-builder"));
assert!(has(&game, 1, "complete-builder"));
assert!(has(&game, 0, "win-rome"));
assert!(!has(&game, 1, "win-greece"));
game.secrets_stripped = true;
assert!(achievements(&game).is_empty());
assert!(!has(
&finish(setup(GameLength::Standard)),
0,
"complete-builder"
));
}
#[test]
fn wonder_catalog_matches_real_registry_and_standard_names() {
let registered: HashSet<_> = crate::content::wonders::get_all_uncached()
.into_iter()
.map(|info| info.wonder)
.filter(|wonder| *wonder != Wonder::Hidden)
.collect();
assert_eq!(
registered,
WONDERS.iter().map(|(wonder, _, _)| *wonder).collect()
);
assert!(
!WONDERS
.iter()
.any(|(wonder, _, _)| *wonder == Wonder::Hidden)
);
let manifest = definitions();
for (_, id, name) in WONDERS {
let entry = manifest
.achievements
.iter()
.find(|entry| entry.id == id)
.unwrap();
assert_eq!(entry.name, format!("{name}: Recorded as Built"));
assert_eq!(
entry.description,
format!(
"Finish with {name} recorded as built by your civilization. Destroyed wonders and merely owning captured wonders do not count."
)
);
assert!(entry.icon.is_none());
}
assert!(
manifest.achievements.iter().all(
|entry| !entry.name.contains("Normal") && !entry.description.contains("Normal")
)
);
}
#[test]
fn every_wonder_requires_surviving_built_record_not_ownership_or_a_win() {
for (wonder, id, _) in WONDERS {
for builder in [0, 1] {
let owner = 1 - builder;
let mut game = finish(setup(GameLength::Standard));
assert!(!has(&game, builder, id));
assert!(!has(&game, owner, id));
// Capturing ownership alone is not a construction record.
let position = game.player(owner).cities[0].position;
let event_player = crate::events::EventPlayer::new(
owner,
EventOrigin::Ability("wonder capture and destruction regression".into()),
);
crate::wonder::gain_wonder(&mut game, &event_player, wonder, position);
crate::wonder::init_wonder(&mut game, owner, wonder);
assert!(!has(&game, owner, id));
game.player_mut(builder).wonders_built.push(wonder);
set_score(&mut game, builder, 10.0);
set_score(&mut game, owner, 100.0);
assert_eq!(achievements(&game)[builder].outcome, "loss");
assert!(has(&game, builder, id), "{id}, builder {builder}");
assert!(!has(&game, owner, id));
for (_, other_id, _) in WONDERS {
assert_eq!(has(&game, builder, other_id), other_id == id);
}
assert!(!has(&game, builder, "two-wonders-built"));
crate::wonder::destroy_wonder(&mut game, &event_player, wonder, position);
assert!(!game.player(builder).wonders_built.contains(&wonder));
assert!(!has(&game, builder, id));
assert!(!has(&game, owner, id));
}
}
}
#[test]
fn destroyed_wonder_no_longer_counts_in_final_built_record() {
let mut game = finish(setup(GameLength::Standard));

View file

@ -1291,6 +1291,43 @@ map city selection and Settler confirmation. Packed-engine protocol and split
WASM bundle checks pass. Existing Clippy warnings and expected rejected-move
WASM diagnostics remain.
# Prepared engine 0.4.151 / achievement manifest revision 2
**Pending independent code/artwork review; do not upload or push release source yet.**
Clash of Cultures (`clash/1`) gains 15 canonical civilization-win achievements,
8 individual surviving wonder-build-record feats and `complete-builder`;
`seven-cities` replaces the removed `four-cities` definition. Standard length
achievement wording is simply Standard. There are 41 definitions. No migration/backfill, rule, practice-policy or viewer
release is included. See `docs/achievements.md` for predicates and eligibility.
Artwork preparation uses the existing source symbols and locked Lucide components:
```sh
npm --prefix web-client run build:achievement-assets
npm --prefix web-client run test:achievement-assets
node web-client/scripts/publish-achievement-assets.mjs # offline dry run only
```
The source/integrity manifest is `release/achievement-assets.json`; generated
256px PNGs, a light/dark contact sheet and their SHA-256 receipt remain ignored
under `.engine/achievement-assets/`. Four legacy PNG provenance records still
require exact-source/license verification; do not treat repository inclusion as
proof of third-party licensing. Lucide notices are included verbatim.
After the code, provenance and exact artwork receipt have independent approval,
upload named assets through the dedicated helper with its explicit publish flag
and reviewed receipt hash. It must verify all 15 public images under the durable
`achievements/clash/achievement-faction-<slug>/...` namespace before the engine
manifest is activated. BGS re-encodes PNG uploads to WebP: verify the **downloaded
WebP** hash and byte length against its URL/metadata, not against the input PNG.
Preserve gallery, other assets and all unrelated metadata. Never change bucket
policy or point icons at viewer-bundle files as a workaround.
Only then release the exact reviewed 0.4.151 engine archive and matching source
using the existing engine-only procedure below. Its packaging/activation receipt
must record source HEAD, both artwork and engine hashes, canonical remote commit,
41 revision-2 definitions, public album visibility, and unchanged hosted viewer.
# Engine 0.4.150 (viewer stays 0.1.217)
Engine-only release for **Clash of Cultures: Monumental edition**, BGS `clash/1`.

View file

@ -7,7 +7,9 @@
"dev": "vite --host 127.0.0.1 --port 8643",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs && npm run test:locales",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs && npm run test:achievement-assets && npm run test:locales",
"build:achievement-assets": "node scripts/build-achievement-assets.mjs",
"test:achievement-assets": "node --test scripts/achievement-assets.test.mjs scripts/publish-achievement-assets.test.mjs",
"build:bridge": "bash scripts/build-bridge.sh",
"publish:bgs": "node scripts/publish.mjs",
"test:locales": "node ../scripts/check-locales.mjs src/localization && node --test scripts/localization-source.test.mjs && npm run localization:check",

View file

@ -0,0 +1,255 @@
{
"revision": 2,
"width": 256,
"height": 256,
"render": {
"background": "#f3f4f6",
"ink": "#18212b",
"emblemSize": 192,
"strokeWidth": 2.5,
"lucideVersion": "0.577.0"
},
"integrity": {
"web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0",
"web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b",
"server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332",
"web-client/package-lock.json": "5c2509542ca8802914b81bf6bc777537c1b95a69f913f6f99aaeae1ae3d5cd6b",
"web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be",
"web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a",
"web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db"
},
"assets": [
{
"civilization": "Rome",
"key": "achievement-faction-rome",
"source": {
"type": "png",
"path": "client/assets/colosseum-rome-svgrepo-com.png",
"sha256": "660f60ac288e2ed97ae208fce824ec4b39681008b68429b82b76f9dfeefb6d67",
"provenance": {
"license": null,
"status": "unresolved — provenance investigation pending; no publication approval",
"originalPath": "client/assets/colosseum-rome-svgrepo-com.png"
}
}
},
{
"civilization": "Greece",
"key": "achievement-faction-greece",
"source": {
"type": "png",
"path": "client/assets/temple-building-with-columns-svgrepo-com.png",
"sha256": "939ab2c36bb3f29aa066348f5ea0f8418e76442f1fcae1537a27ec1706a57e0f",
"provenance": {
"license": null,
"status": "unresolved — provenance investigation pending; no publication approval",
"originalPath": "client/assets/temple-building-with-columns-svgrepo-com.png"
}
}
},
{
"civilization": "China",
"key": "achievement-faction-china",
"source": {
"type": "png",
"path": "client/assets/great-wall-of-china-chinese-svgrepo-com.png",
"sha256": "edc3bfe45c937482fedb708bcd794ed589241f96b095a55daa25be7bb4656e3c",
"provenance": {
"license": null,
"status": "unresolved — provenance investigation pending; no publication approval",
"originalPath": "client/assets/great-wall-of-china-chinese-svgrepo-com.png"
}
}
},
{
"civilization": "Vikings",
"key": "achievement-faction-vikings",
"source": {
"type": "png",
"path": "client/assets/viking-ship-svgrepo-com.png",
"sha256": "a195e2fcafbb2338a6b79c05f55f6c3e5aa64fd68352c30f82e13b8d9094274b",
"provenance": {
"license": null,
"status": "unresolved — provenance investigation pending; no publication approval",
"originalPath": "client/assets/viking-ship-svgrepo-com.png"
}
}
},
{
"civilization": "Babylonia",
"key": "achievement-faction-babylonia",
"source": {
"type": "lucide",
"icon": "Castle",
"path": "web-client/node_modules/lucide-svelte/dist/icons/castle.svelte",
"sha256": "a4728d2a4ffb9f91680aad23e52e69b8889ee5685e81bcecb0f78b34a65dffe1",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "India",
"key": "achievement-faction-india",
"source": {
"type": "lucide",
"icon": "Flower2",
"path": "web-client/node_modules/lucide-svelte/dist/icons/flower-2.svelte",
"sha256": "a326d49e378d4be8ae317ceecac4681862c8b98aba0b6522233ff39c42730852",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Egypt",
"key": "achievement-faction-egypt",
"source": {
"type": "lucide",
"icon": "Pyramid",
"path": "web-client/node_modules/lucide-svelte/dist/icons/pyramid.svelte",
"sha256": "155703be10c462c6a9262a7d16b874fddeae28bd0b12c075b1ad7c41c3d2ce78",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Phoenicia",
"key": "achievement-faction-phoenicia",
"source": {
"type": "lucide",
"icon": "Anchor",
"path": "web-client/node_modules/lucide-svelte/dist/icons/anchor.svelte",
"sha256": "dde616b2f903881bb649122535e6d05dc6e558d778606286e5c5bdea21e1e4d3",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Maya",
"key": "achievement-faction-maya",
"source": {
"type": "lucide",
"icon": "Sunrise",
"path": "web-client/node_modules/lucide-svelte/dist/icons/sunrise.svelte",
"sha256": "9e71ca6595f47c1fc31dd4e6cdf3879ab3b05a222ded44e8e6417cc660c936f1",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Persia",
"key": "achievement-faction-persia",
"source": {
"type": "lucide",
"icon": "Crown",
"path": "web-client/node_modules/lucide-svelte/dist/icons/crown.svelte",
"sha256": "73cc2544bb9e40288bec8195b52bac60a14dcf51d72ca8f34082c656e9ba719c",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Japan",
"key": "achievement-faction-japan",
"source": {
"type": "lucide",
"icon": "Sun",
"path": "web-client/node_modules/lucide-svelte/dist/icons/sun.svelte",
"sha256": "959e560160d0dcfd005484eff0dc78b14aa59969f7e78c9d3175df7c09af1723",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Huns",
"key": "achievement-faction-huns",
"source": {
"type": "lucide",
"icon": "Swords",
"path": "web-client/node_modules/lucide-svelte/dist/icons/swords.svelte",
"sha256": "4e49e51ea49addb5ee156e9fd770d0a8027107411a6a9822476adb497539de5d",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Celts",
"key": "achievement-faction-celts",
"source": {
"type": "lucide",
"icon": "TreePine",
"path": "web-client/node_modules/lucide-svelte/dist/icons/tree-pine.svelte",
"sha256": "94cab10db147c5003f5e9bf027614b1c2ec2f415084043e7bfaf72209c64b1a7",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Aztecs",
"key": "achievement-faction-aztecs",
"source": {
"type": "lucide",
"icon": "Flame",
"path": "web-client/node_modules/lucide-svelte/dist/icons/flame.svelte",
"sha256": "d8c299d553203ea4e7d8633e6893d1cdb388c4866c6c328fb4c6f7ef0b4f4dd3",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
},
{
"civilization": "Carthage",
"key": "achievement-faction-carthage",
"source": {
"type": "lucide",
"icon": "Ship",
"path": "web-client/node_modules/lucide-svelte/dist/icons/ship.svelte",
"sha256": "bc63970b33997f2de8ec077d48c252fc6dd42f03b57735a0e6528e7a38337c49",
"provenance": {
"license": "ISC; Feather-derived portions MIT",
"upstream": "https://github.com/lucide-icons/lucide",
"version": "0.577.0",
"licenseFile": "web-client/release/achievement-assets/LICENSE-lucide.txt"
}
}
}
]
}

View file

@ -0,0 +1,39 @@
ISC License
Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2026 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2026.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
The MIT License (MIT) (for portions derived from Feather)
Copyright (c) 2013-2026 Cole Bemis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,62 @@
# Achievement emblem artwork — local review only
The adjacent `../achievement-assets.json` is the tracked input manifest (revision
2). It binds the 15 playable registry names to the actual canonical emblems in
`src/civilization-emblems.ts`: four PNG masks and eleven Lucide components. NPCs
and the civilization-selection placeholder are excluded. Unknown names never
receive the UI's Landmark fallback. No substitute logos or SVG path copies are
maintained here.
## Generate and verify
From the repository root, using the existing installed web-client dependencies
and Playwright Chromium:
```sh
node web-client/scripts/build-achievement-assets.mjs
node web-client/scripts/build-achievement-assets.mjs --check
node --test web-client/scripts/achievement-assets.test.mjs
```
The builder starts an isolated ephemeral loopback Vite server (not the app's
production configuration), blocks off-origin browser requests, and closes both
server and browser in `finally`. It mounts actual Svelte components with the map
flag's `strokeWidth: 2.5`, serializes them to SVG, then uses the same alpha-mask /
`source-in` coloring technique as `civilization-flags.ts` for both source types.
Each symbol is centered in a 192px box on a 256×256 opaque neutral light-gray
background with dark ink. Standalone badges contain no text. The opaque neutral
background keeps the symbol readable against either light or dark album chrome.
All generated files are ignored under `web-client/.engine/achievement-assets/`:
- `achievement-faction-<lowercase registry name>.png` (15 files)
- `receipt.json`: revision 2, manifest SHA-256, dimensions, Chromium/platform
metadata, and `assets` entries containing `civilization`, `key`, basename
`file`, `sha256`, `width`, `height`
- `contact-sheet.html` and `contact-sheet.png`: labeled independent review sheets
showing all symbols on light and dark surrounds. Labels are not in badge PNGs.
The builder verifies two independent page renders are byte-identical before
writing output. Input hashes, Lucide 0.577.0, dimensions, mapping, and generated
hashes are checked locally. Chromium/platform metadata is recorded because
cross-platform/browser-version rasterization is not claimed byte-identical.
To reproduce release bytes use the same lockfile and recorded Chromium/platform.
The manifest is intentionally not automatically refreshed when canonical sources
change: inspect the changes, review provenance, and deliberately update hashes.
A successful local build is **not** artwork approval or permission to publish.
No uploads are performed by these tools.
## Attribution and unresolved provenance
The eleven Lucide symbols come from `lucide-svelte` **0.577.0**,
https://github.com/lucide-icons/lucide. The full package license is copied verbatim
to `LICENSE-lucide.txt`: ISC, with the included MIT notice for Feather-derived
portions. Preserve these notices with distributions of the derived artwork.
Rome, Greece, China, and Vikings reuse the repository's original PNG assets in
`client/assets/` (exact original paths and SHA-256 hashes are in the manifest).
Their upstream authorship, original download locations, and applicable licenses
are **still under investigation**. Filenames mentioning SVG Repo are not adequate
license evidence. This document does **not** assert that the repository's root
MIT license covers these PNGs. Publication remains blocked pending documented
provenance/license review and independent visual review of the contact sheet.

View file

@ -0,0 +1,36 @@
# Existing PNG provenance investigation (not clearance)
The actual existing PNG masks remain the inputs. Their hashes are pinned in
`../achievement-assets.json`. No substitute illustrations were introduced.
SVG Repo item-page metadata identifies the candidates below, but the original
SVG image requests were blocked or failed to render during verification. A page
name or license label does not prove its image matches a local PNG. **None of
these candidate matches is currently cleared for new publication.**
| Existing symbol | Candidate item pages | Observed page license/provider |
| --- | --- | --- |
| Greece / temple-building-with-columns | <https://www.svgrepo.com/svg/89426/temple-building-with-columns> | CC0; uploader SVG Repo |
| Rome / colosseum-rome | <https://www.svgrepo.com/svg/184166/colosseum-rome>, <https://www.svgrepo.com/svg/184188/colosseum-rome>, <https://www.svgrepo.com/svg/220508/colosseum-rome>, <https://www.svgrepo.com/svg/301824/colosseum-rome>, <https://www.svgrepo.com/svg/301851/colosseum-rome> | CC0; uploader SVG Repo |
| China / great-wall-of-china-chinese | <https://www.svgrepo.com/svg/220522/great-wall-of-china-chinese>, <https://www.svgrepo.com/svg/229211/great-wall-of-china-chinese> | CC0; uploader SVG Repo |
| Vikings / viking-ship | <https://www.svgrepo.com/svg/101379/viking-ship>, <https://www.svgrepo.com/svg/101393/viking-ship>, <https://www.svgrepo.com/svg/157471/viking-ship>, <https://www.svgrepo.com/svg/50060/viking-ship>, <https://www.svgrepo.com/svg/61008/viking-ship>, <https://www.svgrepo.com/svg/86592/viking-ship>, <https://www.svgrepo.com/svg/92309/viking-ship>, <https://www.svgrepo.com/svg/95191/viking-ship> | CC0; uploader SVG Repo |
| Other same-slug Viking candidates | <https://www.svgrepo.com/svg/480728/viking-ship>, <https://www.svgrepo.com/svg/480817/viking-ship> | PD; Icooon Mono |
SVG Repo's license explanation: <https://www.svgrepo.com/page/licensing/>.
CC0 reference: <https://creativecommons.org/publicdomain/zero/1.0/>.
“Uploader SVG Repo” is not a claim that SVG Repo was the original individual artist.
Local silhouettes to match against actual licensed originals:
- Rome: Colosseum facade with tall curved left wall descending to low right wall,
three tiers of cutout arches, wide solid base.
- Greece: triangular pediment, three columns with separate capitals, stepped base.
- China: winding wall leading from foreground toward upper left, battlement tower
at upper right with arched opening.
- Vikings: dragon head at left, curled stern right, large filled sail, horizontal
yard and small flag above it.
The Greek candidate page's license was additionally confirmed via a rendered page
capture, but its main artwork was a broken image. Do not treat that capture as a
successful visual match. Exact item IDs, image correspondence evidence and relevant
license/attribution terms must be reviewed before clearing the manifest records.

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-server",
"version": "0.4.150",
"version": "0.4.151",
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
"license": "MIT",
"type": "commonjs",

View file

@ -0,0 +1,119 @@
import { readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import assert from 'node:assert/strict';
export const root = fileURLToPath(new URL('../../', import.meta.url));
export const webRoot = path.join(root, 'web-client');
export const outputDir = path.join(webRoot, '.engine/achievement-assets');
export const manifestPath = path.join(webRoot, 'release/achievement-assets.json');
export const sha256 = (data) => createHash('sha256').update(data).digest('hex');
export const read = (file) => readFile(path.join(root, file));
export const settings = {
background: '#f3f4f6',
ink: '#18212b',
emblemSize: 192,
strokeWidth: 2.5,
lucideVersion: '0.577.0',
};
// Deliberately strict: changes to the canonical declarations require explicit review,
// never silently accepting civilizationIcon's generic Landmark fallback.
export async function canonicalAssets() {
const text = (await read('web-client/src/civilization-emblems.ts')).toString();
const imports = new Map([...text.matchAll(/import (\w+) from '([^']+\.png)';/g)].map((m) => [m[1], m[2]]));
const icons = new Map(
[...text.match(/const icons:[\s\S]*?= \{([\s\S]*?)\};/)[1].matchAll(/(\w+): (\w+),/g)].map((m) => [
m[1],
m[2],
]),
);
const images = new Map(
[
...text
.match(/export const civilizationImages:[\s\S]*?= \{([\s\S]*?)\};/)[1]
.matchAll(/(\w+): (\w+),/g),
].map((m) => [m[1], m[2]]),
);
const registry = (await read('server/src/content/civilizations.rs')).toString();
const slugs = [...registry.matchAll(/^\s+(\w+)::\1\(\),/gm)].map((m) => m[1]);
assert.equal(slugs.length, 15, 'Playable registry must contain exactly 15 civilizations');
const names = [...icons.keys(), ...images.keys()].filter((name) => slugs.includes(name.toLowerCase()));
assert.equal(names.length, 15, 'Canonical emblems must cover every playable civilization');
return slugs.map((slug) => {
const civilization = names.find((name) => name.toLowerCase() === slug);
assert.ok(civilization, `Missing canonical emblem: ${slug}`);
let source;
if (images.has(civilization)) {
const imported = imports.get(images.get(civilization));
assert.ok(imported, `Missing PNG import: ${civilization}`);
source = { type: 'png', path: path.posix.normalize(`web-client/src/${imported}`) };
} else {
const icon = icons.get(civilization);
assert.ok(icon && icon !== 'Landmark', `Unknown civilization: ${civilization}`);
const kebab = icon.replace(/([a-z])([A-Z0-9])/g, '$1-$2').toLowerCase();
source = {
type: 'lucide',
icon,
path: `web-client/node_modules/lucide-svelte/dist/icons/${kebab}.svelte`,
};
}
return { civilization, key: `achievement-faction-${slug}`, source };
});
}
export async function validateInputs(manifest) {
manifest ??= JSON.parse(await readFile(manifestPath, 'utf8'));
assert.equal(manifest.revision, 2);
assert.equal(manifest.width, 256);
assert.equal(manifest.height, 256);
assert.deepEqual(manifest.render, settings);
const canonical = await canonicalAssets();
assert.deepEqual(
manifest.assets.map(({ civilization, key, source }) => ({
civilization,
key,
source: Object.fromEntries(
Object.keys(canonical.find((a) => a.key === key)?.source ?? {}).map((k) => [k, source[k]]),
),
})),
canonical,
);
for (const asset of manifest.assets)
assert.equal(sha256(await read(asset.source.path)), asset.source.sha256, `Source changed: ${asset.key}`);
for (const [file, hash] of Object.entries(manifest.integrity))
assert.equal(sha256(await read(file)), hash, `Input changed: ${file}`);
const pkg = JSON.parse(await read('web-client/node_modules/lucide-svelte/package.json'));
assert.equal(pkg.version, settings.lucideVersion);
assert.equal(
(await read('web-client/release/achievement-assets/LICENSE-lucide.txt')).toString(),
(await read('web-client/node_modules/lucide-svelte/LICENSE')).toString(),
);
return manifest;
}
export function pngDimensions(bytes) {
assert.equal(bytes.subarray(0, 8).toString('hex'), '89504e470d0a1a0a');
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
}
export async function validateOutputs(directory = outputDir) {
const manifest = await validateInputs();
const receipt = JSON.parse(await readFile(path.join(directory, 'receipt.json'), 'utf8'));
assert.equal(receipt.revision, 2);
assert.equal(receipt.manifestSha256, sha256(await readFile(manifestPath)));
assert.deepEqual(
receipt.assets.map(({ civilization, key }) => ({ civilization, key })),
manifest.assets.map(({ civilization, key }) => ({ civilization, key })),
);
for (const asset of receipt.assets) {
assert.equal(asset.file, `${asset.key}.png`);
const bytes = await readFile(path.join(directory, asset.file));
assert.equal(sha256(bytes), asset.sha256);
assert.deepEqual(pngDimensions(bytes), { width: 256, height: 256 });
assert.equal(asset.width, 256);
assert.equal(asset.height, 256);
}
return receipt;
}

View file

@ -0,0 +1,77 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { access, mkdtemp, cp, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { canonicalAssets, validateInputs, validateOutputs, outputDir } from './achievement-asset-inputs.mjs';
test('all 15 playable registry names have canonical emblems, four PNGs and eleven Lucide icons', async () => {
const canonical = await canonicalAssets();
assert.equal(canonical.length, 15);
assert.equal(canonical.filter((a) => a.source.type === 'png').length, 4);
assert.equal(canonical.filter((a) => a.source.type === 'lucide').length, 11);
assert.equal(new Set(canonical.map((a) => a.key)).size, 15);
for (const a of canonical) {
assert.match(a.key, /^achievement-faction-[a-z]+$/);
assert.ok(!['Barbarians', 'Pirates', 'Choose Civilization'].includes(a.civilization));
assert.notEqual(a.source.icon, 'Landmark');
}
await validateInputs();
});
test('unknown factions, NPCs, omitted assets, wrong icon and changed source hashes fail closed', async () => {
const original = await validateInputs();
for (const mutate of [
(m) => {
m.assets[0].civilization = 'Atlantis';
},
(m) => {
m.assets[0].civilization = 'Pirates';
},
(m) => {
m.assets.pop();
},
(m) => {
m.assets.find((a) => a.source.type === 'lucide').source.icon = 'Landmark';
},
(m) => {
m.assets[0].source.sha256 = '0'.repeat(64);
},
(m) => {
m.render.lucideVersion = 'latest';
},
]) {
const changed = structuredClone(original);
mutate(changed);
await assert.rejects(validateInputs(changed));
}
});
let generated = true;
try {
await access(path.join(outputDir, 'receipt.json'));
} catch {
generated = false;
}
test(
'generated PNG dimensions and hashes match receipt (run build first)',
{ skip: !generated },
async () => {
const receipt = await validateOutputs();
assert.equal(receipt.renderer.reproducibility, 'two independent page renders byte-identical');
},
);
test('generated byte tampering is rejected', { skip: !generated }, async () => {
const directory = await mkdtemp(path.join(tmpdir(), 'achievement-assets-test-'));
try {
await cp(outputDir, directory, { recursive: true });
const receipt = await validateOutputs(directory);
const file = path.join(directory, receipt.assets[0].file);
const bytes = await readFile(file);
bytes[bytes.length - 1] ^= 1;
await writeFile(file, bytes);
await assert.rejects(validateOutputs(directory));
} finally {
await rm(directory, { recursive: true, force: true });
}
});

View file

@ -0,0 +1,175 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { createServer } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { chromium } from 'playwright';
import { createServer as createHttpServer } from 'node:http';
import {
webRoot,
root,
outputDir,
manifestPath,
sha256,
validateInputs,
validateOutputs,
pngDimensions,
} from './achievement-asset-inputs.mjs';
import assert from 'node:assert/strict';
const manifest = await validateInputs();
if (process.argv.includes('--check')) {
await validateOutputs();
console.log('Achievement asset inputs and generated receipt verified.');
} else {
let server, browser, httpServer;
try {
server = await createServer({
configFile: false,
appType: 'custom',
root: webRoot,
publicDir: false,
plugins: [
svelte(),
{
name: 'achievement-svelte-runtime',
resolveId(id) {
if (id === '/achievement-runtime.js') return '\0achievement-runtime';
},
load(id) {
if (id === '\0achievement-runtime') return "export { mount, unmount, flushSync } from 'svelte';";
},
},
],
server: {
middlewareMode: true,
hmr: false,
watch: { ignored: ['**/.engine/**'] },
fs: { allow: [root] },
},
cacheDir: path.join(webRoot, '.engine/achievement-assets-vite'),
});
server.middlewares.use('/achievement-render', (_req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<!doctype html><html><body></body></html>');
});
httpServer = createHttpServer(server.middlewares);
await new Promise((resolve) => httpServer.listen(0, '127.0.0.1', resolve));
const origin = `http://127.0.0.1:${httpServer.address().port}`;
browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 1100 }, deviceScaleFactor: 1 });
await page.route('**/*', (route) =>
new URL(route.request().url()).origin === origin ? route.continue() : route.abort(),
);
await page.goto(`${origin}/achievement-render`);
// Use the actual canonical Svelte component, serializing SVG exactly as the
// map flags do. PNGs and SVGs both use their alpha as source-in ink masks.
const render = async () =>
page.evaluate(async (manifest) => {
const { civilizationImages, civilizationIcon } = await import('/src/civilization-emblems.ts');
const { mount, unmount, flushSync } = await import('/achievement-runtime.js');
const results = [];
for (const asset of manifest.assets) {
// validateInputs has already matched every name and source to the
// canonical registry; this loop cannot request the fallback icon.
let source = civilizationImages[asset.civilization];
if (asset.source.type === 'lucide') {
if (source) throw new Error('Unexpected canonical PNG');
const target = document.createElement('div');
const icon = mount(civilizationIcon(asset.civilization), {
target,
props: { size: 128, color: '#000', strokeWidth: manifest.render.strokeWidth },
});
flushSync();
const svg = target.querySelector('svg');
if (!svg) throw new Error('Missing canonical SVG');
source = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(svg))}`;
await unmount(icon);
}
if (!source) throw new Error('Missing canonical emblem');
const image = new Image();
image.src = source;
await image.decode();
const size = manifest.render.emblemSize;
const mask = document.createElement('canvas');
mask.width = mask.height = size;
const ink = mask.getContext('2d');
const scale = size / Math.max(image.naturalWidth, image.naturalHeight);
const w = image.naturalWidth * scale,
h = image.naturalHeight * scale;
ink.drawImage(image, (size - w) / 2, (size - h) / 2, w, h);
ink.globalCompositeOperation = 'source-in';
ink.fillStyle = manifest.render.ink;
ink.fillRect(0, 0, size, size);
const canvas = document.createElement('canvas');
canvas.width = manifest.width;
canvas.height = manifest.height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = manifest.render.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(mask, (canvas.width - size) / 2, (canvas.height - size) / 2);
results.push({ key: asset.key, data: canvas.toDataURL('image/png').split(',')[1] });
}
return results;
}, manifest);
const first = await render();
// Independent reload ensures no retained component/canvas state affects bytes.
await page.reload();
assert.deepEqual(await render(), first, 'PNG generation must be byte-reproducible');
await mkdir(outputDir, { recursive: true });
const assets = [];
for (let i = 0; i < first.length; i++) {
const bytes = Buffer.from(first[i].data, 'base64');
const dimensions = pngDimensions(bytes);
assert.deepEqual(dimensions, { width: 256, height: 256 });
const asset = manifest.assets[i];
const file = `${asset.key}.png`;
await writeFile(path.join(outputDir, file), bytes);
assets.push({
civilization: asset.civilization,
key: asset.key,
file,
sha256: sha256(bytes),
...dimensions,
});
}
const receipt = {
revision: 2,
manifestSha256: sha256(await readFile(manifestPath)),
width: 256,
height: 256,
renderer: {
chromium: browser.version(),
platform: process.platform,
arch: process.arch,
reproducibility: 'two independent page renders byte-identical',
},
assets,
};
await writeFile(path.join(outputDir, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
const cards = assets
.map(
(a, i) =>
`<figure><img src="data:image/png;base64,${first[i].data}"><figcaption>${a.civilization}<br><small>${a.key}</small></figcaption></figure>`,
)
.join('');
const html = `<!doctype html><meta charset="utf-8"><title>Achievement artwork review — local only</title><style>body{font:16px sans-serif;margin:24px;background:#fff;color:#18212b}section{display:grid;grid-template-columns:repeat(5,1fr);gap:16px;padding:16px}figure{margin:0;text-align:center}img{width:192px;height:192px}figcaption{padding:8px}small{font-size:11px}.dark{background:#18212b;color:#fff}</style><h1>Local achievement artwork review</h1><p>15 canonical symbols. PNG provenance unresolved; not publication approval.</p><section>${cards}</section><h2>Dark surround</h2><section class="dark">${cards}</section>`;
await writeFile(path.join(outputDir, 'contact-sheet.html'), html);
await page.setContent(html);
await page.screenshot({ path: path.join(outputDir, 'contact-sheet.png'), fullPage: true });
await validateOutputs();
console.log(`Generated and verified 15 badges + contact-sheet.html/png + receipt.json in ${outputDir}`);
} finally {
try {
await browser?.close();
} finally {
try {
await server?.close();
} finally {
if (httpServer)
await new Promise((resolve, reject) =>
httpServer.close((error) => (error ? reject(error) : resolve())),
);
}
}
}
}

View file

@ -0,0 +1,238 @@
// Offline by default. This tool only writes named assets, never game metadata,
// gallery, engine releases, activation, or viewer configuration.
import assert from 'node:assert/strict';
import { readFile, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { validateInputs, validateOutputs, outputDir, sha256 } from './achievement-asset-inputs.mjs';
const admin = 'https://admin.boardgamers.space/api/admin';
const publicInfo = 'https://boardgamers.space/api/boardgame/clash/info/latest';
const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
const hashPattern = /^[a-f0-9]{64}$/;
const keyPattern = /^achievement-faction-[a-z]+$/;
function httpsUrl(value) {
try {
const url = new URL(value);
return url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash;
} catch {
return false;
}
}
// License clearance is a human review, not inferred from a filename or an icon
// site's general license. PNG provenance must contain:
// license: nonempty license identifier/text; sourceUrl: exact HTTPS artwork URL;
// verification: { sourceUrl, sourceSha256, license, evidence }.
// The first three verification fields must match this source exactly; evidence
// is a nonempty reviewer-authored citation/explanation of the artwork match and
// license check. Changing provenance requires regenerating/reviewing the receipt.
export function licenseBlockers(manifest) {
return manifest.assets.flatMap(({ key, source }) => {
const p = source.provenance ?? {};
const errors = [];
if (!nonempty(p.license)) errors.push('missing license');
if (source.type === 'png') {
if (!httpsUrl(p.sourceUrl)) errors.push('missing unsigned HTTPS sourceUrl');
const v = p.verification;
if (
!v ||
v.sourceUrl !== p.sourceUrl ||
v.sourceSha256 !== source.sha256 ||
v.license !== p.license ||
!nonempty(v.evidence)
) {
errors.push('missing matched verification evidence');
}
} else if (source.type !== 'lucide') errors.push('unsupported source type');
return errors.map((reason) => ({ key, reason }));
});
}
export function validateReview(manifest, receipt, receiptBytes, reviewedSha256) {
assert.ok(hashPattern.test(reviewedSha256 ?? ''), 'Explicit reviewed receipt SHA-256 required');
assert.equal(sha256(receiptBytes), reviewedSha256, 'Reviewed receipt hash mismatch');
assert.deepEqual(JSON.parse(receiptBytes.toString()), receipt, 'Receipt changed during validation');
assert.equal(receipt.revision, 2);
assert.deepEqual(
receipt.assets.map(({ key, civilization }) => ({ key, civilization })),
manifest.assets.map(({ key, civilization }) => ({ key, civilization })),
'Unexpected asset key',
);
assert.equal(new Set(receipt.assets.map((a) => a.key)).size, receipt.assets.length);
assert.ok(receipt.assets.length > 0);
for (const asset of receipt.assets) {
assert.ok(keyPattern.test(asset.key), 'Unexpected asset key');
assert.equal(asset.file, `${asset.key}.png`);
assert.ok(hashPattern.test(asset.sha256), 'Invalid local hash');
assert.equal(asset.width, 256);
assert.equal(asset.height, 256);
}
assert.equal(licenseBlockers(manifest).length, 0, 'Unresolved source licenses; publication blocked');
}
export function validateHostedAsset(asset, key) {
assert.ok(keyPattern.test(key), 'Unexpected asset key');
assert.ok(asset && httpsUrl(asset.url), 'Hosted URL must be unsigned HTTPS');
const url = new URL(asset.url);
// Production stores public objects below the bucket path, not the host root.
// A storage endpoint change requires review; never follow arbitrary returned URLs.
assert.equal(url.origin, 'https://s3.fr-par.scw.cloud', 'Unexpected storage origin');
assert.equal(asset.contentType, 'image/webp', 'Unexpected asset metadata content type');
const match = url.pathname.match(
new RegExp(`^/bgs-assets/achievements/clash/${key}/([a-f0-9]{16})/${key}\\.webp$`),
);
assert.ok(match, 'Unexpected hosted asset namespace/key');
assert.ok(Number.isSafeInteger(asset.size) && asset.size > 0, 'Invalid hosted size');
return match[1];
}
export function assertPreserved(before, after, keys) {
const unrelated = (value) => {
const copy = structuredClone(value);
delete copy.updatedAt; // Server-maintained timestamp may change on named-asset writes.
for (const key of keys) if (copy.assets) delete copy.assets[key];
return copy;
};
assert.deepEqual(unrelated(after), unrelated(before), 'Unrelated metadata/gallery/assets changed');
}
async function loadLocal() {
const manifest = await validateInputs();
const receipt = await validateOutputs();
const receiptBytes = await readFile(path.join(outputDir, 'receipt.json'));
// Freeze every upload in memory before credentials or network are touched.
const files = new Map();
for (const asset of receipt.assets) {
assert.equal(asset.file, `${asset.key}.png`);
const bytes = await readFile(path.join(outputDir, asset.file));
assert.equal(sha256(bytes), asset.sha256, 'Output changed during validation');
files.set(asset.key, bytes);
}
return { manifest, receipt, receiptBytes, files };
}
export async function run(args = [], dependencies = {}) {
assert.ok(
args.every((a) => a === '--publish' || a === '--dry-run' || /^--reviewed-sha256=[a-f0-9]{64}$/.test(a)),
'Unknown or malformed argument',
);
assert.ok(!(args.includes('--publish') && args.includes('--dry-run')), 'Conflicting modes');
assert.ok(args.filter((a) => a.startsWith('--reviewed-sha256=')).length <= 1, 'Duplicate review hash');
const local = await (dependencies.loadLocal ?? loadLocal)();
const { manifest, receipt, receiptBytes, files } = local;
const blockers = licenseBlockers(manifest);
const reviewedSha256 = args.find((a) => a.startsWith('--reviewed-sha256='))?.split('=')[1];
const report = {
mode: 'offline-dry-run',
receiptSha256: sha256(receiptBytes),
assets: receipt.assets.length,
blockers,
};
if (!args.includes('--publish')) return report;
validateReview(manifest, receipt, receiptBytes, reviewedSha256);
for (const asset of receipt.assets) {
assert.ok(Buffer.isBuffer(files.get(asset.key)), 'Missing frozen PNG');
assert.equal(sha256(files.get(asset.key)), asset.sha256, 'Frozen output hash mismatch');
}
// Only after ALL local review/license checks pass do we read credentials.
const token = (
await (
dependencies.readToken ??
(async () => process.env.BGS_ADMIN_TOKEN ?? (await readFile(path.join(homedir(), '.bgs'), 'utf8')))
)()
).trim();
assert.ok(token.length > 0, 'Missing admin token');
const fetcher = dependencies.fetch ?? globalThis.fetch;
const save =
dependencies.save ??
((data) =>
writeFile(path.join(outputDir, 'upload-receipt.json'), JSON.stringify(data, null, 2) + '\n', {
mode: 0o600,
}));
// Never echo remote bodies, errors, headers, or tokens (including fetch errors).
try {
async function request(url, options = {}) {
const response = await fetcher(url, {
redirect: 'error',
signal: AbortSignal.timeout(60000),
...options,
});
if (!response.ok) throw new Error('Request failed');
return response;
}
async function api(endpoint, body) {
return (
await request(`${admin}${endpoint}`, {
method: body ? 'PUT' : 'GET',
headers: { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'image/png' } : {}) },
...(body ? { body } : {}),
})
).json();
}
const before = await api('/gameinfo/clash/meta');
const gameBefore = await api('/gameinfo/clash/1');
const uploads = [];
const evidence = {
formatRevision: 1,
achievementRevision: receipt.revision,
reviewedReceiptSha256: reviewedSha256,
assets: uploads,
status: 'incomplete',
};
await save(evidence);
for (const localAsset of receipt.assets) {
const { key } = localAsset;
const metadata = await api(
`/gameinfo/clash/assets/${key}?name=${encodeURIComponent(key + '.png')}`,
files.get(key),
);
const asset = metadata.assets?.[key];
const prefix = validateHostedAsset(asset, key);
// No Authorization header, cookies, or redirects for public verification.
const hosted = await request(asset.url, { credentials: 'omit' });
assert.equal(hosted.headers.get('content-type')?.split(';')[0].trim().toLowerCase(), 'image/webp');
const bytes = Buffer.from(await hosted.arrayBuffer());
assert.equal(bytes.length, asset.size);
assert.equal(bytes.subarray(0, 4).toString(), 'RIFF');
assert.equal(bytes.subarray(8, 12).toString(), 'WEBP');
const hash = sha256(bytes);
assert.equal(hash.slice(0, 16), prefix);
uploads.push({ key, url: asset.url, size: asset.size, sha256: hash, localSha256: localAsset.sha256 });
await save(evidence);
}
const after = await api('/gameinfo/clash/meta');
const gameAfter = await api('/gameinfo/clash/1');
const keys = receipt.assets.map((a) => a.key);
assertPreserved(before, after, keys);
assertPreserved(gameBefore, gameAfter, keys);
const published = await (await request(publicInfo, { credentials: 'omit' })).json();
for (const asset of uploads) {
for (const info of [after, gameAfter, published]) {
assert.equal(info.assets?.[asset.key]?.url, asset.url);
assert.equal(info.assets?.[asset.key]?.size, asset.size);
}
}
evidence.status = 'verified';
await save(evidence);
return evidence;
} catch {
throw new Error(
'Publication/verification failed; uploads may be partial. Inspect the local upload receipt; no activation was performed.',
);
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try {
console.log(JSON.stringify(await run(process.argv.slice(2)), null, 2));
} catch {
console.error(
'Achievement asset validation/publication failed. Run offline dry-run to check inputs and license blockers. No activation was performed.',
);
process.exitCode = 1;
}
}

View file

@ -0,0 +1,259 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
run,
licenseBlockers,
validateReview,
validateHostedAsset,
assertPreserved,
} from './publish-achievement-assets.mjs';
import { sha256 } from './achievement-asset-inputs.mjs';
const key = 'achievement-faction-rome';
const png = Buffer.from('frozen PNG fixture; real PNG validation is performed by validateOutputs');
const webp = Buffer.from('RIFF\x08\x00\x00\x00WEBPtest');
const hosted = {
url: `https://s3.fr-par.scw.cloud/bgs-assets/achievements/clash/${key}/${sha256(webp).slice(0, 16)}/${key}.webp`,
size: webp.length,
contentType: 'image/webp',
};
function fixture(type = 'lucide') {
const source = { type, sha256: sha256(png), provenance: { license: 'ISC' } };
const manifest = { assets: [{ key, civilization: 'Rome', source }] };
const receipt = {
revision: 2,
manifestSha256: sha256(JSON.stringify(manifest)),
assets: [{ key, civilization: 'Rome', file: `${key}.png`, sha256: sha256(png), width: 256, height: 256 }],
};
return {
manifest,
receipt,
receiptBytes: Buffer.from(JSON.stringify(receipt)),
files: new Map([[key, png]]),
};
}
const publishArgs = (local) => ['--publish', `--reviewed-sha256=${sha256(local.receiptBytes)}`];
function offlineDeps(local) {
return {
loadLocal: async () => local,
readToken: () => {
throw Error('credential read forbidden');
},
fetch: () => {
throw Error('network forbidden');
},
};
}
test('default dry-run is offline, does not read credentials and reports unresolved PNG provenance', async () => {
const local = fixture('png');
local.manifest.assets[0].source.provenance.license = null;
const result = await run([], offlineDeps(local));
assert.equal(result.mode, 'offline-dry-run');
assert.equal(result.blockers.length, 3);
assert.equal(result.receiptSha256, sha256(local.receiptBytes));
});
test('publication refuses missing review, mismatched review, missing licenses before credentials/network', async () => {
const local = fixture();
await assert.rejects(run(['--publish'], offlineDeps(local)), /reviewed receipt/);
await assert.rejects(
run(['--publish', `--reviewed-sha256=${'0'.repeat(64)}`], offlineDeps(local)),
/hash mismatch/,
);
local.manifest.assets[0].source.provenance.license = null;
await assert.rejects(run(publishArgs(local), offlineDeps(local)), /Unresolved source licenses/);
});
test('PNG clearance requires source URL, exact license/source hash match, and evidence', () => {
const { manifest } = fixture('png');
const source = manifest.assets[0].source;
source.provenance = {
license: 'CC0-1.0',
sourceUrl: 'https://example.org/art/rome',
verification: {
sourceUrl: 'https://example.org/art/rome',
sourceSha256: source.sha256,
license: 'CC0-1.0',
evidence: 'Reviewer matched artwork and license on the source page.',
},
};
assert.deepEqual(licenseBlockers(manifest), []);
for (const field of ['sourceUrl', 'sourceSha256', 'license', 'evidence']) {
const changed = structuredClone(manifest);
changed.assets[0].source.provenance.verification[field] = '';
assert.ok(licenseBlockers(changed).length > 0, field);
}
});
test('review rejects changed receipt, unexpected key and invalid dimensions', () => {
const local = fixture();
const validate = () =>
validateReview(local.manifest, local.receipt, local.receiptBytes, sha256(local.receiptBytes));
validate();
local.receipt.assets[0].width = 255;
assert.throws(validate, /Receipt changed/);
local.receiptBytes = Buffer.from(JSON.stringify(local.receipt));
assert.throws(validate);
local.receipt.assets[0].width = 256;
local.receipt.assets[0].key = 'unrelated-key';
local.receiptBytes = Buffer.from(JSON.stringify(local.receipt));
assert.throws(validate, /Unexpected asset key/);
});
test('frozen output mismatch blocks all network', async () => {
const local = fixture();
local.files.set(key, Buffer.from('changed'));
await assert.rejects(run(publishArgs(local), offlineDeps(local)), /Frozen output hash mismatch/);
});
test('URL validation fails closed for HTTP, signatures, credentials, wrong namespace/key, path tricks and sizes', () => {
assert.equal(validateHostedAsset(hosted, key), sha256(webp).slice(0, 16));
for (const url of [
hosted.url.replace('https:', 'http:'),
hosted.url + '?token=secret',
hosted.url + '#fragment',
hosted.url.replace('s3.fr-par.scw.cloud', 'user:pass@s3.fr-par.scw.cloud'),
hosted.url.replace('/achievements/', '/gallery/'),
hosted.url.replace('/clash/', '/other/'),
hosted.url.replaceAll(key, 'achievement-faction-greece'),
hosted.url.replace('/clash/', '/%63lash/'),
hosted.url.replace('s3.fr-par.scw.cloud', '127.0.0.1'),
hosted.url.replace('s3.fr-par.scw.cloud', 'localhost'),
hosted.url.replace('/bgs-assets/', '/'),
hosted.url.replace('s3.fr-par.scw.cloud', 'untrusted.example'),
])
assert.throws(() => validateHostedAsset({ ...hosted, url }, key));
assert.throws(() => validateHostedAsset(hosted, 'unexpected-key'));
assert.throws(() => validateHostedAsset({ ...hosted, size: '16' }, key));
assert.throws(() => validateHostedAsset({ ...hosted, contentType: 'image/png' }, key));
});
test('preservation checks compare full GETs including gallery and unrelated assets', () => {
const before = {
title: 'Clash',
gallery: [{ asset: 'cover' }],
assets: { cover: { url: 'original' } },
updatedAt: 1,
};
const after = structuredClone(before);
after.updatedAt = 2;
after.assets[key] = hosted;
assertPreserved(before, after, [key]);
for (const change of [
(v) => v.gallery.push({ asset: key }),
(v) => (v.title = 'changed'),
(v) => (v.assets.cover.url = 'changed'),
(v) => (v.assets.unexpected = hosted),
]) {
const altered = structuredClone(after);
change(altered);
assert.throws(() => assertPreserved(before, altered, [key]));
}
});
function mockPublication(local, mutate = () => {}) {
const calls = [],
saved = [];
const baseline = { title: 'Clash', gallery: [], assets: { unrelated: { url: 'keep' } } };
let uploaded = false;
const current = () => ({
...baseline,
assets: { ...baseline.assets, ...(uploaded ? { [key]: hosted } : {}) },
});
const deps = {
loadLocal: async () => local,
readToken: async () => 'SECRET-DO-NOT-LOG',
save: async (value) => saved.push(structuredClone(value)),
fetch: async (url, options) => {
calls.push({ url, options });
let value;
if (options.method === 'PUT') {
uploaded = true;
value = current();
} else if (url === hosted.url) {
const response = new Response(webp, { headers: { 'Content-Type': 'image/webp' } });
return mutate(url, response) ?? response;
} else value = current();
value = mutate(url, value) ?? value;
return new Response(JSON.stringify(value), { headers: { 'Content-Type': 'application/json' } });
},
};
return { deps, calls, saved };
}
test('mock publication uploads only reviewed PNGs, downloads anonymously, verifies full GETs, saves hashes without token', async () => {
const local = fixture();
const { deps, calls, saved } = mockPublication(local);
const result = await run(publishArgs(local), deps);
assert.equal(result.status, 'verified');
assert.equal(result.assets[0].sha256, sha256(webp));
assert.equal(result.reviewedReceiptSha256, sha256(local.receiptBytes));
const writes = calls.filter((c) => c.options.method === 'PUT');
assert.equal(writes.length, 1);
assert.equal(
writes[0].url,
`https://admin.boardgamers.space/api/admin/gameinfo/clash/assets/${key}?name=${key}.png`,
);
assert.equal(writes[0].options.headers['Content-Type'], 'image/png');
assert.deepEqual(writes[0].options.body, png);
for (const call of calls.filter((c) => !c.url.includes('/api/admin/'))) {
assert.equal(call.options.headers, undefined);
assert.equal(call.options.credentials, 'omit');
assert.equal(call.options.redirect, 'error');
}
assert.equal(calls.filter((c) => c.url.endsWith('/meta')).length, 2);
assert.equal(calls.filter((c) => c.url.endsWith('/clash/1')).length, 2);
assert.ok(calls.some((c) => c.url.endsWith('/api/boardgame/clash/info/latest')));
assert.ok(!JSON.stringify(saved).includes('SECRET'));
assert.equal(saved.at(-1).status, 'verified');
});
test('bad download hashes, content type, length, response key and public info mismatch fail verification', async () => {
for (const mutate of [
(url, value) =>
url === hosted.url
? new Response(Buffer.from('RIFF\x08\x00\x00\x00WEBPfail'), {
headers: { 'Content-Type': 'image/webp' },
})
: value,
(url, value) =>
url === hosted.url ? new Response(webp, { headers: { 'Content-Type': 'image/png' } }) : value,
(url, value) =>
url === hosted.url
? new Response(webp.subarray(0, 12), { headers: { 'Content-Type': 'image/webp' } })
: value,
(url, value) => (url.includes('?name=') ? { assets: { unexpected: hosted } } : value),
(url, value) => (url.endsWith('/info/latest') ? { assets: {} } : value),
]) {
const local = fixture();
const { deps, saved } = mockPublication(local, mutate);
await assert.rejects(run(publishArgs(local), deps), /Publication\/verification failed/);
assert.notEqual(saved.at(-1)?.status, 'verified');
}
});
test('remote errors are not leaked even when fetch includes Authorization in its exception', async () => {
const local = fixture();
const { deps } = mockPublication(local);
deps.fetch = async (_url, options) => {
throw Error(JSON.stringify(options));
};
await assert.rejects(
run(publishArgs(local), deps),
(error) => !error.message.includes('SECRET') && !error.stack.includes('Bearer'),
);
});
test('unknown flags and contradictory modes fail closed', async () => {
for (const args of [['--force'], ['--publish', '--dry-run'], ['--reviewed-sha256=bad']]) {
await assert.rejects(
run(args, {
loadLocal: () => {
throw Error('should not load');
},
}),
/argument|modes/,
);
}
});

View file

@ -20,9 +20,26 @@ const finish = () => engine.tryMove(fixture, JSON.stringify({ Playing: 'EndTurn'
test('WASM achievement catalog follows official protocol 0.11.0', () => {
const manifest = achievementManifestSchema.parse(hooks.achievementDefinitions());
assert.equal(manifest.revision, 1);
assert.equal(manifest.achievements.length, 17);
assert.equal(manifest.revision, 2);
assert.equal(manifest.achievements.length, 41);
assert.ok(!manifest.achievements.some((a) => a.id === 'four-cities'));
assert.ok(manifest.achievements.some((a) => a.id === 'seven-cities'));
assert.ok(manifest.achievements.some((a) => a.id === 'complete-builder'));
assert.equal(manifest.achievements.find((a) => a.id === 'complete-standard')?.name, 'Complete Standard');
assert.equal(manifest.achievements.find((a) => a.id === 'win-standard')?.name, 'Win Standard');
assert.ok(manifest.achievements.every((a) => !/\bNormal\b/.test(`${a.name} ${a.description}`)));
assert.deepEqual(hooks.achievementDefinitions(), manifest);
const art = JSON.parse(
readFileSync(new URL('../release/achievement-assets.json', import.meta.url), 'utf8'),
);
assert.equal(art.revision, manifest.revision);
assert.deepEqual(
manifest.achievements
.filter((a) => a.icon?.type === 'asset')
.map((a) => (a.icon!.type === 'asset' ? a.icon!.key : ''))
.sort(),
art.assets.map((a: { key: string }) => a.key).sort(),
);
for (const length of ['shorter', 'standard', 'roll-to-end', 'wonderful-ending', 'epic']) {
for (const verb of ['complete', 'win'])
assert.ok(manifest.achievements.some((a) => a.id === `${verb}-${length}`));
@ -100,6 +117,162 @@ test('all length options survive the serialized WASM boundary', () => {
}
});
const civilizations = [
'Rome',
'Greece',
'China',
'Vikings',
'Babylonia',
'India',
'Egypt',
'Phoenicia',
'Maya',
'Persia',
'Japan',
'Huns',
'Celts',
'Aztecs',
'Carthage',
];
test('all actual civilizations have distinct faction-win badges and durable named asset keys', () => {
const manifest = hooks.achievementDefinitions();
const factionIds = civilizations.map((name) => `win-${name.toLowerCase()}`);
for (const civilization of civilizations) {
const id = `win-${civilization.toLowerCase()}`;
const definition = manifest.achievements.find((a) => a.id === id)!;
assert.ok(definition, civilization);
assert.deepEqual(definition.icon, {
type: 'asset',
key: `achievement-faction-${civilization.toLowerCase()}`,
});
const data = JSON.parse(finish());
data.players[0].civilization = civilization;
data.players[0].special_victory_points = [
{ points: 100, origin: { Ability: 'faction fixture' }, attribution: 'Events' },
];
const results = achievementResultsSchema(manifest, 2).parse(hooks.achievements(JSON.stringify(data)));
assert.equal(results[0].outcome, 'win');
assert.deepEqual(
results[0].earned.filter((id) => factionIds.includes(id)),
[id],
);
assert.equal(results[1].outcome, 'loss');
assert.deepEqual(
results[1].earned.filter((id) => factionIds.includes(id)),
[],
);
assert.deepEqual(hooks.achievements(engine.stripSecret(JSON.stringify(data), 0)), []);
data.state = 'Playing';
assert.deepEqual(hooks.achievements(JSON.stringify(data)), []);
}
});
test('seven-city badge uses final city count: six fails, seven passes, no retired ID', () => {
for (const count of [6, 7]) {
const data = JSON.parse(finish());
const city = data.players[0].cities[0];
data.players[0].cities = Array.from({ length: count }, (_, i) => ({
...structuredClone(city),
position: `A${i + 1}`,
}));
const results = hooks.achievements(JSON.stringify(data));
assert.equal(results[0].earned.includes('seven-cities'), count === 7);
assert.ok(results.every((r) => !r.earned.includes('four-cities')));
}
});
test('Builder reaches real completion and awards both winner and loser, never ongoing or filtered', () => {
const data = JSON.parse(fixture);
data.options = { ...data.options, variant: 'Builder' };
data.players[0].special_victory_points = [
{ points: 100, origin: { Ability: 'builder fixture' }, attribution: 'Events' },
];
const raw = JSON.stringify(data);
assert.deepEqual(hooks.achievements(raw), []);
const completed = engine.tryMove(raw, JSON.stringify({ Playing: 'EndTurn' }), 0);
assert.equal(engine.ended(completed), true);
const results = hooks.achievements(completed);
assert.equal(results.length, 2);
assert.ok(results.some((r) => r.outcome === 'loss'));
for (const result of results) {
assert.ok(result.earned.includes('complete-builder'));
assert.ok(result.earned.includes('complete-standard'));
}
for (const seat of [undefined, 0, 1])
assert.deepEqual(hooks.achievements(engine.stripSecret(completed, seat)), []);
assert.ok(hooks.achievements(finish()).every((r) => !r.earned.includes('complete-builder')));
});
const wonders = [
['Colosseum', 'great-arena'],
['Pyramids', 'great-pyramids'],
['GreatGardens', 'great-gardens'],
['GreatLibrary', 'great-library'],
['GreatLighthouse', 'great-lighthouse'],
['GreatMausoleum', 'great-mausoleum'],
['GreatStatue', 'great-statue'],
['GreatWall', 'great-wall'],
];
test('each real wonder awards only its surviving builder record, even to a losing original builder', () => {
const manifest = hooks.achievementDefinitions();
assert.deepEqual(
manifest.achievements
.filter((a) => a.id.startsWith('built-'))
.map((a) => a.id)
.sort(),
wonders.map(([, slug]) => `built-${slug}`).sort(),
);
for (const [wonder, slug] of wonders) {
const data = JSON.parse(finish());
for (const player of data.players) {
player.wonders_built = [];
for (const city of player.cities ?? []) if (city.city_pieces) city.city_pieces.wonders = [];
}
assert.ok(hooks.achievements(JSON.stringify(data)).every((r) => !r.earned.includes(`built-${slug}`)));
// The wonder survives in the opponent's city after capture; only seat 0 built it.
data.players[0].wonders_built = [wonder];
data.players[1].cities[0].city_pieces ??= {};
data.players[1].cities[0].city_pieces.wonders = [wonder];
data.players[1].special_victory_points = [
{ points: 100, origin: { Ability: 'wonder fixture' }, attribution: 'Events' },
];
const raw = JSON.stringify(data);
const results = achievementResultsSchema(manifest, 2).parse(hooks.achievements(raw));
assert.equal(results[0].outcome, 'loss');
assert.deepEqual(
results[0].earned.filter((id) => id.startsWith('built-')),
[`built-${slug}`],
);
assert.ok(!results[0].earned.includes('two-wonders-built'));
assert.deepEqual(
results[1].earned.filter((id) => id.startsWith('built-')),
[],
);
assert.deepEqual(hooks.achievements(JSON.stringify(JSON.parse(raw))), results);
assert.deepEqual(hooks.achievements(engine.stripSecret(raw, 0)), []);
// This is the persisted shape after destruction removes both piece and record.
data.players[0].wonders_built = [];
data.players[1].cities[0].city_pieces.wonders = [];
assert.ok(hooks.achievements(JSON.stringify(data)).every((r) => !r.earned.includes(`built-${slug}`)));
data.state = 'Playing';
data.players[0].wonders_built = [wonder];
assert.deepEqual(hooks.achievements(JSON.stringify(data)), []);
}
});
test('ongoing analysis branches and their filtered views do not earn badges', async () => {
const raw = await engine.init(2, [], { variant: 'Builder' }, 'achievement-analysis', {});
assert.equal(engine.canLaunchAnalysisMode(raw), true);
const analysis = engine.createAnalysisScenario(raw, { player: 0, seed: 'achievement-analysis-branch' });
assert.equal(engine.ended(analysis), false);
assert.deepEqual(hooks.achievements(analysis), []);
assert.deepEqual(hooks.achievements(engine.stripSecret(analysis, 0)), []);
// Completed practice/analysis provenance remains a platform eligibility check:
// the engine save has no persistent provenance field.
});
test('filtered snapshots and all-withdrawn completions cannot award achievements', () => {
const finished = finish();
for (const seat of [undefined, 0, 1]) {