Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
# online
|
||||
|
||||
- Incari accounts and the online service, client side (ADR 0058; the wire format is
|
||||
`docs/online-protocol.md`, which the service implements; change both together).
|
||||
- No game, LWJGL or TeaVM types (`BoundaryTest`): `:client`'s `incari.client.online` feeds it the
|
||||
world and draws its screens.
|
||||
- Compiled into the browser build: no reflection, no blocking, nothing TeaVM's class library lacks.
|
||||
Gson's tree API only.
|
||||
- `OnlineService` is game-thread only. The platform's network callbacks are queued and run in
|
||||
`tick()`; proof of work runs on the background executor it's given and reports back the same way.
|
||||
- Never log or keep a password; never log a token or a recovery code. Nothing in the game may wait
|
||||
on the service: every call returns at once and answers through a callback on a later tick.
|
||||
- Test: `./gradlew :online:check`. The vectors in `src/test/resources/incari/online/vectors.json`
|
||||
are shared with the backend.
|
||||
@@ -0,0 +1,33 @@
|
||||
# online: Incari accounts, client side
|
||||
|
||||
## Purpose
|
||||
|
||||
The client's side of Incari's optional online service (ADR 0058): one WebSocket to the service,
|
||||
with back-off and a resumable session, speaking the protocol in
|
||||
[`docs/online-protocol.md`](../docs/online-protocol.md). The service itself is closed source and
|
||||
not in this repository; [`tools/onlinedev`](../tools/onlinedev) stands in for it during development.
|
||||
|
||||
## Entry points
|
||||
|
||||
- `OnlineService`: the connection, sign-up (with `ProofOfWork`), sign-in, `SessionStore`, recovery
|
||||
codes, and everything below. Fills in the framework's `Online` for features.
|
||||
- `WorldPlayers`, `ServerHash`: which players in the world are Incari players, matched by a hash of
|
||||
the server's address so the service never stores a plain list of servers.
|
||||
- `Social`: friends, requests, conversations and blocking (ADR 0059).
|
||||
- `Releases`: the latest release the service names, for the update notice (ADR 0060).
|
||||
- `Catalog`, `Loadout`, `Wardrobe`: cosmetics owned, worn and synced (ADR 0061).
|
||||
- Test fixtures: `FakeService`, an in-process stand-in that answers as the service should.
|
||||
|
||||
The screens live in `client`'s `incari.client.online`; accounts aren't a module.
|
||||
|
||||
## Invariants
|
||||
|
||||
See [`AGENTS.md`](AGENTS.md): no game types, no blocking, game-thread only, and never a password,
|
||||
token or recovery code in a log.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :online:check
|
||||
./gradlew :tools:onlinedev:run --args="--listen 8090" # then the page with ?online=ws://localhost:8090/v1/ws
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
plugins {
|
||||
`java-library`
|
||||
// An in-process stand-in for the service, for the tests and for tools/onlinedev.
|
||||
`java-test-fixtures`
|
||||
}
|
||||
|
||||
// Incari accounts and the online service, client side (ADR 0058): the one WebSocket to the service
|
||||
// and its back-off, the protocol's messages, the session store, sign-up's proof of work, server
|
||||
// hashes, presence and the lookup cache. No game types, so it's tested on the JVM against a fake
|
||||
// service; :client's incari.client.online draws the screens and feeds it the world.
|
||||
dependencies {
|
||||
api(project(":platform-api"))
|
||||
api(project(":framework"))
|
||||
|
||||
// Messages are JSON through Gson's tree API (no reflection). The game ships Gson, so at run time
|
||||
// its copy is on the class path; this is compile-only, as in :framework.
|
||||
compileOnly(libs.gson)
|
||||
|
||||
testFixturesImplementation(libs.gson)
|
||||
testImplementation(libs.gson)
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testImplementation(libs.archunit)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.function.DoubleSupplier;
|
||||
|
||||
/**
|
||||
* How long to wait before trying the service again (ADR 0058): 1 second after the first failure,
|
||||
* doubling to 5 minutes, each wait between half and all of that so a restarted service isn't met by
|
||||
* every client at once. A connection that stays up a minute counts as a success and starts over.
|
||||
*/
|
||||
final class Backoff {
|
||||
|
||||
static final long FIRST_MILLIS = 1_000;
|
||||
static final long MAX_MILLIS = 5 * 60_000;
|
||||
/** How long a connection must last before its drop counts as a fresh start. */
|
||||
static final long STEADY_MILLIS = 60_000;
|
||||
|
||||
private final DoubleSupplier random;
|
||||
private int failures;
|
||||
private long connectedAt = -1;
|
||||
|
||||
/** @param random numbers in [0, 1), for the jitter */
|
||||
Backoff(DoubleSupplier random) {
|
||||
this.random = random;
|
||||
}
|
||||
|
||||
/** The connection is up, as of {@code now}. */
|
||||
void connected(long now) {
|
||||
connectedAt = now;
|
||||
}
|
||||
|
||||
/** The connection failed or dropped at {@code now}: how many milliseconds to wait before the next try. */
|
||||
long failed(long now) {
|
||||
if (connectedAt >= 0 && now - connectedAt >= STEADY_MILLIS) {
|
||||
failures = 0;
|
||||
}
|
||||
connectedAt = -1;
|
||||
long ceiling = failures >= 20 ? MAX_MILLIS : Math.min(MAX_MILLIS, FIRST_MILLIS << failures);
|
||||
failures++;
|
||||
return ceiling / 2 + (long) (random.getAsDouble() * (ceiling - ceiling / 2));
|
||||
}
|
||||
|
||||
/** Starts over: the player asked to try now. */
|
||||
void reset() {
|
||||
failures = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Every cosmetic this client can draw (ADR 0061), in the wardrobe's order. The service keeps the same
|
||||
* ids ({@code docs/online-protocol.md}); an id the service sends that isn't here (from a newer
|
||||
* client) is ignored, so a newer catalog never breaks an older client.
|
||||
*
|
||||
* <p>Immutable; any thread.
|
||||
*/
|
||||
public final class Catalog {
|
||||
|
||||
private static final List<Cosmetic> ALL = List.of(
|
||||
// Capes: the client's own art (CapeArt), some of it animated.
|
||||
free("cape.frost", "Frost"),
|
||||
free("cape.aurora", "Aurora"),
|
||||
free("cape.midnight", "Midnight"),
|
||||
free("cape.ember", "Ember"),
|
||||
free("cape.sakura", "Sakura"),
|
||||
free("cape.tide", "Tide"),
|
||||
free("cape.mono", "Mono"),
|
||||
// Hats: small models on the head, hidden under a helmet.
|
||||
free("hat.crown", "Crown"),
|
||||
free("hat.halo", "Halo"),
|
||||
free("hat.top_hat", "Top Hat"),
|
||||
free("hat.beanie", "Beanie"),
|
||||
free("hat.horns", "Horns"),
|
||||
free("hat.cat_ears", "Cat Ears"),
|
||||
// On the back: hidden while an elytra is worn.
|
||||
free("back.angel_wings", "Angel Wings"),
|
||||
free("back.frost_wings", "Frost Wings"),
|
||||
free("back.bat_wings", "Bat Wings"),
|
||||
free("back.backpack", "Backpack"),
|
||||
// Name tags: the name's color over the head.
|
||||
free("nametag.ice", "Ice"),
|
||||
free("nametag.gold", "Gold"),
|
||||
free("nametag.mint", "Mint"),
|
||||
free("nametag.rose", "Rose"),
|
||||
free("nametag.violet", "Violet"),
|
||||
free("nametag.frost", "Frost Fade"),
|
||||
free("nametag.sunset", "Sunset Fade"),
|
||||
free("nametag.aurora", "Aurora Fade"),
|
||||
// Trails: a few particles behind the player as they move.
|
||||
free("trail.snow", "Snowflakes"),
|
||||
free("trail.hearts", "Hearts"),
|
||||
free("trail.sparkles", "Sparkles"),
|
||||
free("trail.notes", "Notes"),
|
||||
// Emotes: played from the emote wheel, seen by Incari players nearby.
|
||||
free("emote.wave", "Wave"),
|
||||
free("emote.clap", "Clap"),
|
||||
free("emote.cheer", "Cheer"),
|
||||
free("emote.salute", "Salute"),
|
||||
free("emote.facepalm", "Facepalm"),
|
||||
free("emote.shrug", "Shrug"),
|
||||
free("emote.dab", "Dab"),
|
||||
free("emote.bow", "Bow"));
|
||||
|
||||
private static final Map<String, Cosmetic> BY_ID = new HashMap<>();
|
||||
private static final Map<Cosmetic.Slot, List<Cosmetic>> BY_SLOT = new EnumMap<>(Cosmetic.Slot.class);
|
||||
|
||||
static {
|
||||
for (Cosmetic.Slot slot : Cosmetic.Slot.values()) {
|
||||
List<Cosmetic> inSlot = new ArrayList<>();
|
||||
for (Cosmetic each : ALL) {
|
||||
if (each.slot() == slot) {
|
||||
inSlot.add(each);
|
||||
}
|
||||
}
|
||||
BY_SLOT.put(slot, Collections.unmodifiableList(inSlot));
|
||||
}
|
||||
for (Cosmetic each : ALL) {
|
||||
if (BY_ID.put(each.id(), each) != null) {
|
||||
throw new IllegalStateException("Two cosmetics are " + each.id());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Catalog() {}
|
||||
|
||||
private static Cosmetic free(String id, String name) {
|
||||
String prefix = id.substring(0, id.indexOf('.'));
|
||||
for (Cosmetic.Slot slot : Cosmetic.Slot.values()) {
|
||||
if (slot.prefix().equals(prefix)) {
|
||||
return new Cosmetic(id, slot, name, true);
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException(id);
|
||||
}
|
||||
|
||||
/** Every cosmetic, in the wardrobe's order. */
|
||||
public static List<Cosmetic> all() {
|
||||
return ALL;
|
||||
}
|
||||
|
||||
/** The cosmetic with this id, or null if this client has none by it. */
|
||||
public static @Nullable Cosmetic byId(String id) {
|
||||
return BY_ID.get(id);
|
||||
}
|
||||
|
||||
/** The cosmetics in {@code slot}, in the wardrobe's order. */
|
||||
public static List<Cosmetic> inSlot(Cosmetic.Slot slot) {
|
||||
return BY_SLOT.getOrDefault(slot, List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package incari.online;
|
||||
|
||||
/**
|
||||
* One cosmetic in Incari's catalog (ADR 0061): something an account wears that other Incari players
|
||||
* see (a cape, a hat, a name tag's color), or an emote it can play. The client draws each from its
|
||||
* own art; the service only keeps which ids an account owns and wears.
|
||||
*
|
||||
* @param id the id the service and other clients know it by, {@code <slot>.<name>}; never changes
|
||||
* @param slot where it's worn: one cosmetic per slot
|
||||
* @param name what the wardrobe calls it
|
||||
* @param free whether every account owns it
|
||||
*/
|
||||
public record Cosmetic(String id, Slot slot, String name, boolean free) {
|
||||
|
||||
/** Where a cosmetic is worn. An account wears at most one per slot; emotes are played, not worn. */
|
||||
public enum Slot {
|
||||
CAPE("cape", "Capes"),
|
||||
HAT("hat", "Hats"),
|
||||
BACK("back", "Wings & Back"),
|
||||
NAMETAG("nametag", "Name Tags"),
|
||||
TRAIL("trail", "Trails"),
|
||||
EMOTE("emote", "Emotes");
|
||||
|
||||
private final String prefix;
|
||||
private final String label;
|
||||
|
||||
Slot(String prefix, String label) {
|
||||
this.prefix = prefix;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
/** The ids' prefix: {@code cape} in {@code cape.frost}. */
|
||||
public String prefix() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
/** What the wardrobe's tab says. */
|
||||
public String label() {
|
||||
return label;
|
||||
}
|
||||
|
||||
/** Whether a cosmetic in this slot is worn (and sent with {@code equip}); emotes aren't. */
|
||||
public boolean worn() {
|
||||
return this != EMOTE;
|
||||
}
|
||||
}
|
||||
|
||||
public Cosmetic {
|
||||
if (!id.startsWith(slot.prefix() + ".")) {
|
||||
throw new IllegalArgumentException(id + " isn't in slot " + slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The rules for an Incari username and password (ADR 0058), checked as the player types so the
|
||||
* form can say what's wrong before anything is sent. The service checks them again, against a
|
||||
* longer list of common passwords; these are a courtesy, not the defence.
|
||||
*/
|
||||
public final class Credentials {
|
||||
|
||||
public static final int MIN_USERNAME = 3;
|
||||
public static final int MAX_USERNAME = 16;
|
||||
public static final int MIN_PASSWORD = 10;
|
||||
public static final int MAX_PASSWORD = 128;
|
||||
|
||||
/**
|
||||
* Passwords long enough to pass the length rule that people still pick most. The service holds
|
||||
* the 10,000 most common; this short list catches the obvious ones without a round trip.
|
||||
*/
|
||||
private static final Set<String> COMMON = Set.of(
|
||||
"1234567890",
|
||||
"0987654321",
|
||||
"1234567891",
|
||||
"12345678910",
|
||||
"123456789a",
|
||||
"123456789q",
|
||||
"a123456789",
|
||||
"qwertyuiop",
|
||||
"qwerty1234",
|
||||
"qwerty123456",
|
||||
"1q2w3e4r5t",
|
||||
"1qaz2wsx3edc",
|
||||
"asdfghjkl1",
|
||||
"zxcvbnm123",
|
||||
"abcdefghij",
|
||||
"abc1234567",
|
||||
"password12",
|
||||
"password123",
|
||||
"password1234",
|
||||
"password1!",
|
||||
"p@ssw0rd12",
|
||||
"passw0rd123",
|
||||
"iloveyou12",
|
||||
"iloveyou123",
|
||||
"letmein123",
|
||||
"welcome123",
|
||||
"football12",
|
||||
"football123",
|
||||
"baseball12",
|
||||
"princess12",
|
||||
"sunshine12",
|
||||
"monkey1234",
|
||||
"dragon1234",
|
||||
"trustno1234",
|
||||
"minecraft1",
|
||||
"minecraft12",
|
||||
"minecraft123",
|
||||
"minecraft1234",
|
||||
"eaglercraft",
|
||||
"eaglercraft1",
|
||||
"eaglercraft123",
|
||||
"incariclient",
|
||||
"incari1234",
|
||||
"chromebook1",
|
||||
"chromebook123",
|
||||
"fortnite123",
|
||||
"roblox12345");
|
||||
|
||||
private Credentials() {}
|
||||
|
||||
/** Whether {@code c} may be in a username: ASCII letters, digits and underscores. */
|
||||
public static boolean usernameCharacter(char c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
|
||||
}
|
||||
|
||||
/** What's wrong with {@code username}, or null if it's one the service could take. */
|
||||
public static @Nullable String usernameProblem(String username) {
|
||||
if (username.length() < MIN_USERNAME || username.length() > MAX_USERNAME) {
|
||||
return "A username is " + MIN_USERNAME + " to " + MAX_USERNAME + " characters";
|
||||
}
|
||||
for (int i = 0; i < username.length(); i++) {
|
||||
if (!usernameCharacter(username.charAt(i))) {
|
||||
return "Only letters, digits and underscores";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What's wrong with {@code password} for {@code username}'s account, or null if it's fine. */
|
||||
public static @Nullable String passwordProblem(String password, String username) {
|
||||
if (password.length() < MIN_PASSWORD) {
|
||||
return "At least " + MIN_PASSWORD + " characters";
|
||||
}
|
||||
if (password.length() > MAX_PASSWORD) {
|
||||
return "At most " + MAX_PASSWORD + " characters";
|
||||
}
|
||||
String lower = password.toLowerCase(Locale.ROOT);
|
||||
if (COMMON.contains(lower) || oneCharacter(lower) || counting(lower)) {
|
||||
return "Too common: anyone could guess it";
|
||||
}
|
||||
if (!username.isEmpty() && lower.contains(username.toLowerCase(Locale.ROOT))) {
|
||||
return "Don't put your username in it";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean oneCharacter(String text) {
|
||||
return text.chars().distinct().count() <= 2;
|
||||
}
|
||||
|
||||
/** 0123456789..., abcdef..., or the same backwards. */
|
||||
private static boolean counting(String text) {
|
||||
int up = 0;
|
||||
int down = 0;
|
||||
for (int i = 1; i < text.length(); i++) {
|
||||
int step = text.charAt(i) - text.charAt(i - 1);
|
||||
up += step == 1 ? 1 : 0;
|
||||
down += step == -1 ? 1 : 0;
|
||||
}
|
||||
return up == text.length() - 1 || down == text.length() - 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package incari.online;
|
||||
|
||||
/**
|
||||
* Why a request to the service didn't work, with what the screens say about it. The service's
|
||||
* errors are deliberately general (ADR 0058): a failed sign-in never says whether the username
|
||||
* exists.
|
||||
*/
|
||||
public enum Failure {
|
||||
/** The username and password (or code) didn't match an account; also what rate limits look like. */
|
||||
WRONG_CREDENTIALS("Wrong username or password."),
|
||||
/** The password given to confirm an action wasn't the account's. */
|
||||
WRONG_PASSWORD("That isn't your password."),
|
||||
/** The recovery code didn't match, or was used already. */
|
||||
WRONG_CODE("Wrong username or recovery code."),
|
||||
/** The username is taken. */
|
||||
TAKEN("That username is taken."),
|
||||
/** The service turned the request down for its form (a rule broken). */
|
||||
REJECTED("That wasn't accepted. Check what you typed."),
|
||||
/** Too many tries; wait before the next. */
|
||||
RATE_LIMITED("Too many tries. Wait a few minutes and try again."),
|
||||
/** The account isn't signed in on this connection any more. */
|
||||
SIGNED_OUT("You were signed out. Sign in again."),
|
||||
/** The service can't be reached, or the connection dropped before it answered. */
|
||||
OFFLINE("Can't reach Incari. Try again later."),
|
||||
/** They don't take messages (or friend requests) from the player. */
|
||||
CLOSED("They aren't taking messages from you."),
|
||||
/** This client is too old for the service. */
|
||||
UPDATE("Update Incari Client to sign in."),
|
||||
/** The service had a problem of its own. */
|
||||
UNAVAILABLE("Incari is having trouble. Try again later.");
|
||||
|
||||
private final String message;
|
||||
|
||||
Failure(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
/** What to tell the player. */
|
||||
public String message() {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Predicate;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* What a player wears (ADR 0061): at most one cosmetic in each worn slot. Read from the ids the
|
||||
* service sends, forgivingly: an id this client doesn't know, an emote, or a second cosmetic for a
|
||||
* slot is left out.
|
||||
*
|
||||
* <p>Immutable; any thread.
|
||||
*/
|
||||
public final class Loadout {
|
||||
|
||||
/** Nothing worn. */
|
||||
public static final Loadout EMPTY = new Loadout(new EnumMap<>(Cosmetic.Slot.class));
|
||||
|
||||
private final Map<Cosmetic.Slot, Cosmetic> bySlot;
|
||||
private final List<String> ids;
|
||||
|
||||
private Loadout(EnumMap<Cosmetic.Slot, Cosmetic> bySlot) {
|
||||
this.bySlot = bySlot;
|
||||
List<String> list = new ArrayList<>();
|
||||
for (Cosmetic each : bySlot.values()) {
|
||||
list.add(each.id());
|
||||
}
|
||||
this.ids = List.copyOf(list);
|
||||
}
|
||||
|
||||
/** The loadout these ids describe, leaving out what this client can't draw. */
|
||||
public static Loadout of(List<String> ids) {
|
||||
if (ids.isEmpty()) {
|
||||
return EMPTY;
|
||||
}
|
||||
EnumMap<Cosmetic.Slot, Cosmetic> bySlot = new EnumMap<>(Cosmetic.Slot.class);
|
||||
for (String id : ids) {
|
||||
Cosmetic cosmetic = Catalog.byId(id);
|
||||
if (cosmetic != null && cosmetic.slot().worn()) {
|
||||
bySlot.putIfAbsent(cosmetic.slot(), cosmetic);
|
||||
}
|
||||
}
|
||||
return bySlot.isEmpty() ? EMPTY : new Loadout(bySlot);
|
||||
}
|
||||
|
||||
/** What's worn in {@code slot}, or null. */
|
||||
public @Nullable Cosmetic in(Cosmetic.Slot slot) {
|
||||
return bySlot.get(slot);
|
||||
}
|
||||
|
||||
/** Whether {@code cosmetic} is worn. */
|
||||
public boolean wears(Cosmetic cosmetic) {
|
||||
return cosmetic.equals(bySlot.get(cosmetic.slot()));
|
||||
}
|
||||
|
||||
/** This loadout with {@code cosmetic} in its slot, in place of what was there. */
|
||||
public Loadout with(Cosmetic cosmetic) {
|
||||
if (!cosmetic.slot().worn()) {
|
||||
throw new IllegalArgumentException(cosmetic.id() + " isn't worn");
|
||||
}
|
||||
EnumMap<Cosmetic.Slot, Cosmetic> next = copy();
|
||||
next.put(cosmetic.slot(), cosmetic);
|
||||
return new Loadout(next);
|
||||
}
|
||||
|
||||
/** This loadout with nothing in {@code slot}. */
|
||||
public Loadout without(Cosmetic.Slot slot) {
|
||||
if (!bySlot.containsKey(slot)) {
|
||||
return this;
|
||||
}
|
||||
EnumMap<Cosmetic.Slot, Cosmetic> next = copy();
|
||||
next.remove(slot);
|
||||
return next.isEmpty() ? EMPTY : new Loadout(next);
|
||||
}
|
||||
|
||||
/** This loadout with only what {@code owns} allows. */
|
||||
Loadout ownedBy(Predicate<Cosmetic> owns) {
|
||||
EnumMap<Cosmetic.Slot, Cosmetic> next = copy();
|
||||
if (!next.values().removeIf(each -> !owns.test(each))) {
|
||||
return this;
|
||||
}
|
||||
return next.isEmpty() ? EMPTY : new Loadout(next);
|
||||
}
|
||||
|
||||
private EnumMap<Cosmetic.Slot, Cosmetic> copy() {
|
||||
EnumMap<Cosmetic.Slot, Cosmetic> next = new EnumMap<>(Cosmetic.Slot.class);
|
||||
next.putAll(bySlot);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** The ids worn, in slot order: what {@code equip} sends. */
|
||||
public List<String> ids() {
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** Whether nothing is worn. */
|
||||
public boolean isEmpty() {
|
||||
return ids.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(@Nullable Object other) {
|
||||
return other instanceof Loadout loadout && bySlot.equals(loadout.bySlot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return bySlot.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Loadout" + ids;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,129 @@
|
||||
package incari.online;
|
||||
|
||||
/**
|
||||
* Sign-up's proof of work (ADR 0058): the service hands out a 16-byte challenge and a number of
|
||||
* bits, and the client finds a nonce such that SHA-256 of the challenge followed by the nonce (8
|
||||
* bytes, big-endian) starts with that many zero bits. The two fit one SHA-256 block, so each try is
|
||||
* one compression with nothing allocated.
|
||||
*
|
||||
* <p>Solved in steps ({@link #step}) so the caller can yield between them: in the page, the
|
||||
* background pool runs it between frames. One thread at a time.
|
||||
*/
|
||||
final class ProofOfWork {
|
||||
|
||||
/** The largest nonce tried: JSON numbers are exact up to 2^53, and no answer takes that long. */
|
||||
static final long MAX_NONCE = (1L << 53) - 1;
|
||||
|
||||
private final int bits;
|
||||
private final int[] block = new int[64];
|
||||
private final int[] state = new int[8];
|
||||
private long nonce;
|
||||
private long found = -1;
|
||||
|
||||
/**
|
||||
* @param challenge the service's 16 bytes
|
||||
* @param bits how many leading zero bits the hash needs, 0 to 64
|
||||
*/
|
||||
ProofOfWork(byte[] challenge, int bits) {
|
||||
if (challenge.length != 16) {
|
||||
throw new IllegalArgumentException("A challenge is 16 bytes, not " + challenge.length);
|
||||
}
|
||||
if (bits < 0 || bits > 64) {
|
||||
throw new IllegalArgumentException("Bits out of range: " + bits);
|
||||
}
|
||||
this.bits = bits;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
block[i] = (challenge[i * 4] & 0xFF) << 24
|
||||
| (challenge[i * 4 + 1] & 0xFF) << 16
|
||||
| (challenge[i * 4 + 2] & 0xFF) << 8
|
||||
| (challenge[i * 4 + 3] & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries up to {@code tries} more nonces. Returns true once one is found ({@link #nonce}).
|
||||
*
|
||||
* @throws IllegalStateException if every nonce up to {@link #MAX_NONCE} failed (never, for a fair challenge)
|
||||
*/
|
||||
boolean step(int tries) {
|
||||
if (found >= 0) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < tries; i++) {
|
||||
if (nonce > MAX_NONCE) {
|
||||
throw new IllegalStateException("No nonce found");
|
||||
}
|
||||
if (passes(nonce)) {
|
||||
found = nonce;
|
||||
return true;
|
||||
}
|
||||
nonce++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The nonce found; -1 until {@link #step} returns true. */
|
||||
long nonce() {
|
||||
return found;
|
||||
}
|
||||
|
||||
/** How many nonces have been tried. */
|
||||
long tried() {
|
||||
return found >= 0 ? found + 1 : nonce;
|
||||
}
|
||||
|
||||
/** Whether {@code candidate} answers the challenge. Hot path: allocates nothing. */
|
||||
boolean passes(long candidate) {
|
||||
// Words 0-3 are the challenge; 4-5 the nonce; then the padding: a 1 bit, zeros, and the
|
||||
// message's length in bits (24 bytes = 192).
|
||||
block[4] = (int) (candidate >>> 32);
|
||||
block[5] = (int) candidate;
|
||||
block[6] = 0x80000000;
|
||||
for (int i = 7; i < 15; i++) {
|
||||
block[i] = 0;
|
||||
}
|
||||
block[15] = 192;
|
||||
System.arraycopy(Sha256.INITIAL, 0, state, 0, 8);
|
||||
Sha256.compress(state, block);
|
||||
return leadingZeros(state) >= bits;
|
||||
}
|
||||
|
||||
private static int leadingZeros(int[] state) {
|
||||
int zeros = Integer.numberOfLeadingZeros(state[0]);
|
||||
return zeros < 32 ? zeros : 32 + Integer.numberOfLeadingZeros(state[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64url without padding (RFC 4648 section 5), as the service writes its challenges. Not
|
||||
* {@code java.util.Base64}: its padding rules differ between the JDK and TeaVM.
|
||||
*
|
||||
* @throws IllegalArgumentException for a character outside the alphabet or a bad length
|
||||
*/
|
||||
static byte[] base64Url(String text) {
|
||||
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
int length = text.length();
|
||||
while (length > 0 && text.charAt(length - 1) == '=') {
|
||||
length--;
|
||||
}
|
||||
if (length % 4 == 1) {
|
||||
throw new IllegalArgumentException("Not base64url: bad length");
|
||||
}
|
||||
byte[] out = new byte[length * 3 / 4];
|
||||
int bits = 0;
|
||||
int count = 0;
|
||||
int at = 0;
|
||||
for (int i = 0; i < length; i++) {
|
||||
int value = alphabet.indexOf(text.charAt(i));
|
||||
if (value < 0) {
|
||||
throw new IllegalArgumentException("Not base64url: " + text.charAt(i));
|
||||
}
|
||||
bits = bits << 6 | value;
|
||||
count += 6;
|
||||
if (count >= 8) {
|
||||
count -= 8;
|
||||
out[at++] = (byte) (bits >> count);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.Locale;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Recovery codes as the player types them (ADR 0058): twelve characters of Crockford's base32 in
|
||||
* three groups ({@code XXXX-XXXX-XXXX}). The alphabet has no I, L, O or U, so a code read off paper
|
||||
* where one looks like a digit is read as the digit, as Crockford's rules say.
|
||||
*/
|
||||
public final class RecoveryCodes {
|
||||
|
||||
static final String ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
||||
private static final int LENGTH = 12;
|
||||
|
||||
private RecoveryCodes() {}
|
||||
|
||||
/**
|
||||
* {@code typed} in its one written form, or null if it isn't a code: spaces and dashes are
|
||||
* ignored, case too, and I and L read as 1, O as 0.
|
||||
*/
|
||||
public static @Nullable String normalize(String typed) {
|
||||
StringBuilder code = new StringBuilder(LENGTH + 2);
|
||||
int count = 0;
|
||||
for (int i = 0; i < typed.length(); i++) {
|
||||
char c = Character.toUpperCase(typed.charAt(i));
|
||||
if (c == ' ' || c == '-') {
|
||||
continue;
|
||||
}
|
||||
if (c == 'I' || c == 'L') {
|
||||
c = '1';
|
||||
} else if (c == 'O') {
|
||||
c = '0';
|
||||
}
|
||||
if (ALPHABET.indexOf(c) < 0 || count == LENGTH) {
|
||||
return null;
|
||||
}
|
||||
if (count == 4 || count == 8) {
|
||||
code.append('-');
|
||||
}
|
||||
code.append(c);
|
||||
count++;
|
||||
}
|
||||
return count == LENGTH ? code.toString() : null;
|
||||
}
|
||||
|
||||
/** {@code code} as the service sent it, in the written form (upper case, grouped). */
|
||||
static String display(String code) {
|
||||
String normal = normalize(code);
|
||||
return normal == null ? code.toUpperCase(Locale.ROOT) : normal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Incari's release versions: one to four whole numbers joined by dots ({@code 0.2.0}). The service
|
||||
* names the latest in its {@code hello} answer, with its changelog; the client compares it with its own.
|
||||
*/
|
||||
public final class Releases {
|
||||
|
||||
/** At most this many changelog lines, each at most {@link #MAX_NOTE} characters: all fit the notes screen. */
|
||||
public static final int MAX_NOTES = 12;
|
||||
|
||||
public static final int MAX_NOTE = 120;
|
||||
|
||||
private static final Pattern VERSION = Pattern.compile("\\d{1,6}(\\.\\d{1,6}){0,3}");
|
||||
|
||||
private Releases() {}
|
||||
|
||||
/** {@code version} if it's a release version, else null: anything else the service sends is dropped. */
|
||||
public static @Nullable String valid(@Nullable String version) {
|
||||
return version != null && VERSION.matcher(version).matches() ? version : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code latest} comes after {@code current}. Missing parts count as 0, so {@code 1.2}
|
||||
* and {@code 1.2.0} are the same; either not a release version is never newer.
|
||||
*/
|
||||
public static boolean newer(@Nullable String latest, @Nullable String current) {
|
||||
String later = valid(latest);
|
||||
String now = valid(current);
|
||||
if (later == null || now == null) {
|
||||
return false;
|
||||
}
|
||||
String[] a = later.split("\\.", -1);
|
||||
String[] b = now.split("\\.", -1);
|
||||
for (int i = 0; i < Math.max(a.length, b.length); i++) {
|
||||
int x = i < a.length ? Integer.parseInt(a[i]) : 0;
|
||||
int y = i < b.length ? Integer.parseInt(b[i]) : 0;
|
||||
if (x != y) {
|
||||
return x > y;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code note} is a changelog line the client shows: 1 to {@link #MAX_NOTE} characters,
|
||||
* no control characters and nothing invisible (zero-width or direction marks), which could make
|
||||
* it read as something other than it is.
|
||||
*/
|
||||
public static boolean note(String note) {
|
||||
return !note.isBlank()
|
||||
&& note.codePointCount(0, note.length()) <= MAX_NOTE
|
||||
&& note.codePoints()
|
||||
.noneMatch(c -> Character.isISOControl(c) || Character.getType(c) == Character.FORMAT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* What a request to the service came to: a value, or why not.
|
||||
*
|
||||
* @param <T> the value's type ({@link Void} for requests with nothing to give back)
|
||||
*/
|
||||
public final class Result<T> {
|
||||
|
||||
private final @Nullable T value;
|
||||
private final @Nullable Failure failure;
|
||||
|
||||
private Result(@Nullable T value, @Nullable Failure failure) {
|
||||
this.value = value;
|
||||
this.failure = failure;
|
||||
}
|
||||
|
||||
public static <T> Result<T> ok(T value) {
|
||||
return new Result<>(Objects.requireNonNull(value), null);
|
||||
}
|
||||
|
||||
/** Success with nothing to give back. */
|
||||
public static Result<Void> done() {
|
||||
return new Result<>(null, null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> failed(Failure failure) {
|
||||
return new Result<>(null, failure);
|
||||
}
|
||||
|
||||
public boolean ok() {
|
||||
return failure == null;
|
||||
}
|
||||
|
||||
/** The value; throws if it failed or has none. */
|
||||
public T value() {
|
||||
if (value == null) {
|
||||
throw new IllegalStateException("No value: " + failure);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Why it failed; null if it didn't. */
|
||||
public @Nullable Failure failure() {
|
||||
return failure;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return failure == null ? "ok" : failure.name();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Where the player is, as the service sees it (ADR 0058): SHA-256 of a fixed prefix and the address
|
||||
* they connected to, normalized so that the ways of writing one address agree. Two players see each
|
||||
* other only if their hashes match. The service never stores a plain list of servers; the hash keeps
|
||||
* plain addresses out of its database and logs (a determined attacker with a list of servers can
|
||||
* still match it).
|
||||
*
|
||||
* <p>Shared with the backend through {@code vectors.json}: change the prefix or the rules together.
|
||||
*/
|
||||
public final class ServerHash {
|
||||
|
||||
/** Bumped if the rules below ever change, so old and new hashes never match by accident. */
|
||||
static final String PREFIX = "incari-server-v1\n";
|
||||
|
||||
private static final int GAME_PORT = 25565;
|
||||
|
||||
private ServerHash() {}
|
||||
|
||||
/**
|
||||
* The hash of the address the player joined through, as 64 lowercase hex digits.
|
||||
*
|
||||
* @param address as the server list holds it: {@code host}, {@code host:port}, {@code ws://} or
|
||||
* {@code wss://} URLs, or {@code relay:<code>} for a world shared through an Eagler relay
|
||||
*/
|
||||
public static String of(String address) {
|
||||
return Sha256.hex(PREFIX + normalize(address));
|
||||
}
|
||||
|
||||
/**
|
||||
* The address in its one written form: a lowercase host without a trailing dot, the port only if
|
||||
* it isn't the default, and a URL reduced to its host, port and path (no query, no trailing
|
||||
* slash). A relay's join code is kept as typed: codes may be case-sensitive.
|
||||
*/
|
||||
static String normalize(String address) {
|
||||
String trimmed = address.strip();
|
||||
String lower = trimmed.toLowerCase(Locale.ROOT);
|
||||
if (lower.startsWith("relay:")) {
|
||||
return "relay:" + trimmed.substring("relay:".length()).strip();
|
||||
}
|
||||
if (lower.startsWith("ws://") || lower.startsWith("wss://")) {
|
||||
boolean secure = lower.startsWith("wss://");
|
||||
String rest = trimmed.substring(secure ? 6 : 5);
|
||||
int end = indexOfAny(rest, "?#");
|
||||
if (end >= 0) {
|
||||
rest = rest.substring(0, end);
|
||||
}
|
||||
int slash = rest.indexOf('/');
|
||||
String authority = slash < 0 ? rest : rest.substring(0, slash);
|
||||
String path = slash < 0 ? "" : rest.substring(slash);
|
||||
while (path.endsWith("/")) {
|
||||
path = path.substring(0, path.length() - 1);
|
||||
}
|
||||
return (secure ? "wss://" : "ws://") + hostAndPort(authority, secure ? 443 : 80) + path;
|
||||
}
|
||||
return hostAndPort(trimmed, GAME_PORT);
|
||||
}
|
||||
|
||||
/** {@code host[:port]} or {@code [v6]:port}, lowercased, without the default port or a trailing dot. */
|
||||
private static String hostAndPort(String authority, int defaultPort) {
|
||||
String host = authority;
|
||||
String port = "";
|
||||
int at = host.lastIndexOf('@');
|
||||
if (at >= 0) {
|
||||
host = host.substring(at + 1);
|
||||
}
|
||||
if (host.startsWith("[")) {
|
||||
int close = host.indexOf(']');
|
||||
if (close > 0) {
|
||||
port = host.substring(close + 1).startsWith(":") ? host.substring(close + 2) : "";
|
||||
host = host.substring(0, close + 1);
|
||||
}
|
||||
} else {
|
||||
int colon = host.lastIndexOf(':');
|
||||
if (colon >= 0 && host.indexOf(':') == colon) {
|
||||
port = host.substring(colon + 1);
|
||||
host = host.substring(0, colon);
|
||||
}
|
||||
}
|
||||
host = host.toLowerCase(Locale.ROOT);
|
||||
while (host.endsWith(".")) {
|
||||
host = host.substring(0, host.length() - 1);
|
||||
}
|
||||
if (port.isEmpty() || port.equals(Integer.toString(defaultPort))) {
|
||||
return host;
|
||||
}
|
||||
return host + ":" + port;
|
||||
}
|
||||
|
||||
private static int indexOfAny(String text, String characters) {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
if (characters.indexOf(text.charAt(i)) >= 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package incari.online;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonParser;
|
||||
import incari.framework.config.ConfigStorage;
|
||||
import java.io.IOException;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The session token, kept between starts (ADR 0058): {@code session.json} under the client's
|
||||
* {@code incari/online}, which the browser stores behind in OPFS or IndexedDB (ADR 0011). The token,
|
||||
* never the password. The username is kept beside it, to show while the session resumes.
|
||||
*
|
||||
* <p>Game thread; the storage returns at once.
|
||||
*/
|
||||
final class SessionStore {
|
||||
|
||||
static final String FILE = "session.json";
|
||||
|
||||
/** A saved session. */
|
||||
record Saved(String username, String token) {
|
||||
@Override
|
||||
public String toString() {
|
||||
// Never the token, in a log or anywhere else.
|
||||
return "Saved[" + username + "]";
|
||||
}
|
||||
}
|
||||
|
||||
private final ConfigStorage storage;
|
||||
private final Problems problems;
|
||||
|
||||
/** Where a file that can't be read or written is reported. */
|
||||
interface Problems {
|
||||
void report(String message, @Nullable Throwable error);
|
||||
}
|
||||
|
||||
SessionStore(ConfigStorage storage, Problems problems) {
|
||||
this.storage = storage;
|
||||
this.problems = problems;
|
||||
}
|
||||
|
||||
/** The saved session, or null if there's none or it can't be read. */
|
||||
@Nullable
|
||||
Saved load() {
|
||||
try {
|
||||
String text = storage.read(FILE);
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
JsonObject json = JsonParser.parseString(text).getAsJsonObject();
|
||||
String username = json.has("username") ? json.get("username").getAsString() : "";
|
||||
String token = json.has("token") ? json.get("token").getAsString() : "";
|
||||
return token.isEmpty() ? null : new Saved(username, token);
|
||||
} catch (IOException | JsonParseException | IllegalStateException | UnsupportedOperationException e) {
|
||||
problems.report("Couldn't read the saved Incari session; signed out", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void save(Saved session) {
|
||||
JsonObject json = new JsonObject();
|
||||
json.addProperty("username", session.username());
|
||||
json.addProperty("token", session.token());
|
||||
try {
|
||||
storage.write(FILE, json.toString());
|
||||
} catch (IOException e) {
|
||||
problems.report("Couldn't save the Incari session; you'll sign in again next time", e);
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
try {
|
||||
storage.delete(FILE);
|
||||
} catch (IOException e) {
|
||||
problems.report("Couldn't delete the saved Incari session", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package incari.online;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* SHA-256 (FIPS 180-4), written out so proof of work can hash one block per nonce without
|
||||
* allocating: {@code MessageDigest} copies its input and makes a result array each time, and sign-up
|
||||
* hashes some 262,000 nonces on a Chromebook (ADR 0058).
|
||||
*/
|
||||
final class Sha256 {
|
||||
|
||||
private static final int[] K = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
};
|
||||
|
||||
static final int[] INITIAL = {
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
|
||||
};
|
||||
|
||||
private Sha256() {}
|
||||
|
||||
/** The hash of {@code text}'s UTF-8 bytes, as 64 lowercase hex digits. */
|
||||
static String hex(String text) {
|
||||
return hex(hash(text.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
/** {@code bytes} as lowercase hex. */
|
||||
static String hex(byte[] bytes) {
|
||||
StringBuilder out = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
out.append(Character.forDigit(b >> 4 & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** The hash of {@code message}. */
|
||||
static byte[] hash(byte[] message) {
|
||||
int blocks = (message.length + 8) / 64 + 1;
|
||||
byte[] padded = new byte[blocks * 64];
|
||||
System.arraycopy(message, 0, padded, 0, message.length);
|
||||
padded[message.length] = (byte) 0x80;
|
||||
long bits = (long) message.length * 8;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
padded[padded.length - 1 - i] = (byte) (bits >>> (8 * i));
|
||||
}
|
||||
int[] state = INITIAL.clone();
|
||||
int[] w = new int[64];
|
||||
for (int block = 0; block < blocks; block++) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
int at = block * 64 + i * 4;
|
||||
w[i] = (padded[at] & 0xFF) << 24
|
||||
| (padded[at + 1] & 0xFF) << 16
|
||||
| (padded[at + 2] & 0xFF) << 8
|
||||
| (padded[at + 3] & 0xFF);
|
||||
}
|
||||
compress(state, w);
|
||||
}
|
||||
byte[] out = new byte[32];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out[i * 4] = (byte) (state[i] >>> 24);
|
||||
out[i * 4 + 1] = (byte) (state[i] >>> 16);
|
||||
out[i * 4 + 2] = (byte) (state[i] >>> 8);
|
||||
out[i * 4 + 3] = (byte) state[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one block through {@code state}. {@code w} holds the block's 16 words first and is used as
|
||||
* the message schedule (64 words), so its last 48 are overwritten. Hot path: allocates nothing.
|
||||
*/
|
||||
static void compress(int[] state, int[] w) {
|
||||
for (int i = 16; i < 64; i++) {
|
||||
int s0 = Integer.rotateRight(w[i - 15], 7) ^ Integer.rotateRight(w[i - 15], 18) ^ (w[i - 15] >>> 3);
|
||||
int s1 = Integer.rotateRight(w[i - 2], 17) ^ Integer.rotateRight(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
int a = state[0];
|
||||
int b = state[1];
|
||||
int c = state[2];
|
||||
int d = state[3];
|
||||
int e = state[4];
|
||||
int f = state[5];
|
||||
int g = state[6];
|
||||
int h = state[7];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
int s1 = Integer.rotateRight(e, 6) ^ Integer.rotateRight(e, 11) ^ Integer.rotateRight(e, 25);
|
||||
int ch = (e & f) ^ (~e & g);
|
||||
int t1 = h + s1 + ch + K[i] + w[i];
|
||||
int s0 = Integer.rotateRight(a, 2) ^ Integer.rotateRight(a, 13) ^ Integer.rotateRight(a, 22);
|
||||
int maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
int t2 = s0 + maj;
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + t1;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = t1 + t2;
|
||||
}
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
state[4] += e;
|
||||
state[5] += f;
|
||||
state[6] += g;
|
||||
state[7] += h;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
package incari.online;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Friends, friend requests and conversations (ADR 0059), as the client knows them: the chat menu
|
||||
* draws this, and {@link OnlineService} keeps it current from the service's answers and events.
|
||||
*
|
||||
* <p>Conversations with friends are kept by the service and loaded a page at a time. Those with
|
||||
* other Incari players on the same server live only here and go when the player leaves, since a
|
||||
* player's {@code pid} means nothing on another server.
|
||||
*
|
||||
* <p>Game thread only.
|
||||
*/
|
||||
public final class Social {
|
||||
|
||||
/** At most this many messages a conversation keeps in memory; older ones load again on demand. */
|
||||
static final int MAX_KEPT = 300;
|
||||
|
||||
/** Who may message the player. */
|
||||
public enum MessagesFrom {
|
||||
/** Friends, and Incari players on the same server. */
|
||||
EVERYONE("everyone", "Friends and players on your server"),
|
||||
/** Friends only: the default. */
|
||||
FRIENDS("friends", "Friends only"),
|
||||
/** Nobody: messaging is off. */
|
||||
NOBODY("nobody", "Nobody (off)");
|
||||
|
||||
final String wire;
|
||||
private final String label;
|
||||
|
||||
MessagesFrom(String wire, String label) {
|
||||
this.wire = wire;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
/** What the settings call it. */
|
||||
public String label() {
|
||||
return label;
|
||||
}
|
||||
|
||||
static MessagesFrom of(String wire) {
|
||||
for (MessagesFrom each : values()) {
|
||||
if (each.wire.equals(wire)) {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
return FRIENDS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A friend.
|
||||
*
|
||||
* @param fid the service's id for the friendship
|
||||
* @param username their Incari username: friends know each other's
|
||||
* @param online whether they're connected to the service now
|
||||
* @param server the server they're on, if they share it with friends and are on one
|
||||
*/
|
||||
public record Friend(
|
||||
String fid,
|
||||
String username,
|
||||
boolean online,
|
||||
@Nullable String server) {}
|
||||
|
||||
/**
|
||||
* A friend request, either way.
|
||||
*
|
||||
* @param label the sender's username for one received; for one sent, the name it was sent to
|
||||
*/
|
||||
public record Request(String rid, boolean incoming, String label) {}
|
||||
|
||||
/** Where a message is: sent, still going, or turned away. */
|
||||
public enum Delivery {
|
||||
SENT,
|
||||
SENDING,
|
||||
/** The service wouldn't deliver it: they don't take messages from the player, or it was too fast. */
|
||||
FAILED
|
||||
}
|
||||
|
||||
/** One message in a conversation. */
|
||||
public record Message(String mid, boolean mine, String text, long at, Delivery delivery) {}
|
||||
|
||||
/**
|
||||
* Who a conversation is with: a friend (by {@code fid}) or an Incari player on this server (by
|
||||
* {@code pid}). {@link #key} names the conversation.
|
||||
*/
|
||||
public record Peer(boolean friend, String id, String label) {
|
||||
/** The conversation's name: the same for one person whatever their label. */
|
||||
public String key() {
|
||||
return (friend ? "f:" : "p:") + id;
|
||||
}
|
||||
}
|
||||
|
||||
/** One conversation's messages, oldest first. */
|
||||
public static final class Conversation {
|
||||
private final List<Message> messages = new ArrayList<>();
|
||||
private int unread;
|
||||
/** Whether the service has older messages than the first here (friends only). */
|
||||
private boolean more = true;
|
||||
|
||||
private boolean loading;
|
||||
private boolean loaded;
|
||||
/**
|
||||
* Whether messages may have come while the client was disconnected: if so, the newest page
|
||||
* is reloaded before anything is marked read.
|
||||
*/
|
||||
private boolean stale;
|
||||
|
||||
public List<Message> messages() {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public int unread() {
|
||||
return unread;
|
||||
}
|
||||
|
||||
/** Whether older messages can be loaded. */
|
||||
public boolean hasMore() {
|
||||
return more;
|
||||
}
|
||||
|
||||
/** Whether a page of older messages is on its way. */
|
||||
public boolean loading() {
|
||||
return loading;
|
||||
}
|
||||
|
||||
boolean loaded() {
|
||||
return loaded;
|
||||
}
|
||||
|
||||
void startLoading() {
|
||||
loading = true;
|
||||
}
|
||||
|
||||
/** Older messages arrived, oldest first. */
|
||||
void older(List<Message> page, boolean hasMore) {
|
||||
loading = false;
|
||||
loaded = true;
|
||||
more = hasMore;
|
||||
List<Message> merged = new ArrayList<>(page.size() + messages.size());
|
||||
for (Message each : page) {
|
||||
if (find(each.mid()) < 0) {
|
||||
merged.add(each);
|
||||
}
|
||||
}
|
||||
merged.addAll(messages);
|
||||
messages.clear();
|
||||
messages.addAll(merged);
|
||||
}
|
||||
|
||||
boolean stale() {
|
||||
return stale;
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest page arrived again, oldest first, after a reconnect. Joined to what's held if
|
||||
* they meet; if they don't (more came meanwhile than a page), the page replaces them, and
|
||||
* scrolling up loads the rest again. The player's own unsent messages stay either way.
|
||||
*/
|
||||
void newest(List<Message> page, boolean hasMore) {
|
||||
loading = false;
|
||||
loaded = true;
|
||||
stale = false;
|
||||
boolean meets = messages.isEmpty();
|
||||
for (Message each : page) {
|
||||
if (find(each.mid()) >= 0) {
|
||||
meets = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
List<Message> merged = new ArrayList<>(page.size() + messages.size());
|
||||
if (meets) {
|
||||
if (messages.isEmpty()) {
|
||||
more = hasMore;
|
||||
}
|
||||
merged.addAll(messages);
|
||||
for (Message each : page) {
|
||||
if (find(each.mid()) < 0) {
|
||||
merged.add(each);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
more = hasMore;
|
||||
merged.addAll(page);
|
||||
for (Message each : messages) {
|
||||
if (each.delivery() != Delivery.SENT) {
|
||||
merged.add(each);
|
||||
}
|
||||
}
|
||||
}
|
||||
merged.sort((a, b) -> Long.compare(a.at(), b.at()));
|
||||
while (merged.size() > MAX_KEPT) {
|
||||
merged.remove(0);
|
||||
more = true;
|
||||
}
|
||||
messages.clear();
|
||||
messages.addAll(merged);
|
||||
}
|
||||
|
||||
void loadFailed() {
|
||||
loading = false;
|
||||
}
|
||||
|
||||
/** A new message at the end; drops the oldest past {@link #MAX_KEPT}. */
|
||||
void add(Message message) {
|
||||
if (find(message.mid()) >= 0) {
|
||||
return;
|
||||
}
|
||||
messages.add(message);
|
||||
if (messages.size() > MAX_KEPT) {
|
||||
messages.remove(0);
|
||||
more = true;
|
||||
}
|
||||
}
|
||||
|
||||
void replace(String mid, Message message) {
|
||||
int at = find(mid);
|
||||
if (at >= 0) {
|
||||
messages.set(at, message);
|
||||
}
|
||||
}
|
||||
|
||||
int find(String mid) {
|
||||
for (int i = messages.size() - 1; i >= 0; i--) {
|
||||
if (messages.get(i).mid().equals(mid)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void unread(int count) {
|
||||
unread = count;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Something to tell the player about while the chat menu is closed: a toast.
|
||||
*
|
||||
* @param who whose it is, for the picture
|
||||
* @param request whether it's about friends (a request, a new friend) rather than a message
|
||||
*/
|
||||
public record Notice(String who, boolean request, String title, String text) {}
|
||||
|
||||
private @Nullable Boolean available;
|
||||
private boolean loaded;
|
||||
private final Map<String, Friend> friends = new LinkedHashMap<>();
|
||||
private final Map<String, Request> requests = new LinkedHashMap<>();
|
||||
private final Map<String, Conversation> conversations = new LinkedHashMap<>();
|
||||
/** The names of the Incari players on this server whose conversations are here, by pid. */
|
||||
private final Map<String, String> playerNames = new LinkedHashMap<>();
|
||||
/** The pid each request sent to a player on this server went to, by rid. */
|
||||
private final Map<String, String> sentToPid = new HashMap<>();
|
||||
|
||||
private final List<Notice> notices = new ArrayList<>();
|
||||
private MessagesFrom messagesFrom = MessagesFrom.FRIENDS;
|
||||
private boolean friendRequests = true;
|
||||
private long revision;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// What the chat menu reads
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Whether the service has friends and messages: null until it answers, false for a service that
|
||||
* doesn't speak them yet.
|
||||
*/
|
||||
public @Nullable Boolean available() {
|
||||
return available;
|
||||
}
|
||||
|
||||
/** Whether the friend list has arrived since signing in. */
|
||||
public boolean loaded() {
|
||||
return loaded;
|
||||
}
|
||||
|
||||
/** Every friend: online ones first, then by name. */
|
||||
public List<Friend> friends() {
|
||||
List<Friend> list = new ArrayList<>(friends.values());
|
||||
list.sort((a, b) -> a.online() != b.online()
|
||||
? (a.online() ? -1 : 1)
|
||||
: String.CASE_INSENSITIVE_ORDER.compare(a.username(), b.username()));
|
||||
return list;
|
||||
}
|
||||
|
||||
public @Nullable Friend friend(String fid) {
|
||||
return friends.get(fid);
|
||||
}
|
||||
|
||||
/** Friend requests: received ones first, newest last within each. */
|
||||
public List<Request> requests() {
|
||||
List<Request> list = new ArrayList<>();
|
||||
for (Request each : requests.values()) {
|
||||
if (each.incoming()) {
|
||||
list.add(each);
|
||||
}
|
||||
}
|
||||
for (Request each : requests.values()) {
|
||||
if (!each.incoming()) {
|
||||
list.add(each);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* The friend request the player sent to {@code peer}, an Incari player on this server, still
|
||||
* waiting; null if there's none. Never a request received: its label is the sender's Incari
|
||||
* username, which says nothing about who they are here. Known by the player's {@code pid} when
|
||||
* it was sent from here; otherwise (sent before a reconnect, or elsewhere) by the name it was
|
||||
* sent to.
|
||||
*/
|
||||
public @Nullable Request sentTo(Peer peer) {
|
||||
if (peer.friend()) {
|
||||
return null;
|
||||
}
|
||||
for (Request each : requests.values()) {
|
||||
if (!each.incoming() && peer.id().equals(sentToPid.get(each.rid()))) {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
for (Request each : requests.values()) {
|
||||
if (!each.incoming()
|
||||
&& !sentToPid.containsKey(each.rid())
|
||||
&& each.label().equalsIgnoreCase(peer.label())) {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The conversation with {@code peer}, made empty if there's none yet. */
|
||||
public Conversation conversation(Peer peer) {
|
||||
return conversations.computeIfAbsent(peer.key(), key -> new Conversation());
|
||||
}
|
||||
|
||||
/** The conversation with {@code peer}, or null if nothing was said yet. */
|
||||
public @Nullable Conversation existing(Peer peer) {
|
||||
return conversations.get(peer.key());
|
||||
}
|
||||
|
||||
/**
|
||||
* Incari players on this server who messaged the player, by pid, with the names they had: they
|
||||
* stay in the list after leaving, until the player does.
|
||||
*/
|
||||
public Map<String, String> playersMessaged() {
|
||||
return Map.copyOf(playerNames);
|
||||
}
|
||||
|
||||
/** Unread messages across every conversation. */
|
||||
public int unread() {
|
||||
int total = 0;
|
||||
for (Conversation each : conversations.values()) {
|
||||
total += each.unread;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Received friend requests waiting for an answer. */
|
||||
public int pendingRequests() {
|
||||
int count = 0;
|
||||
for (Request each : requests.values()) {
|
||||
count += each.incoming() ? 1 : 0;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public MessagesFrom messagesFrom() {
|
||||
return messagesFrom;
|
||||
}
|
||||
|
||||
/** Whether others can send the player friend requests. */
|
||||
public boolean friendRequests() {
|
||||
return friendRequests;
|
||||
}
|
||||
|
||||
/** What happened since the last call, to show as toasts; taken. */
|
||||
public List<Notice> takeNotices() {
|
||||
if (notices.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Notice> taken = List.copyOf(notices);
|
||||
notices.clear();
|
||||
return taken;
|
||||
}
|
||||
|
||||
/** A number that goes up whenever anything here changes. */
|
||||
public long revision() {
|
||||
return revision;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// What the service changes
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
void settings(MessagesFrom from, boolean requests) {
|
||||
messagesFrom = from;
|
||||
friendRequests = requests;
|
||||
revision++;
|
||||
}
|
||||
|
||||
void available(boolean yes) {
|
||||
available = yes;
|
||||
revision++;
|
||||
}
|
||||
|
||||
/**
|
||||
* The full list, after signing in (and after each reconnect): replaces what was here. The
|
||||
* friends' conversations still held may have missed messages meanwhile: they're marked stale,
|
||||
* and their newest page loads again when next shown. Their unread counts are the service's.
|
||||
*/
|
||||
void loaded(List<Friend> friendList, List<Request> requestList, Map<String, Integer> unread) {
|
||||
loaded = true;
|
||||
friends.clear();
|
||||
for (Friend each : friendList) {
|
||||
friends.put(each.fid(), each);
|
||||
}
|
||||
requests.clear();
|
||||
for (Request each : requestList) {
|
||||
requests.put(each.rid(), each);
|
||||
}
|
||||
sentToPid.keySet().retainAll(requests.keySet());
|
||||
for (var each = conversations.entrySet().iterator(); each.hasNext(); ) {
|
||||
Map.Entry<String, Conversation> entry = each.next();
|
||||
String key = entry.getKey();
|
||||
if (!key.startsWith("f:")) {
|
||||
continue;
|
||||
}
|
||||
if (!friends.containsKey(key.substring(2))) {
|
||||
// Unfriended while the client wasn't connected: the conversation went with it.
|
||||
each.remove();
|
||||
continue;
|
||||
}
|
||||
entry.getValue().stale = true;
|
||||
entry.getValue().unread(0);
|
||||
}
|
||||
for (Map.Entry<String, Integer> each : unread.entrySet()) {
|
||||
conversation(new Peer(true, each.getKey(), "")).unread(each.getValue());
|
||||
}
|
||||
revision++;
|
||||
}
|
||||
|
||||
void friend(Friend friend, boolean announce) {
|
||||
Friend old = friends.put(friend.fid(), friend);
|
||||
if (old == null && announce) {
|
||||
notices.add(new Notice(friend.username(), true, "New friend", friend.username() + " is now your friend."));
|
||||
}
|
||||
revision++;
|
||||
}
|
||||
|
||||
void unfriended(String fid) {
|
||||
if (friends.remove(fid) != null) {
|
||||
conversations.remove("f:" + fid);
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
void request(Request request) {
|
||||
if (requests.put(request.rid(), request) == null && request.incoming()) {
|
||||
notices.add(new Notice(request.label(), true, request.label(), "Sent you a friend request"));
|
||||
}
|
||||
revision++;
|
||||
}
|
||||
|
||||
/** The request {@code rid} was sent to the Incari player here with this per-server id. */
|
||||
void requestSentTo(String rid, String pid) {
|
||||
sentToPid.put(rid, pid);
|
||||
revision++;
|
||||
}
|
||||
|
||||
void requestGone(String rid) {
|
||||
sentToPid.remove(rid);
|
||||
if (requests.remove(rid) != null) {
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
/** A message arrived, or one of the player's was sent. */
|
||||
void message(Peer peer, Message message, boolean viewing) {
|
||||
Conversation conversation = conversation(peer);
|
||||
conversation.add(message);
|
||||
if (!peer.friend()) {
|
||||
playerNames.put(peer.id(), peer.label());
|
||||
}
|
||||
if (!message.mine() && !viewing) {
|
||||
conversation.unread(conversation.unread + 1);
|
||||
notices.add(new Notice(peer.label(), false, peer.label(), message.text()));
|
||||
}
|
||||
revision++;
|
||||
}
|
||||
|
||||
void replace(Peer peer, String mid, Message message) {
|
||||
conversation(peer).replace(mid, message);
|
||||
revision++;
|
||||
}
|
||||
|
||||
void older(Peer peer, List<Message> page, boolean more) {
|
||||
conversation(peer).older(page, more);
|
||||
revision++;
|
||||
}
|
||||
|
||||
void newest(Peer peer, List<Message> page, boolean more) {
|
||||
conversation(peer).newest(page, more);
|
||||
revision++;
|
||||
}
|
||||
|
||||
void loadFailed(Peer peer) {
|
||||
conversation(peer).loadFailed();
|
||||
revision++;
|
||||
}
|
||||
|
||||
void read(Peer peer) {
|
||||
Conversation conversation = conversations.get(peer.key());
|
||||
if (conversation != null && conversation.unread > 0) {
|
||||
conversation.unread(0);
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
/** The player left the server: conversations with its players go, their ids meaning nothing now. */
|
||||
void leftServer() {
|
||||
if (playerNames.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (String pid : playerNames.keySet()) {
|
||||
conversations.remove("p:" + pid);
|
||||
}
|
||||
playerNames.clear();
|
||||
revision++;
|
||||
}
|
||||
|
||||
/** Signed out: everything goes. */
|
||||
void clear() {
|
||||
available = null;
|
||||
loaded = false;
|
||||
friends.clear();
|
||||
requests.clear();
|
||||
conversations.clear();
|
||||
playerNames.clear();
|
||||
sentToPid.clear();
|
||||
notices.clear();
|
||||
messagesFrom = MessagesFrom.FRIENDS;
|
||||
friendRequests = true;
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package incari.online;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import incari.framework.config.ConfigStorage;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The player's own cosmetics (ADR 0061): what they wear, what they own, their saved outfits, and
|
||||
* whether they see other players' cosmetics. Kept on this device in {@code wardrobe.json} under the
|
||||
* client's {@code incari/online}, so what's worn shows at once and without an account; while
|
||||
* signed in, the account's wardrobe on the service is the truth and this follows it.
|
||||
*
|
||||
* <p>Changes apply here at once, so the wardrobe screen never waits on the service;
|
||||
* {@link OnlineService} sends {@code equip} once the player stops, at most once a second.
|
||||
*
|
||||
* <p>Game thread only.
|
||||
*/
|
||||
public final class Wardrobe {
|
||||
|
||||
static final String FILE = "wardrobe.json";
|
||||
|
||||
/** The most outfits kept. */
|
||||
public static final int MAX_OUTFITS = 12;
|
||||
|
||||
/** The longest outfit name. */
|
||||
public static final int MAX_OUTFIT_NAME = 24;
|
||||
|
||||
/** A loadout the player saved under a name, to put on again in one click. */
|
||||
public record Outfit(String name, Loadout loadout) {}
|
||||
|
||||
private final ConfigStorage storage;
|
||||
private final OnlineService.Log log;
|
||||
|
||||
private Loadout worn = Loadout.EMPTY;
|
||||
/** The non-free cosmetics the account owns, as the service last said. */
|
||||
private final Set<String> owned = new HashSet<>();
|
||||
|
||||
private final List<Outfit> outfits = new ArrayList<>();
|
||||
private boolean showOthers = true;
|
||||
|
||||
/** Whether the account's wardrobe arrived on this connection: what's worn is then the account's. */
|
||||
private boolean synced;
|
||||
/** Whether it arrived at all since signing in (a reconnect keeps changes made while away). */
|
||||
private boolean accountSeen;
|
||||
/** Whether what's worn changed here and the service hasn't heard yet. */
|
||||
private boolean unsent;
|
||||
|
||||
private long revision;
|
||||
|
||||
Wardrobe(ConfigStorage storage, OnlineService.Log log) {
|
||||
this.storage = storage;
|
||||
this.log = log;
|
||||
load();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// What the screens read
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** What the player wears now. */
|
||||
public Loadout worn() {
|
||||
return worn;
|
||||
}
|
||||
|
||||
/** Whether the player may wear (or play) {@code cosmetic}. */
|
||||
public boolean owns(Cosmetic cosmetic) {
|
||||
return cosmetic.free() || owned.contains(cosmetic.id());
|
||||
}
|
||||
|
||||
/** The emotes the player owns, in the catalog's order: the emote wheel's. */
|
||||
public List<Cosmetic> emotes() {
|
||||
List<Cosmetic> emotes = new ArrayList<>();
|
||||
for (Cosmetic each : Catalog.inSlot(Cosmetic.Slot.EMOTE)) {
|
||||
if (owns(each)) {
|
||||
emotes.add(each);
|
||||
}
|
||||
}
|
||||
return emotes;
|
||||
}
|
||||
|
||||
/** The saved outfits, oldest first. */
|
||||
public List<Outfit> outfits() {
|
||||
return List.copyOf(outfits);
|
||||
}
|
||||
|
||||
/** Whether other players' cosmetics are drawn (the player may find them distracting). */
|
||||
public boolean showOthers() {
|
||||
return showOthers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether other Incari players see what's worn: signed in, with the account's wardrobe here.
|
||||
* Otherwise only this player sees it.
|
||||
*/
|
||||
public boolean shared() {
|
||||
return synced;
|
||||
}
|
||||
|
||||
/** Goes up whenever anything here changes. */
|
||||
public long revision() {
|
||||
return revision;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// What the screens change
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** Puts {@code cosmetic} on, in place of what was in its slot. Ignored for one not owned. */
|
||||
public void wear(Cosmetic cosmetic) {
|
||||
if (owns(cosmetic) && cosmetic.slot().worn()) {
|
||||
change(worn.with(cosmetic));
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes off what's worn in {@code slot}. */
|
||||
public void takeOff(Cosmetic.Slot slot) {
|
||||
change(worn.without(slot));
|
||||
}
|
||||
|
||||
/** Puts on {@code loadout} whole (an outfit, or nothing), leaving out what isn't owned. */
|
||||
public void wear(Loadout loadout) {
|
||||
change(loadout.ownedBy(this::owns));
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves what's worn as an outfit called {@code name} (cut to {@link #MAX_OUTFIT_NAME}), replacing
|
||||
* one of the same name.
|
||||
*
|
||||
* @return false if there's no room for another
|
||||
*/
|
||||
public boolean saveOutfit(String name) {
|
||||
String trimmed = name.strip();
|
||||
if (trimmed.length() > MAX_OUTFIT_NAME) {
|
||||
trimmed = trimmed.substring(0, MAX_OUTFIT_NAME);
|
||||
}
|
||||
if (trimmed.isEmpty()) {
|
||||
trimmed = "Outfit " + (outfits.size() + 1);
|
||||
}
|
||||
for (int i = 0; i < outfits.size(); i++) {
|
||||
if (outfits.get(i).name().equalsIgnoreCase(trimmed)) {
|
||||
outfits.set(i, new Outfit(trimmed, worn));
|
||||
saved();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (outfits.size() >= MAX_OUTFITS) {
|
||||
return false;
|
||||
}
|
||||
outfits.add(new Outfit(trimmed, worn));
|
||||
saved();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Forgets an outfit. */
|
||||
public void deleteOutfit(Outfit outfit) {
|
||||
if (outfits.remove(outfit)) {
|
||||
saved();
|
||||
}
|
||||
}
|
||||
|
||||
/** Draws other players' cosmetics, or not. */
|
||||
public void setShowOthers(boolean show) {
|
||||
if (show != showOthers) {
|
||||
showOthers = show;
|
||||
saved();
|
||||
}
|
||||
}
|
||||
|
||||
private void change(Loadout next) {
|
||||
if (next.equals(worn)) {
|
||||
return;
|
||||
}
|
||||
worn = next;
|
||||
unsent = true;
|
||||
saved();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The service's side (OnlineService)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The account's wardrobe arrived. On signing in, what the account wears replaces what's worn
|
||||
* here, unless the account wears nothing yet and this device does: then the device's is kept and
|
||||
* sent, so what a player picked before making an account carries over. Later (a reconnect, or
|
||||
* another session's change), a change made here and not yet sent wins: the player made it after
|
||||
* the service's answer left.
|
||||
*
|
||||
* @return whether what's worn here should be sent
|
||||
*/
|
||||
boolean fromAccount(Set<String> ownedIds, Loadout equipped) {
|
||||
owned.clear();
|
||||
owned.addAll(ownedIds);
|
||||
boolean keep = accountSeen ? unsent : equipped.isEmpty() && !worn.isEmpty();
|
||||
synced = true;
|
||||
accountSeen = true;
|
||||
if (keep) {
|
||||
worn = worn.ownedBy(this::owns);
|
||||
} else {
|
||||
worn = equipped.ownedBy(this::owns);
|
||||
}
|
||||
unsent = keep;
|
||||
saved();
|
||||
return unsent;
|
||||
}
|
||||
|
||||
/** The service took what was sent; {@code equipped} is what it keeps. */
|
||||
void sent(Loadout sentLoadout, Loadout equipped) {
|
||||
if (worn.equals(sentLoadout)) {
|
||||
unsent = false;
|
||||
if (!equipped.equals(worn)) {
|
||||
worn = equipped.ownedBy(this::owns);
|
||||
saved();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What's worn here, if the service hasn't heard of it yet and is to; null otherwise. */
|
||||
@Nullable
|
||||
Loadout unsent() {
|
||||
return synced && unsent ? worn : null;
|
||||
}
|
||||
|
||||
/** Signed out: what the device keeps is what was worn, less what only the account owned. */
|
||||
void signedOut() {
|
||||
synced = false;
|
||||
accountSeen = false;
|
||||
unsent = false;
|
||||
owned.clear();
|
||||
worn = worn.ownedBy(this::owns);
|
||||
saved();
|
||||
}
|
||||
|
||||
/** The connection dropped: the account's wardrobe is asked for again when it's back. */
|
||||
void disconnected() {
|
||||
if (synced) {
|
||||
synced = false;
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The file
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
private void saved() {
|
||||
revision++;
|
||||
JsonObject json = new JsonObject();
|
||||
json.add("worn", ids(worn.ids()));
|
||||
json.add("owned", ids(List.copyOf(owned)));
|
||||
JsonArray list = new JsonArray();
|
||||
for (Outfit outfit : outfits) {
|
||||
JsonObject each = new JsonObject();
|
||||
each.addProperty("name", outfit.name());
|
||||
each.add("worn", ids(outfit.loadout().ids()));
|
||||
list.add(each);
|
||||
}
|
||||
json.add("outfits", list);
|
||||
json.addProperty("showOthers", showOthers);
|
||||
try {
|
||||
storage.write(FILE, json.toString());
|
||||
} catch (IOException e) {
|
||||
log.warn("Couldn't save the wardrobe", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void load() {
|
||||
try {
|
||||
String text = storage.read(FILE);
|
||||
if (text == null) {
|
||||
return;
|
||||
}
|
||||
JsonObject json = JsonParser.parseString(text).getAsJsonObject();
|
||||
for (String id : strings(json, "owned")) {
|
||||
owned.add(id);
|
||||
}
|
||||
worn = Loadout.of(strings(json, "worn")).ownedBy(this::owns);
|
||||
if (json.get("outfits") instanceof JsonArray list) {
|
||||
for (JsonElement each : list) {
|
||||
if (each instanceof JsonObject outfit && outfit.has("name") && outfits.size() < MAX_OUTFITS) {
|
||||
outfits.add(new Outfit(outfit.get("name").getAsString(), Loadout.of(strings(outfit, "worn"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (json.has("showOthers")) {
|
||||
showOthers = json.get("showOthers").getAsBoolean();
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
// A broken file costs the player their outfits, not their game.
|
||||
log.warn("Couldn't read the wardrobe; starting with nothing worn", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonArray ids(List<String> ids) {
|
||||
JsonArray array = new JsonArray(ids.size());
|
||||
for (String id : ids) {
|
||||
array.add(id);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
private static List<String> strings(JsonObject json, String key) {
|
||||
List<String> out = new ArrayList<>();
|
||||
if (json.get(key) instanceof JsonArray array) {
|
||||
for (JsonElement each : array) {
|
||||
if (each.isJsonPrimitive()) {
|
||||
out.add(each.getAsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package incari.online;
|
||||
|
||||
import incari.framework.online.IncariPlayer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The world the player is in, as the service hears of it, and which players in its tab list are
|
||||
* Incari players (ADR 0058). Each name is looked up once as it appears, and the answer kept until
|
||||
* the player leaves; the service's {@code seen}, {@code gone} and {@code cosmetics} events keep it
|
||||
* current.
|
||||
*
|
||||
* <p>Game thread only.
|
||||
*/
|
||||
final class WorldPlayers {
|
||||
|
||||
/** At most this many names a lookup (the service's limit). */
|
||||
static final int MAX_LOOKUP = 256;
|
||||
|
||||
/** At least this long between lookups: the service allows ten a minute. */
|
||||
static final long LOOKUP_INTERVAL_MILLIS = 6_500;
|
||||
|
||||
/** Where the player is: the server's hash, their name there, and the plain address. */
|
||||
record Place(String serverHash, String name, String address) {}
|
||||
|
||||
private @Nullable Place place;
|
||||
/**
|
||||
* The tab list: the UUIDs under each name, and each UUID's name. One name can have several: a
|
||||
* server's NPCs often take a player's name. A name is forgotten when its last UUID goes.
|
||||
*/
|
||||
private final Map<String, Set<UUID>> ids = new HashMap<>();
|
||||
|
||||
private final Map<UUID, String> names = new HashMap<>();
|
||||
/** The Incari players among them, by name; and each one's name by their per-server id. */
|
||||
private final Map<String, IncariPlayer> players = new HashMap<>();
|
||||
|
||||
private final Map<String, String> namesByPid = new HashMap<>();
|
||||
/** Names in the tab list not yet asked about. */
|
||||
private final Set<String> unasked = new LinkedHashSet<>();
|
||||
|
||||
private long nextLookup;
|
||||
private long revision;
|
||||
|
||||
/** The player joined a server through {@code address}, as {@code name}. Forgets the last world. */
|
||||
void join(String address, String name) {
|
||||
clear();
|
||||
place = new Place(ServerHash.of(address), name, address);
|
||||
revision++;
|
||||
}
|
||||
|
||||
/** The player left the world (or is in singleplayer, which the service never hears of). */
|
||||
void leave() {
|
||||
clear();
|
||||
place = null;
|
||||
revision++;
|
||||
}
|
||||
|
||||
private void clear() {
|
||||
ids.clear();
|
||||
names.clear();
|
||||
players.clear();
|
||||
namesByPid.clear();
|
||||
unasked.clear();
|
||||
nextLookup = 0;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
Place place() {
|
||||
return place;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab list as it is now: names that are new are queued for a lookup, and players who left
|
||||
* are forgotten. Cheap when nothing changed.
|
||||
*/
|
||||
void tabList(Map<UUID, String> now) {
|
||||
if (place == null || now.equals(names)) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<UUID, String> entry : List.copyOf(names.entrySet())) {
|
||||
if (!entry.getValue().equals(now.get(entry.getKey()))) {
|
||||
String name = entry.getValue();
|
||||
names.remove(entry.getKey());
|
||||
Set<UUID> same = ids.get(name);
|
||||
if (same != null) {
|
||||
UUID owner = uuidOf(name);
|
||||
same.remove(entry.getKey());
|
||||
if (!same.isEmpty()) {
|
||||
// Someone else by that name is still here, so an NPC leaving takes nobody's
|
||||
// badge. If the account's player left, look the name up again rather than
|
||||
// give the account to whoever is left.
|
||||
if (entry.getKey().equals(owner)) {
|
||||
IncariPlayer gone = players.remove(name);
|
||||
if (gone != null) {
|
||||
namesByPid.remove(gone.pid());
|
||||
}
|
||||
if (!name.equals(place.name())) {
|
||||
unasked.add(name);
|
||||
}
|
||||
}
|
||||
revision++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ids.remove(name);
|
||||
unasked.remove(name);
|
||||
IncariPlayer gone = players.remove(name);
|
||||
if (gone != null) {
|
||||
namesByPid.remove(gone.pid());
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Map.Entry<UUID, String> entry : now.entrySet()) {
|
||||
if (!names.containsKey(entry.getKey())) {
|
||||
names.put(entry.getKey(), entry.getValue());
|
||||
Set<UUID> same = ids.computeIfAbsent(entry.getValue(), name -> new LinkedHashSet<>());
|
||||
same.add(entry.getKey());
|
||||
if (same.size() == 1 && !entry.getValue().equals(place.name())) {
|
||||
unasked.add(entry.getValue());
|
||||
} else if (same.size() > 1) {
|
||||
// Which of them the account is may change.
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The UUID an Incari account under {@code name} goes with: of several under one name, the first
|
||||
* that looks like a player's (version 4, online mode; version 3, offline mode), since NPCs
|
||||
* that copy a player's name usually have other versions (Citizens uses 2); else the first.
|
||||
*/
|
||||
private @Nullable UUID uuidOf(String name) {
|
||||
Set<UUID> same = ids.get(name);
|
||||
if (same == null || same.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
for (UUID each : same) {
|
||||
if (each.version() == 4 || each.version() == 3) {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
return same.iterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* The names to look up now, at most {@link #MAX_LOOKUP}, or an empty list if there are none or
|
||||
* the last lookup was too recent. The names are taken: if the lookup fails, {@link #askAgain}.
|
||||
*/
|
||||
List<String> takeLookup(long now) {
|
||||
if (place == null || unasked.isEmpty() || now < nextLookup) {
|
||||
return List.of();
|
||||
}
|
||||
nextLookup = now + LOOKUP_INTERVAL_MILLIS;
|
||||
List<String> batch = new ArrayList<>(Math.min(MAX_LOOKUP, unasked.size()));
|
||||
var each = unasked.iterator();
|
||||
while (each.hasNext() && batch.size() < MAX_LOOKUP) {
|
||||
batch.add(each.next());
|
||||
each.remove();
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
/** A lookup that didn't get through: its names (those still in the tab list) are asked again later. */
|
||||
void askAgain(List<String> batch) {
|
||||
for (String name : batch) {
|
||||
if (ids.containsKey(name) && !players.containsKey(name)) {
|
||||
unasked.add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Every name in the tab list is asked about again: after a reconnect, the service forgot them. */
|
||||
void askAll() {
|
||||
if (place == null) {
|
||||
return;
|
||||
}
|
||||
for (String name : ids.keySet()) {
|
||||
if (!name.equals(place.name())) {
|
||||
unasked.add(name);
|
||||
}
|
||||
}
|
||||
if (!players.isEmpty()) {
|
||||
players.clear();
|
||||
namesByPid.clear();
|
||||
revision++;
|
||||
}
|
||||
nextLookup = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code name} is an Incari player here ({@code seen}, or a lookup's answer). Ignored for a name
|
||||
* not in the tab list: the answer came after they left.
|
||||
*/
|
||||
void seen(String name, IncariPlayer player) {
|
||||
if (!ids.containsKey(name)) {
|
||||
return;
|
||||
}
|
||||
IncariPlayer old = players.put(name, player);
|
||||
if (old != null) {
|
||||
namesByPid.remove(old.pid());
|
||||
}
|
||||
namesByPid.put(player.pid(), name);
|
||||
revision++;
|
||||
}
|
||||
|
||||
/** The account with this per-server id left, signed out, or blocked the player. */
|
||||
void gone(String pid) {
|
||||
String name = namesByPid.remove(pid);
|
||||
if (name != null) {
|
||||
players.remove(name);
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
/** The account with this per-server id wears other cosmetics now. */
|
||||
void cosmetics(String pid, List<String> cosmetics) {
|
||||
String name = namesByPid.get(pid);
|
||||
IncariPlayer old = name == null ? null : players.get(name);
|
||||
if (name != null && old != null) {
|
||||
players.put(name, new IncariPlayer(pid, old.friend(), cosmetics, old.badge()));
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
/** The service's {@code badge} event: an Incari player here showed or hid the badge. */
|
||||
void badge(String pid, boolean badge) {
|
||||
String name = namesByPid.get(pid);
|
||||
IncariPlayer old = name == null ? null : players.get(name);
|
||||
if (name != null && old != null && old.badge() != badge) {
|
||||
players.put(name, new IncariPlayer(pid, old.friend(), old.cosmetics(), badge));
|
||||
revision++;
|
||||
}
|
||||
}
|
||||
|
||||
/** The UUID of the player whose account has this per-server id, or null. */
|
||||
@Nullable
|
||||
UUID uuid(String pid) {
|
||||
String name = namesByPid.get(pid);
|
||||
return name == null ? null : uuidOf(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Incari player with this UUID in the world, or null. Of several players under one name
|
||||
* only one is the account's ({@link #uuidOf}): an NPC by the same name shows no badge.
|
||||
*/
|
||||
@Nullable
|
||||
IncariPlayer player(UUID id) {
|
||||
String name = names.get(id);
|
||||
return name == null || !id.equals(uuidOf(name)) ? null : players.get(name);
|
||||
}
|
||||
|
||||
/** The Incari players in the world by name, for the blocking and reporting screen. */
|
||||
Map<String, IncariPlayer> players() {
|
||||
return Map.copyOf(players);
|
||||
}
|
||||
|
||||
long revision() {
|
||||
return revision;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Incari accounts and the online service, client side (ADR 0058): one WebSocket to the service, the
|
||||
* account requests, the session store, proof of work, presence and the lookup cache. No game types.
|
||||
*/
|
||||
@NullMarked
|
||||
package incari.online;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -0,0 +1,84 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.framework.online.IncariPlayer;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** ADR 0062's additions: featured servers in hello, usage counts, and the Incari badge. */
|
||||
class Adr0062Test {
|
||||
|
||||
private static final String PASSWORD = "correct horse battery";
|
||||
private static final UUID ALEX = new UUID(1, 1);
|
||||
private static final UUID STEVE = new UUID(2, 2);
|
||||
|
||||
private final FakeService fake = new FakeService();
|
||||
|
||||
private Client started() {
|
||||
Client client = new Client(fake);
|
||||
client.service.start();
|
||||
return client.settle();
|
||||
}
|
||||
|
||||
private Client signedUp(String username) {
|
||||
Client client = started();
|
||||
Result<List<String>> result = client.await(done -> client.service.signUp(username, PASSWORD, done));
|
||||
assertThat(result.ok()).isTrue();
|
||||
return client;
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloReplacesTheFeaturedServersOnlyWhenItNamesThem() {
|
||||
assertThat(started().service.featuredServers()).isNull();
|
||||
fake.featured = List.of(
|
||||
new String[] {"Carrotcraft", "wss://eagler.carrot-craft.org"},
|
||||
new String[] {"", "wss://nameless.example"},
|
||||
new String[] {"Spaces", "wss://bad address"});
|
||||
assertThat(started().service.featuredServers())
|
||||
.containsExactly(new OnlineService.Featured("Carrotcraft", "wss://eagler.carrot-craft.org"));
|
||||
fake.featured = List.of();
|
||||
assertThat(started().service.featuredServers()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCountGoesOutSignedOutAndFailsOffline() {
|
||||
Client client = started();
|
||||
Result<Void> sent = client.await(done -> client.service.count("AAAAAAAAAAAAAAAAAAAAAA", "0.2.0", "fast", done));
|
||||
assertThat(sent.ok()).isTrue();
|
||||
assertThat(fake.counts).hasSize(1);
|
||||
assertThat(fake.counts.get(0)).containsExactly("AAAAAAAAAAAAAAAAAAAAAA", "0.2.0", "fast");
|
||||
|
||||
Client offline = new Client(fake);
|
||||
Result<Void> failed =
|
||||
offline.await(done -> offline.service.count("AAAAAAAAAAAAAAAAAAAAAA", "0.2.0", "fast", done));
|
||||
assertThat(failed.ok()).isFalse();
|
||||
assertThat(fake.counts).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBadgeShowsUntilTheAccountHidesItAndOthersHearOfTheChange() {
|
||||
Client alex = signedUp("AlexAccount");
|
||||
Client steve = signedUp("SteveAccount");
|
||||
assertThat(alex.service.showsBadge()).isTrue();
|
||||
Map<UUID, String> tab = Map.of(ALEX, "Alex", STEVE, "Steve");
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.service.tabList(tab);
|
||||
alex.settle();
|
||||
steve.service.joined("play.example.com", "Steve");
|
||||
steve.service.tabList(tab);
|
||||
steve.settle();
|
||||
IncariPlayer seen = steve.service.player(ALEX);
|
||||
assertThat(seen).isNotNull();
|
||||
assertThat(seen.badge()).isTrue();
|
||||
|
||||
Result<Void> hidden = alex.await(done -> alex.service.setShowBadge(false, done));
|
||||
assertThat(hidden.ok()).isTrue();
|
||||
assertThat(alex.service.showsBadge()).isFalse();
|
||||
steve.settle();
|
||||
assertThat(Objects.requireNonNull(steve.service.player(ALEX)).badge()).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package incari.online;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
|
||||
import com.tngtech.archunit.core.importer.ImportOption;
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
|
||||
/**
|
||||
* The online client holds no game, LWJGL or TeaVM types: the JDK's basics, Gson's tree API for the
|
||||
* messages, the platform's network and the framework's views.
|
||||
*/
|
||||
@AnalyzeClasses(packages = "incari.online", importOptions = ImportOption.DoNotIncludeTests.class)
|
||||
class BoundaryTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule onlyJdkGsonPlatformAndFramework = classes()
|
||||
.should()
|
||||
.onlyDependOnClassesThat()
|
||||
.resideInAnyPackage(
|
||||
"java.lang..",
|
||||
"java.util..",
|
||||
"java.io",
|
||||
"java.nio",
|
||||
"java.nio.charset",
|
||||
"org.jspecify..",
|
||||
"com.google.gson..",
|
||||
"incari.platform.api.net",
|
||||
"incari.framework.config",
|
||||
"incari.framework.online",
|
||||
"incari.online..");
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package incari.online;
|
||||
|
||||
import incari.framework.config.ConfigStorage;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** One client against a {@link FakeService}: a service, its storage, a clock the test moves. */
|
||||
final class Client {
|
||||
|
||||
final MemoryStorage storage = new MemoryStorage();
|
||||
final List<String> warnings = new ArrayList<>();
|
||||
long now = 1_000_000;
|
||||
final OnlineService service;
|
||||
|
||||
Client(FakeService fake) {
|
||||
this(fake, new MemoryStorage());
|
||||
}
|
||||
|
||||
Client(FakeService fake, MemoryStorage files) {
|
||||
this.storage.files.putAll(files.files);
|
||||
this.service = new OnlineService(
|
||||
"wss://online.test/v1/ws",
|
||||
"test",
|
||||
fake,
|
||||
storage,
|
||||
Runnable::run,
|
||||
() -> {},
|
||||
() -> now,
|
||||
() -> 0.5,
|
||||
(message, error) -> warnings.add(message));
|
||||
}
|
||||
|
||||
/** Ticks a few times, for queued messages and their answers to settle. */
|
||||
Client settle() {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
service.tick();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Runs {@code call} with a callback, settles, and returns what the callback heard. */
|
||||
<T> Result<T> await(Consumer<Consumer<Result<T>>> call) {
|
||||
List<Result<T>> heard = new ArrayList<>();
|
||||
call.accept(heard::add);
|
||||
settle();
|
||||
if (heard.size() != 1) {
|
||||
throw new AssertionError("Heard " + heard.size() + " answers");
|
||||
}
|
||||
return heard.get(0);
|
||||
}
|
||||
|
||||
/** Files by path, in memory. */
|
||||
static final class MemoryStorage implements ConfigStorage {
|
||||
final Map<String, String> files = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public @Nullable String read(String path) {
|
||||
return files.get(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(String path, String text) {
|
||||
files.put(path, text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String path) {
|
||||
files.remove(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import incari.framework.online.IncariPlayer;
|
||||
import incari.framework.online.Online.Status;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class OnlineServiceTest {
|
||||
|
||||
private static final String PASSWORD = "correct horse battery";
|
||||
private static final UUID ALEX = new UUID(1, 1);
|
||||
private static final UUID STEVE = new UUID(2, 2);
|
||||
|
||||
private final FakeService fake = new FakeService();
|
||||
|
||||
private Client started() {
|
||||
Client client = new Client(fake);
|
||||
client.service.start();
|
||||
return client.settle();
|
||||
}
|
||||
|
||||
private Client signedUp(String username) {
|
||||
Client client = started();
|
||||
Result<List<String>> result = client.await(done -> client.service.signUp(username, PASSWORD, done));
|
||||
assertThat(result.ok()).isTrue();
|
||||
return client;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyUrlIsOffAndNeverConnects() {
|
||||
OnlineService off = new OnlineService(
|
||||
"", "test", fake, new Client.MemoryStorage(), Runnable::run, () -> {}, () -> 0, () -> 0, (m, e) -> {});
|
||||
off.start();
|
||||
off.tick();
|
||||
assertThat(off.status()).isEqualTo(Status.OFF);
|
||||
assertThat(fake.sockets).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nothingConnectsBeforeStart() {
|
||||
Client client = new Client(fake).settle();
|
||||
assertThat(fake.sockets).isEmpty();
|
||||
assertThat(client.service.status()).isEqualTo(Status.CONNECTING);
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloLeavesTheClientSignedOut() {
|
||||
Client client = started();
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(fake.received.get(0).get("t").getAsString()).isEqualTo("hello");
|
||||
assertThat(fake.received.get(0).get("v").getAsInt()).isEqualTo(OnlineService.PROTOCOL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloNamesTheLatestRelease() {
|
||||
assertThat(started().service.latestRelease()).isNull();
|
||||
fake.announceRelease("0.3.1");
|
||||
Client client = new Client(fake);
|
||||
long before = client.service.revision();
|
||||
client.service.start();
|
||||
client.settle();
|
||||
assertThat(client.service.latestRelease()).isEqualTo("0.3.1");
|
||||
assertThat(client.service.revision()).isNotEqualTo(before);
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloCarriesTheReleaseNotes() {
|
||||
assertThat(started().service.releaseNotes()).isEmpty();
|
||||
fake.announceRelease("0.3.1", "Faster chunk loading", " A changelog ");
|
||||
assertThat(started().service.releaseNotes()).containsExactly("Faster chunk loading", "A changelog");
|
||||
}
|
||||
|
||||
@Test
|
||||
void releaseNotesThatAreNotPlainTextAreDropped() {
|
||||
String[] notes = new String[Releases.MAX_NOTES + 3];
|
||||
notes[0] = "hidden\u200Bspace";
|
||||
notes[1] = "x".repeat(Releases.MAX_NOTE + 1);
|
||||
for (int i = 2; i < notes.length; i++) {
|
||||
notes[i] = "Change " + i;
|
||||
}
|
||||
fake.announceRelease("0.3.1", notes);
|
||||
List<String> kept = started().service.releaseNotes();
|
||||
assertThat(kept).hasSize(Releases.MAX_NOTES).startsWith("Change 2").doesNotContain(notes[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReleaseThatIsNotAVersionIsIgnored() {
|
||||
fake.announceRelease("0.3.1 <script>");
|
||||
assertThat(started().service.latestRelease()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void signUpSolvesTheChallengeSignsInAndKeepsOnlyTheToken() {
|
||||
Client client = started();
|
||||
Result<List<String>> result = client.await(done -> client.service.signUp("Frost_1", PASSWORD, done));
|
||||
|
||||
assertThat(result.ok()).isTrue();
|
||||
assertThat(result.value()).hasSize(10).allMatch(code -> RecoveryCodes.normalize(code) != null);
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_IN);
|
||||
assertThat(client.service.accountName()).isEqualTo("Frost_1");
|
||||
String saved = client.storage.files.get(SessionStore.FILE);
|
||||
assertThat(saved).contains("token-").doesNotContain(PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTakenUsernameSaysSo() {
|
||||
signedUp("Frost");
|
||||
Client other = started();
|
||||
Result<List<String>> result = other.await(done -> other.service.signUp("frost", PASSWORD, done));
|
||||
assertThat(result.failure()).isEqualTo(Failure.TAKEN);
|
||||
assertThat(other.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSavedSessionResumesOnTheNextStart() {
|
||||
Client first = signedUp("Frost");
|
||||
Client second = new Client(fake, first.storage);
|
||||
assertThat(second.service.accountName()).isEqualTo("Frost");
|
||||
second.service.start();
|
||||
second.settle();
|
||||
assertThat(second.service.status()).isEqualTo(Status.SIGNED_IN);
|
||||
assertThat(fake.last().account).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEndedSessionIsForgottenOnResume() {
|
||||
Client first = signedUp("Frost");
|
||||
fake.accounts.get("frost").tokens.clear();
|
||||
Client second = new Client(fake, first.storage);
|
||||
second.service.start();
|
||||
second.settle();
|
||||
assertThat(second.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(second.service.accountName()).isNull();
|
||||
assertThat(second.storage.files).doesNotContainKey(SessionStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrongPasswordsAndRateLimitsReadTheSame() {
|
||||
signedUp("Frost");
|
||||
Client client = started();
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Frost", "wrong password!", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_CREDENTIALS);
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Nobody", PASSWORD, done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_CREDENTIALS);
|
||||
fake.limitNext = "signin";
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Frost", PASSWORD, done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_CREDENTIALS);
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Frost", PASSWORD, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecoveryCodeSetsANewPasswordOnce() {
|
||||
Client owner = started();
|
||||
List<String> codes = owner.<List<String>>await(done -> owner.service.signUp("Frost", PASSWORD, done))
|
||||
.value();
|
||||
Client client = started();
|
||||
String typed = codes.get(3).toLowerCase(java.util.Locale.ROOT).replace("-", " ");
|
||||
assertThat(client.<Void>await(done -> client.service.recover("Frost", typed, "a new long password", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_IN);
|
||||
// Every other session ended.
|
||||
owner.settle();
|
||||
assertThat(owner.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
|
||||
Client again = started();
|
||||
assertThat(again.<Void>await(done -> again.service.recover("Frost", codes.get(3), "another password!", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_CODE);
|
||||
assertThat(again.<Void>await(done -> again.service.recover("Frost", "not a code", "another password!", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_CODE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountActionsNeedThePassword() {
|
||||
Client client = signedUp("Frost");
|
||||
assertThat(client.<Void>await(done -> client.service.changePassword("wrong", "a new long password", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_PASSWORD);
|
||||
assertThat(client.<Void>await(done -> client.service.changePassword(PASSWORD, "a new long password", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(client.<List<String>>await(done -> client.service.newRecoveryCodes(PASSWORD, done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.WRONG_PASSWORD);
|
||||
assertThat(client.<List<String>>await(done -> client.service.newRecoveryCodes("a new long password", done))
|
||||
.value())
|
||||
.hasSize(10);
|
||||
assertThat(client.<Void>await(done -> client.service.deleteAccount("a new long password", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(fake.accounts).isEmpty();
|
||||
assertThat(client.storage.files).doesNotContainKey(SessionStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signOutEverywhereEndsTheOtherSessions() {
|
||||
Client one = signedUp("Frost");
|
||||
Client two = started();
|
||||
assertThat(two.<Void>await(done -> two.service.signIn("Frost", PASSWORD, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(one.<Void>await(done -> one.service.signOut(true, done)).ok())
|
||||
.isTrue();
|
||||
two.settle();
|
||||
assertThat(one.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(two.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(two.storage.files).doesNotContainKey(SessionStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingOutOfflineStillForgetsTheSession() {
|
||||
Client client = signedUp("Frost");
|
||||
fake.reachable = false;
|
||||
fake.last().drop();
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.CONNECTING);
|
||||
assertThat(client.<Void>await(done -> client.service.signOut(false, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(client.service.accountName()).isNull();
|
||||
assertThat(client.storage.files).doesNotContainKey(SessionStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingOutWhileResumingStaysSignedOut() {
|
||||
Client first = signedUp("Frost");
|
||||
Client second = new Client(fake, first.storage);
|
||||
second.service.start();
|
||||
// The first tick opens and says hello; the second hears hello's answer and sends resume.
|
||||
second.service.tick();
|
||||
second.service.tick();
|
||||
second.service.signOut(false, result -> {});
|
||||
second.settle();
|
||||
assertThat(second.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(second.storage.files).doesNotContainKey(SessionStore.FILE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOutdatedClientStopsTrying() {
|
||||
fake.protocol = OnlineService.PROTOCOL + 1;
|
||||
Client client = started();
|
||||
assertThat(client.service.status()).isEqualTo(Status.UPDATE_NEEDED);
|
||||
client.now += 3_600_000;
|
||||
client.settle();
|
||||
assertThat(fake.sockets).hasSize(1);
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Frost", PASSWORD, done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.UPDATE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreachableServiceIsRetriedWithBackoffAndRequestsFailAtOnce() {
|
||||
fake.reachable = false;
|
||||
Client client = started();
|
||||
assertThat(client.service.status()).isEqualTo(Status.CONNECTING);
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Frost", PASSWORD, done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.OFFLINE);
|
||||
fake.reachable = true;
|
||||
// The first wait is half to all of a second (here, three quarters).
|
||||
client.now += 700;
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.CONNECTING);
|
||||
client.now += 100;
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retryConnectsAtOnce() {
|
||||
fake.reachable = false;
|
||||
Client client = started();
|
||||
fake.reachable = true;
|
||||
client.service.retry();
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSilentServiceTimesOut() {
|
||||
fake.answerHello = false;
|
||||
Client client = started();
|
||||
client.now += OnlineService.OPEN_TIMEOUT_MILLIS;
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.CONNECTING);
|
||||
assertThat(fake.sockets.get(0).isOpen()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedConnectionResumesTheSession() {
|
||||
Client client = signedUp("Frost");
|
||||
fake.last().drop();
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.CONNECTING);
|
||||
assertThat(client.service.accountName()).isEqualTo("Frost");
|
||||
client.now += 1_000;
|
||||
client.settle();
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_IN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void playersOnTheSameServerSeeEachOther() {
|
||||
Client alex = signedUp("AlexAccount");
|
||||
Client steve = signedUp("SteveAccount");
|
||||
Map<UUID, String> tab = Map.of(ALEX, "Alex", STEVE, "Steve");
|
||||
|
||||
alex.service.wardrobe().wear(java.util.Objects.requireNonNull(Catalog.byId("cape.frost")));
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.service.tabList(tab);
|
||||
alex.settle();
|
||||
// The address goes to the service only for friends' sake, and only while shared.
|
||||
JsonObject presence = presence(0);
|
||||
assertThat(presence.get("serverHash").getAsString()).isEqualTo(ServerHash.of("Play.Example.com:25565"));
|
||||
assertThat(presence.get("server").getAsString()).isEqualTo("play.example.com");
|
||||
|
||||
steve.service.joined("PLAY.example.com.", "Steve");
|
||||
steve.service.tabList(tab);
|
||||
steve.settle();
|
||||
|
||||
// Steve's lookup found Alex; Alex heard Steve arrive.
|
||||
IncariPlayer alexSeen = steve.service.player(ALEX);
|
||||
assertThat(alexSeen).isNotNull();
|
||||
assertThat(alexSeen.cosmetics()).containsExactly("cape.frost");
|
||||
assertThat(steve.service.player(STEVE)).isNull();
|
||||
alex.settle();
|
||||
assertThat(alex.service.player(STEVE)).isNotNull();
|
||||
|
||||
// Steve leaves: Alex hears it, once the grace for a server switch is over.
|
||||
steve.service.left();
|
||||
steve.now += OnlineService.PRESENCE_GRACE_MILLIS;
|
||||
steve.settle();
|
||||
alex.settle();
|
||||
assertThat(alex.service.player(STEVE)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentServersNeverMatch() {
|
||||
Client alex = signedUp("AlexAccount");
|
||||
Client steve = signedUp("SteveAccount");
|
||||
Map<UUID, String> tab = Map.of(ALEX, "Alex", STEVE, "Steve");
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.service.tabList(tab);
|
||||
steve.service.joined("mc.example.com", "Steve");
|
||||
steve.service.tabList(tab);
|
||||
alex.settle();
|
||||
steve.settle();
|
||||
assertThat(alex.service.player(STEVE)).isNull();
|
||||
assertThat(steve.service.player(ALEX)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void notSharingTheServerLeavesTheAddressOut() {
|
||||
Client alex = signedUp("AlexAccount");
|
||||
assertThat(alex.<Void>await(done -> alex.service.setShareServer(false, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.settle();
|
||||
assertThat(presence(0).has("server")).isFalse();
|
||||
assertThat(alex.service.sharesServer()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockingHidesBothWaysAndUnblockingBringsThemBack() {
|
||||
Client alex = signedUp("AlexAccount");
|
||||
Client steve = signedUp("SteveAccount");
|
||||
Map<UUID, String> tab = Map.of(ALEX, "Alex", STEVE, "Steve");
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.service.tabList(tab);
|
||||
steve.service.joined("play.example.com", "Steve");
|
||||
steve.service.tabList(tab);
|
||||
alex.settle();
|
||||
steve.settle();
|
||||
IncariPlayer steveSeen = alex.service.player(STEVE);
|
||||
assertThat(steveSeen).isNotNull();
|
||||
|
||||
assertThat(alex.<Void>await(done -> alex.service.blockPlayer("Steve", steveSeen, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(alex.service.player(STEVE)).isNull();
|
||||
List<OnlineService.Block> blocks =
|
||||
alex.<List<OnlineService.Block>>await(alex.service::blocks).value();
|
||||
// Labelled by the name Alex saw, never the account's username.
|
||||
assertThat(blocks).extracting(OnlineService.Block::label).containsExactly("Steve");
|
||||
|
||||
assertThat(alex.<Void>await(done -> alex.service.unblock(blocks.get(0), done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
alex.now += WorldPlayers.LOOKUP_INTERVAL_MILLIS;
|
||||
alex.settle();
|
||||
assertThat(alex.service.player(STEVE)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsGoThrough() {
|
||||
Client client = signedUp("Frost");
|
||||
assertThat(client.<Void>await(done -> client.service.reportUsername(
|
||||
"Someone", OnlineService.ReportReason.SPAM, "x".repeat(900), done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
JsonObject report = fake.received.get(fake.received.size() - 1);
|
||||
assertThat(report.get("reason").getAsString()).isEqualTo("spam");
|
||||
assertThat(report.get("note").getAsString()).hasSize(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedOutClientsCantUseAccountRequests() {
|
||||
Client client = started();
|
||||
assertThat(client.<Void>await(done -> client.service.blockUsername("x", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.SIGNED_OUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordsAreNeverWarnedAbout() {
|
||||
Client client = signedUp("Frost");
|
||||
client.<Void>await(done -> client.service.signIn("Frost", PASSWORD, done));
|
||||
assertThat(client.warnings).noneMatch(message -> message.contains(PASSWORD));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignUpCancelledBeforeItsFormMakesNoAccount() {
|
||||
Client client = started();
|
||||
List<Result<List<String>>> heard = new java.util.ArrayList<>();
|
||||
client.service.signUp("Frost", PASSWORD, heard::add);
|
||||
assertThat(client.service.cancelSignUp()).isTrue();
|
||||
client.settle();
|
||||
|
||||
assertThat(heard).isEmpty();
|
||||
assertThat(fake.accounts).isEmpty();
|
||||
assertThat(fake.received)
|
||||
.noneMatch(message -> message.get("t").getAsString().equals("signup"));
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignUpWhoseFormIsOutStillHandsOverTheCodes() {
|
||||
Client client = started();
|
||||
List<Result<List<String>>> heard = new java.util.ArrayList<>();
|
||||
client.service.signUp("Frost", PASSWORD, heard::add);
|
||||
// The challenge's answer, then the solved nonce: the form goes.
|
||||
client.service.tick();
|
||||
client.service.tick();
|
||||
assertThat(fake.received)
|
||||
.anyMatch(message -> message.get("t").getAsString().equals("signup"));
|
||||
|
||||
assertThat(client.service.cancelSignUp()).isFalse();
|
||||
client.settle();
|
||||
assertThat(heard).hasSize(1);
|
||||
assertThat(heard.get(0).value()).hasSize(10);
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_IN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignInWithNoAnswerStartsAFreshConnection() {
|
||||
signedUp("Frost").service.signOut(false, result -> {});
|
||||
Client client = started();
|
||||
int sockets = fake.sockets.size();
|
||||
fake.unanswered.add("signin");
|
||||
List<Result<Void>> heard = new java.util.ArrayList<>();
|
||||
client.service.signIn("Frost", PASSWORD, heard::add);
|
||||
client.now += OnlineService.REQUEST_TIMEOUT_MILLIS;
|
||||
client.settle();
|
||||
|
||||
// The service may have signed the old connection in: it goes, and the next starts signed out.
|
||||
assertThat(heard).extracting(Result::failure).containsExactly(Failure.OFFLINE);
|
||||
assertThat(fake.sockets.get(sockets - 1).open).isFalse();
|
||||
fake.unanswered.clear();
|
||||
client.now += 60_000;
|
||||
client.settle();
|
||||
assertThat(fake.sockets).hasSize(sockets + 1);
|
||||
assertThat(client.service.status()).isEqualTo(Status.SIGNED_OUT);
|
||||
assertThat(client.<Void>await(done -> client.service.signIn("Frost", PASSWORD, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAnswerThatCantBeReadFailsOnlyItsRequest() {
|
||||
Client alex = signedUp("AlexAccount");
|
||||
fake.unanswered.add("befriend");
|
||||
List<Result<Void>> heard = new java.util.ArrayList<>();
|
||||
alex.service.befriend("SomeoneElse", heard::add);
|
||||
alex.settle();
|
||||
int id = fake.received.get(fake.received.size() - 1).get("id").getAsInt();
|
||||
|
||||
JsonObject bad = new JsonObject();
|
||||
bad.addProperty("t", "ok");
|
||||
bad.addProperty("id", id);
|
||||
bad.addProperty("request", "not a request");
|
||||
JsonObject request = new JsonObject();
|
||||
request.addProperty("t", "request");
|
||||
request.addProperty("rid", "r9");
|
||||
request.addProperty("incoming", true);
|
||||
request.addProperty("label", "Friendly");
|
||||
// Both in one tick: the bad answer mustn't take the event after it down with it.
|
||||
fake.last().say(bad);
|
||||
fake.last().say(request);
|
||||
alex.settle();
|
||||
|
||||
assertThat(heard).extracting(Result::failure).containsExactly(Failure.UNAVAILABLE);
|
||||
assertThat(alex.service.social().requests())
|
||||
.extracting(Social.Request::rid)
|
||||
.containsExactly("r9");
|
||||
}
|
||||
|
||||
private JsonObject presence(int which) {
|
||||
return fake.received.stream()
|
||||
.filter(message -> message.get("t").getAsString().equals("presence"))
|
||||
.skip(which)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** What the client tells the service about where the player is, and how often (ADR 0058). */
|
||||
class PresenceTest {
|
||||
|
||||
private static final String PASSWORD = "correct horse battery";
|
||||
|
||||
private final FakeService fake = new FakeService();
|
||||
|
||||
private Client signedUp(String username) {
|
||||
Client client = new Client(fake);
|
||||
client.service.start();
|
||||
client.settle();
|
||||
assertThat(client.<List<String>>await(done -> client.service.signUp(username, PASSWORD, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
return client;
|
||||
}
|
||||
|
||||
private List<JsonObject> presences() {
|
||||
return fake.received.stream()
|
||||
.filter(message -> message.get("t").getAsString().equals("presence"))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServerSwitchBackToTheSamePlaceSendsNothingMore() {
|
||||
Client alex = signedUp("Alex");
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.settle();
|
||||
assertThat(presences()).hasSize(1);
|
||||
|
||||
// A proxy's server switch: out of the world for a moment, then back through the same address.
|
||||
alex.service.left();
|
||||
alex.settle();
|
||||
alex.now += 3_000;
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.settle();
|
||||
alex.now += OnlineService.PRESENCE_GRACE_MILLIS;
|
||||
alex.settle();
|
||||
|
||||
assertThat(presences()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavingClearsThePlaceOnceTheGraceIsOver() {
|
||||
Client alex = signedUp("Alex");
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.settle();
|
||||
alex.service.left();
|
||||
alex.settle();
|
||||
assertThat(presences()).hasSize(1);
|
||||
|
||||
alex.now += OnlineService.PRESENCE_GRACE_MILLIS;
|
||||
alex.settle();
|
||||
assertThat(presences()).hasSize(2);
|
||||
assertThat(presences().get(1).get("serverHash").isJsonNull()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherServerWithinTheGraceReplacesThePlaceAtOnce() {
|
||||
Client alex = signedUp("Alex");
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.settle();
|
||||
alex.service.left();
|
||||
alex.service.joined("mc.other.net", "AlexMC");
|
||||
alex.settle();
|
||||
|
||||
assertThat(presences()).hasSize(2);
|
||||
assertThat(presences().get(1).get("serverHash").getAsString()).isEqualTo(ServerHash.of("mc.other.net"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLimitedPresenceGoesAgainLater() {
|
||||
Client alex = signedUp("Alex");
|
||||
fake.limitNext = "presence";
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.settle();
|
||||
assertThat(presences()).hasSize(1);
|
||||
|
||||
// Not every tick: that would only use up the limit again.
|
||||
alex.now += OnlineService.PRESENCE_RETRY_MILLIS - 1;
|
||||
alex.settle();
|
||||
assertThat(presences()).hasSize(1);
|
||||
|
||||
alex.now += 1;
|
||||
alex.settle();
|
||||
assertThat(presences()).hasSize(2);
|
||||
assertThat(fake.last().serverHash).isEqualTo(ServerHash.of("play.example.com"));
|
||||
assertThat(alex.warnings).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReconnectSendsThePlaceAgain() {
|
||||
Client alex = signedUp("Alex");
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.settle();
|
||||
fake.last().drop();
|
||||
alex.settle();
|
||||
alex.now += 60_000;
|
||||
alex.settle();
|
||||
|
||||
assertThat(presences()).hasSize(2);
|
||||
assertThat(fake.last().serverHash).isEqualTo(ServerHash.of("play.example.com"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ReleasesTest {
|
||||
|
||||
@Test
|
||||
void aLaterPartIsNewer() {
|
||||
assertThat(Releases.newer("0.2.0", "0.1.0")).isTrue();
|
||||
assertThat(Releases.newer("0.10.0", "0.9.3")).isTrue();
|
||||
assertThat(Releases.newer("1.0", "0.99.99")).isTrue();
|
||||
assertThat(Releases.newer("0.1.1", "0.1")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameOrOlderIsNot() {
|
||||
assertThat(Releases.newer("0.1.0", "0.1.0")).isFalse();
|
||||
assertThat(Releases.newer("0.1", "0.1.0")).isFalse();
|
||||
assertThat(Releases.newer("0.1.0", "0.2.0")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anythingElseIsNeverNewer() {
|
||||
assertThat(Releases.valid("1.2.3-beta")).isNull();
|
||||
assertThat(Releases.valid("")).isNull();
|
||||
assertThat(Releases.valid("1.2.3.4.5")).isNull();
|
||||
assertThat(Releases.valid("v1.0")).isNull();
|
||||
assertThat(Releases.newer("2.0-rc1", "1.0")).isFalse();
|
||||
assertThat(Releases.newer("2.0", "dev")).isFalse();
|
||||
assertThat(Releases.newer(null, "1.0")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNoteIsPlainTextThatFits() {
|
||||
assertThat(Releases.note("Faster chunk loading")).isTrue();
|
||||
assertThat(Releases.note("x".repeat(Releases.MAX_NOTE))).isTrue();
|
||||
assertThat(Releases.note("\uD83D\uDE00".repeat(Releases.MAX_NOTE)))
|
||||
.as("counted in characters")
|
||||
.isTrue();
|
||||
assertThat(Releases.note("x".repeat(Releases.MAX_NOTE + 1))).isFalse();
|
||||
assertThat(Releases.note("")).isFalse();
|
||||
assertThat(Releases.note(" ")).isFalse();
|
||||
assertThat(Releases.note("two\nlines")).isFalse();
|
||||
assertThat(Releases.note("hidden\u200Bspace")).isFalse();
|
||||
assertThat(Releases.note("right\u202Eto left")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Back-off, the credential rules and the world's lookup queue, on their own. */
|
||||
class RulesTest {
|
||||
|
||||
@Test
|
||||
void backoffDoublesToFiveMinutesAndStartsOverAfterAMinuteUp() {
|
||||
Backoff backoff = new Backoff(() -> 0.999_999);
|
||||
List<Long> waits = new ArrayList<>();
|
||||
for (int i = 0; i < 12; i++) {
|
||||
waits.add(backoff.failed(0));
|
||||
}
|
||||
assertThat(waits.get(0)).isEqualTo(999);
|
||||
assertThat(waits.get(1)).isEqualTo(1_999);
|
||||
assertThat(waits.get(8)).isEqualTo(255_999);
|
||||
assertThat(waits.get(9)).isEqualTo(Backoff.MAX_MILLIS - 1);
|
||||
assertThat(waits.get(11)).isEqualTo(Backoff.MAX_MILLIS - 1);
|
||||
backoff.connected(0);
|
||||
assertThat(backoff.failed(Backoff.STEADY_MILLIS - 1)).isEqualTo(Backoff.MAX_MILLIS - 1);
|
||||
backoff.connected(0);
|
||||
assertThat(backoff.failed(Backoff.STEADY_MILLIS)).isEqualTo(999);
|
||||
}
|
||||
|
||||
@Test
|
||||
void backoffWaitsAtLeastHalf() {
|
||||
assertThat(new Backoff(() -> 0).failed(0)).isEqualTo(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
void usernames() {
|
||||
assertThat(Credentials.usernameProblem("Frost_1")).isNull();
|
||||
assertThat(Credentials.usernameProblem("ab")).isNotNull();
|
||||
assertThat(Credentials.usernameProblem("a".repeat(17))).isNotNull();
|
||||
assertThat(Credentials.usernameProblem("frost-1")).isNotNull();
|
||||
assertThat(Credentials.usernameProblem("frøst")).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwords() {
|
||||
assertThat(Credentials.passwordProblem("correct horse battery", "Frost"))
|
||||
.isNull();
|
||||
assertThat(Credentials.passwordProblem("short", "Frost")).contains("At least");
|
||||
assertThat(Credentials.passwordProblem("Minecraft123", "Frost")).contains("common");
|
||||
assertThat(Credentials.passwordProblem("aaaaaaaaaaaa", "Frost")).contains("common");
|
||||
assertThat(Credentials.passwordProblem("ababababab", "Frost")).contains("common");
|
||||
assertThat(Credentials.passwordProblem("abcdefghijklm", "Frost")).contains("common");
|
||||
assertThat(Credentials.passwordProblem("9876543210", "Frost")).contains("common");
|
||||
assertThat(Credentials.passwordProblem("my frost password", "Frost")).contains("username");
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookupsAreBatchedPacedAndAskedOnce() {
|
||||
WorldPlayers world = new WorldPlayers();
|
||||
UUID me = new UUID(0, 0);
|
||||
UUID a = new UUID(0, 1);
|
||||
UUID b = new UUID(0, 2);
|
||||
world.join("play.example.com", "Me");
|
||||
world.tabList(Map.of(me, "Me", a, "A"));
|
||||
assertThat(world.takeLookup(0)).containsExactly("A");
|
||||
world.tabList(Map.of(me, "Me", a, "A", b, "B"));
|
||||
assertThat(world.takeLookup(1)).isEmpty();
|
||||
assertThat(world.takeLookup(WorldPlayers.LOOKUP_INTERVAL_MILLIS)).containsExactly("B");
|
||||
// Nobody new: nothing to ask.
|
||||
assertThat(world.takeLookup(10 * WorldPlayers.LOOKUP_INTERVAL_MILLIS)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void lateAnswersForPlayersWhoLeftAreDropped() {
|
||||
WorldPlayers world = new WorldPlayers();
|
||||
UUID a = new UUID(0, 1);
|
||||
world.join("play.example.com", "Me");
|
||||
world.tabList(Map.of(a, "A"));
|
||||
world.tabList(Map.of());
|
||||
world.seen("A", new incari.framework.online.IncariPlayer("p", false, List.of()));
|
||||
assertThat(world.player(a)).isNull();
|
||||
assertThat(world.players()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLargeTabListIsAskedInParts() {
|
||||
WorldPlayers world = new WorldPlayers();
|
||||
world.join("play.example.com", "Me");
|
||||
java.util.HashMap<UUID, String> tab = new java.util.HashMap<>();
|
||||
for (int i = 0; i < 300; i++) {
|
||||
tab.put(new UUID(1, i), "P" + i);
|
||||
}
|
||||
world.tabList(tab);
|
||||
assertThat(world.takeLookup(0)).hasSize(WorldPlayers.MAX_LOOKUP);
|
||||
assertThat(world.takeLookup(WorldPlayers.LOOKUP_INTERVAL_MILLIS)).hasSize(300 - WorldPlayers.MAX_LOOKUP);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.framework.online.IncariPlayer;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Friends, requests and messages (ADR 0059) against the fake service. */
|
||||
class SocialTest {
|
||||
|
||||
private static final String PASSWORD = "correct horse battery";
|
||||
private static final UUID ALEX = new UUID(1, 1);
|
||||
private static final UUID STEVE = new UUID(2, 2);
|
||||
|
||||
private final FakeService fake = new FakeService();
|
||||
|
||||
private Client signedUp(String username) {
|
||||
Client client = new Client(fake);
|
||||
client.service.start();
|
||||
client.settle();
|
||||
assertThat(client.<List<String>>await(done -> client.service.signUp(username, PASSWORD, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
return client;
|
||||
}
|
||||
|
||||
private Social.Friend friends(Client a, String bName, Client b) {
|
||||
assertThat(a.<Void>await(done -> a.service.befriend(bName, done)).ok()).isTrue();
|
||||
b.settle();
|
||||
Social.Request incoming = b.service.social().requests().get(0);
|
||||
assertThat(b.<Void>await(done -> b.service.accept(incoming, done)).ok()).isTrue();
|
||||
a.settle();
|
||||
return a.service.social().friends().get(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFriendListLoadsOnSignIn() {
|
||||
Client client = signedUp("Frost");
|
||||
assertThat(client.service.social().available()).isTrue();
|
||||
assertThat(client.service.social().loaded()).isTrue();
|
||||
assertThat(client.service.social().friends()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceWithoutFriendsSaysSo() {
|
||||
fake.friendsSpoken = false;
|
||||
Client client = signedUp("Frost");
|
||||
assertThat(client.service.social().available()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestByUsernameIsAcceptedAndBothBecomeFriends() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
assertThat(alex.<Void>await(done -> alex.service.befriend("steve", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(alex.service.social().requests())
|
||||
.singleElement()
|
||||
.satisfies(request -> assertThat(request.incoming()).isFalse());
|
||||
steve.settle();
|
||||
Social.Request incoming = steve.service.social().requests().get(0);
|
||||
assertThat(incoming.incoming()).isTrue();
|
||||
assertThat(incoming.label()).isEqualTo("Alex");
|
||||
assertThat(steve.service.social().pendingRequests()).isEqualTo(1);
|
||||
assertThat(steve.service.social().takeNotices()).singleElement().satisfies(notice -> {
|
||||
assertThat(notice.request()).isTrue();
|
||||
assertThat(notice.who()).isEqualTo("Alex");
|
||||
});
|
||||
|
||||
assertThat(steve.<Void>await(done -> steve.service.accept(incoming, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
alex.settle();
|
||||
assertThat(steve.service.social().friends())
|
||||
.extracting(Social.Friend::username)
|
||||
.containsExactly("Alex");
|
||||
assertThat(alex.service.social().friends())
|
||||
.extracting(Social.Friend::username)
|
||||
.containsExactly("Steve");
|
||||
assertThat(alex.service.social().requests()).isEmpty();
|
||||
assertThat(steve.service.social().requests()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void askingSomeoneWhoAskedYouMakesYouFriends() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
alex.<Void>await(done -> alex.service.befriend("Steve", done));
|
||||
steve.settle();
|
||||
assertThat(steve.<Void>await(done -> steve.service.befriend("Alex", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
alex.settle();
|
||||
assertThat(steve.service.social().friends()).hasSize(1);
|
||||
assertThat(alex.service.social().friends()).hasSize(1);
|
||||
assertThat(alex.service.social().requests()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestsTurnedOffArriveNowhere() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
assertThat(steve.<Void>await(done -> steve.service.setFriendRequests(false, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
assertThat(steve.service.social().friendRequests()).isFalse();
|
||||
// Alex isn't told: the request looks sent.
|
||||
assertThat(alex.<Void>await(done -> alex.service.befriend("Steve", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
steve.settle();
|
||||
assertThat(steve.service.social().requests()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void declineWithdrawsAndUnfriendRemoves() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
alex.<Void>await(done -> alex.service.befriend("Steve", done));
|
||||
Social.Request sent = alex.service.social().requests().get(0);
|
||||
assertThat(alex.<Void>await(done -> alex.service.decline(sent, done)).ok())
|
||||
.isTrue();
|
||||
steve.settle();
|
||||
assertThat(steve.service.social().requests()).isEmpty();
|
||||
|
||||
Social.Friend friend = friends(alex, "Steve", steve);
|
||||
assertThat(alex.<Void>await(done -> alex.service.unfriend(friend, done)).ok())
|
||||
.isTrue();
|
||||
steve.settle();
|
||||
assertThat(alex.service.social().friends()).isEmpty();
|
||||
assertThat(steve.service.social().friends()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void friendsMessageEachOther() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Social.Friend steveFriend = friends(alex, "Steve", steve);
|
||||
Social.Peer toSteve = new Social.Peer(true, steveFriend.fid(), steveFriend.username());
|
||||
|
||||
assertThat(alex.<Void>await(done -> alex.service.sendMessage(toSteve, " hi there ", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
List<Social.Message> sent = alex.service.social().conversation(toSteve).messages();
|
||||
assertThat(sent).singleElement().satisfies(message -> {
|
||||
assertThat(message.text()).isEqualTo("hi there");
|
||||
assertThat(message.mine()).isTrue();
|
||||
assertThat(message.delivery()).isEqualTo(Social.Delivery.SENT);
|
||||
});
|
||||
|
||||
steve.settle();
|
||||
Social.Friend alexFriend = steve.service.social().friends().get(0);
|
||||
Social.Peer toAlex = new Social.Peer(true, alexFriend.fid(), alexFriend.username());
|
||||
assertThat(steve.service.social().unread()).isEqualTo(1);
|
||||
steve.service.social().takeNotices();
|
||||
steve.service.viewing(toAlex);
|
||||
assertThat(steve.service.social().unread()).isZero();
|
||||
|
||||
// While Steve looks at the conversation, a new message arrives read, with no toast.
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "again", done));
|
||||
steve.settle();
|
||||
assertThat(steve.service.social().unread()).isZero();
|
||||
assertThat(steve.service.social().takeNotices()).isEmpty();
|
||||
assertThat(steve.service.social().conversation(toAlex).messages())
|
||||
.extracting(Social.Message::text)
|
||||
.containsExactly("hi there", "again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void messagesSentWhileDisconnectedArriveOnReconnect() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Social.Friend steveFriend = friends(alex, "Steve", steve);
|
||||
Social.Peer toSteve = new Social.Peer(true, steveFriend.fid(), steveFriend.username());
|
||||
Social.Friend alexFriend = steve.service.social().friends().get(0);
|
||||
Social.Peer toAlex = new Social.Peer(true, alexFriend.fid(), alexFriend.username());
|
||||
steve.service.viewing(toAlex);
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "one", done));
|
||||
steve.settle();
|
||||
|
||||
// Steve's connection drops; Alex goes on talking.
|
||||
fake.sockets.stream()
|
||||
.filter(socket -> socket.open && socket.account != null && socket.account.username.equals("Steve"))
|
||||
.findFirst()
|
||||
.orElseThrow()
|
||||
.drop();
|
||||
steve.settle();
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "two", done));
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "three", done));
|
||||
steve.now += 60_000;
|
||||
steve.settle();
|
||||
|
||||
assertThat(steve.service.status()).isEqualTo(incari.framework.online.Online.Status.SIGNED_IN);
|
||||
assertThat(steve.service.social().conversation(toAlex).messages())
|
||||
.extracting(Social.Message::text)
|
||||
.containsExactly("one", "two", "three");
|
||||
// Read up to the newest, now that it's held.
|
||||
String newest =
|
||||
steve.service.social().conversation(toAlex).messages().get(2).mid();
|
||||
assertThat(fake.received.stream()
|
||||
.filter(message -> message.get("t").getAsString().equals("read"))
|
||||
.reduce((first, second) -> second)
|
||||
.orElseThrow()
|
||||
.get("mid")
|
||||
.getAsString())
|
||||
.isEqualTo(newest);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConversationNotShownLoadsWhatItMissedWhenNextShown() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Social.Friend steveFriend = friends(alex, "Steve", steve);
|
||||
Social.Peer toSteve = new Social.Peer(true, steveFriend.fid(), steveFriend.username());
|
||||
Social.Friend alexFriend = steve.service.social().friends().get(0);
|
||||
Social.Peer toAlex = new Social.Peer(true, alexFriend.fid(), alexFriend.username());
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "one", done));
|
||||
steve.settle();
|
||||
steve.service.viewing(toAlex);
|
||||
steve.service.viewing(null);
|
||||
|
||||
fake.sockets.stream()
|
||||
.filter(socket -> socket.open && socket.account != null && socket.account.username.equals("Steve"))
|
||||
.findFirst()
|
||||
.orElseThrow()
|
||||
.drop();
|
||||
steve.settle();
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "two", done));
|
||||
steve.now += 60_000;
|
||||
steve.settle();
|
||||
// The service's count, though the client held the conversation already read.
|
||||
assertThat(steve.service.social().unread()).isEqualTo(1);
|
||||
|
||||
steve.service.viewing(toAlex);
|
||||
steve.service.loadOlder(toAlex);
|
||||
steve.settle();
|
||||
assertThat(steve.service.social().conversation(toAlex).messages())
|
||||
.extracting(Social.Message::text)
|
||||
.containsExactly("one", "two");
|
||||
assertThat(steve.service.social().unread()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyLoadsOlderPages() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Social.Friend steveFriend = friends(alex, "Steve", steve);
|
||||
Social.Peer toSteve = new Social.Peer(true, steveFriend.fid(), "Steve");
|
||||
for (int i = 0; i < FakeService.HISTORY_PAGE + 10; i++) {
|
||||
int n = i;
|
||||
alex.<Void>await(done -> alex.service.sendMessage(toSteve, "message " + n, done));
|
||||
}
|
||||
// A fresh client: the history comes from the service a page at a time.
|
||||
Client again = new Client(fake, alex.storage);
|
||||
again.service.start();
|
||||
again.settle();
|
||||
again.service.loadOlder(toSteve);
|
||||
again.settle();
|
||||
Social.Conversation conversation = again.service.social().conversation(toSteve);
|
||||
assertThat(conversation.messages()).hasSize(FakeService.HISTORY_PAGE);
|
||||
assertThat(conversation.hasMore()).isTrue();
|
||||
again.service.loadOlder(toSteve);
|
||||
again.settle();
|
||||
assertThat(conversation.messages()).hasSize(FakeService.HISTORY_PAGE + 10);
|
||||
assertThat(conversation.messages().get(0).text()).isEqualTo("message 0");
|
||||
assertThat(conversation.hasMore()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void messagingTurnedOffTurnsMessagesAway() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Social.Friend steveFriend = friends(alex, "Steve", steve);
|
||||
steve.<Void>await(done -> steve.service.setMessagesFrom(Social.MessagesFrom.NOBODY, done));
|
||||
Social.Peer toSteve = new Social.Peer(true, steveFriend.fid(), "Steve");
|
||||
assertThat(alex.<Void>await(done -> alex.service.sendMessage(toSteve, "hello?", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.CLOSED);
|
||||
assertThat(alex.service.social().conversation(toSteve).messages())
|
||||
.singleElement()
|
||||
.satisfies(message -> assertThat(message.delivery()).isEqualTo(Social.Delivery.FAILED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void playersOnTheServerMessageOnlyWhenTheyAllowEveryone() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Map<UUID, String> tab = Map.of(ALEX, "AlexMC", STEVE, "SteveMC");
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.service.tabList(tab);
|
||||
steve.service.joined("play.example.com", "SteveMC");
|
||||
steve.service.tabList(tab);
|
||||
alex.settle();
|
||||
steve.settle();
|
||||
IncariPlayer steveHere = alex.service.player(STEVE);
|
||||
assertThat(steveHere).isNotNull();
|
||||
Social.Peer toSteve = new Social.Peer(false, steveHere.pid(), "SteveMC");
|
||||
|
||||
// Friends only, by default.
|
||||
assertThat(alex.<Void>await(done -> alex.service.sendMessage(toSteve, "hey", done))
|
||||
.failure())
|
||||
.isEqualTo(Failure.CLOSED);
|
||||
steve.<Void>await(done -> steve.service.setMessagesFrom(Social.MessagesFrom.EVERYONE, done));
|
||||
assertThat(alex.<Void>await(done -> alex.service.sendMessage(toSteve, "hey", done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
steve.settle();
|
||||
assertThat(steve.service.social().playersMessaged()).containsValue("AlexMC");
|
||||
assertThat(steve.service.social().unread()).isEqualTo(1);
|
||||
|
||||
// Leaving the server ends what was said there.
|
||||
steve.service.left();
|
||||
assertThat(steve.service.social().playersMessaged()).isEmpty();
|
||||
assertThat(steve.service.social().unread()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestToAPlayerOnTheServerIsLabelledByTheirName() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Map<UUID, String> tab = Map.of(ALEX, "AlexMC", STEVE, "SteveMC");
|
||||
alex.service.joined("play.example.com", "AlexMC");
|
||||
alex.service.tabList(tab);
|
||||
steve.service.joined("play.example.com", "SteveMC");
|
||||
steve.service.tabList(tab);
|
||||
alex.settle();
|
||||
IncariPlayer steveHere = alex.service.player(STEVE);
|
||||
assertThat(steveHere).isNotNull();
|
||||
assertThat(alex.<Void>await(done -> alex.service.befriend("SteveMC", steveHere, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
// The username stays Steve's to share: Alex sees the name they sent it to.
|
||||
assertThat(alex.service.social().requests().get(0).label()).isEqualTo("SteveMC");
|
||||
// Known by Steve's pid, whatever name another player here goes by.
|
||||
assertThat(alex.service.social().sentTo(new Social.Peer(false, steveHere.pid(), "SteveMC")))
|
||||
.isNotNull();
|
||||
assertThat(alex.service.social().sentTo(new Social.Peer(false, "someone-else", "SteveMC")))
|
||||
.isNull();
|
||||
steve.settle();
|
||||
assertThat(steve.service.social().requests().get(0).label()).isEqualTo("Alex");
|
||||
// A request received is never one Steve sent, even under a matching name.
|
||||
IncariPlayer alexHere = steve.service.player(ALEX);
|
||||
assertThat(alexHere).isNotNull();
|
||||
assertThat(steve.service.social().sentTo(new Social.Peer(false, alexHere.pid(), "Alex")))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockingAFriendEndsItOnBothSides() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
Social.Friend steveFriend = friends(alex, "Steve", steve);
|
||||
assertThat(alex.<Void>await(done -> alex.service.blockFriend(steveFriend, done))
|
||||
.ok())
|
||||
.isTrue();
|
||||
steve.settle();
|
||||
assertThat(alex.service.social().friends()).isEmpty();
|
||||
assertThat(steve.service.social().friends()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void askingTwiceIsOneRequest() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
alex.<Void>await(done -> alex.service.befriend("Steve", done));
|
||||
alex.<Void>await(done -> alex.service.befriend("Steve", done));
|
||||
steve.settle();
|
||||
assertThat(alex.service.social().requests()).hasSize(1);
|
||||
assertThat(steve.service.social().requests()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingOutForgetsEverything() {
|
||||
Client alex = signedUp("Alex");
|
||||
Client steve = signedUp("Steve");
|
||||
friends(alex, "Steve", steve);
|
||||
alex.<Void>await(done -> alex.service.signOut(false, done));
|
||||
assertThat(alex.service.social().friends()).isEmpty();
|
||||
assertThat(alex.service.social().loaded()).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Objects;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The vectors shared with the backend ({@code vectors.json}, made with Python's hashlib): server
|
||||
* hashes, proof of work and recovery codes must come out the same on both sides.
|
||||
*/
|
||||
class VectorsTest {
|
||||
|
||||
private static JsonObject vectors() throws IOException {
|
||||
try (InputStream in = Objects.requireNonNull(VectorsTest.class.getResourceAsStream("vectors.json"))) {
|
||||
return JsonParser.parseString(new String(in.readAllBytes(), StandardCharsets.UTF_8))
|
||||
.getAsJsonObject();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverHashes() throws IOException {
|
||||
JsonObject vectors = vectors();
|
||||
assertThat(vectors.get("serverHashPrefix").getAsString()).isEqualTo(ServerHash.PREFIX);
|
||||
for (JsonElement each : vectors.getAsJsonArray("serverHashes")) {
|
||||
JsonObject vector = each.getAsJsonObject();
|
||||
String address = vector.get("address").getAsString();
|
||||
assertThat(ServerHash.normalize(address))
|
||||
.as(address)
|
||||
.isEqualTo(vector.get("normalized").getAsString());
|
||||
assertThat(ServerHash.of(address))
|
||||
.as(address)
|
||||
.isEqualTo(vector.get("hash").getAsString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void proofOfWork() throws IOException {
|
||||
for (JsonElement each : vectors().getAsJsonArray("proofOfWork")) {
|
||||
JsonObject vector = each.getAsJsonObject();
|
||||
ProofOfWork work = new ProofOfWork(
|
||||
ProofOfWork.base64Url(vector.get("challenge").getAsString()),
|
||||
vector.get("bits").getAsInt());
|
||||
while (!work.step(1000)) {
|
||||
// On to the answer.
|
||||
}
|
||||
// The first nonce that passes, as the vectors' maker searched from 0 too.
|
||||
assertThat(work.nonce()).isEqualTo(vector.get("nonce").getAsLong());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveryCodes() throws IOException {
|
||||
JsonObject codes = vectors().getAsJsonObject("recoveryCodes");
|
||||
for (JsonElement each : codes.getAsJsonArray("valid")) {
|
||||
String typed = each.getAsJsonArray().get(0).getAsString();
|
||||
assertThat(RecoveryCodes.normalize(typed))
|
||||
.as(typed)
|
||||
.isEqualTo(each.getAsJsonArray().get(1).getAsString());
|
||||
}
|
||||
for (JsonElement each : codes.getAsJsonArray("invalid")) {
|
||||
assertThat(RecoveryCodes.normalize(each.getAsString()))
|
||||
.as(each.getAsString())
|
||||
.isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sha256AgreesWithTheJdk() throws NoSuchAlgorithmException {
|
||||
MessageDigest jdk = MessageDigest.getInstance("SHA-256");
|
||||
for (int length = 0; length < 200; length++) {
|
||||
byte[] message = new byte[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
message[i] = (byte) (i * 31 + length);
|
||||
}
|
||||
assertThat(Sha256.hash(message)).as("length %d", length).isEqualTo(jdk.digest(message));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void base64UrlReadsWithAndWithoutPadding() {
|
||||
assertThat(ProofOfWork.base64Url("AAECAwQFBgcICQoLDA0ODw"))
|
||||
.containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
|
||||
assertThat(ProofOfWork.base64Url("AAECAwQFBgcICQoLDA0ODw==")).hasSize(16);
|
||||
assertThat(ProofOfWork.base64Url("-_8")).containsExactly(0xFB, 0xFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import incari.framework.online.IncariPlayer;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class WardrobeTest {
|
||||
|
||||
private static final String PASSWORD = "correct horse battery";
|
||||
private static final UUID ALEX = new UUID(1, 1);
|
||||
private static final UUID STEVE = new UUID(2, 2);
|
||||
private static final Cosmetic FROST = cosmetic("cape.frost");
|
||||
private static final Cosmetic EMBER = cosmetic("cape.ember");
|
||||
private static final Cosmetic CROWN = cosmetic("hat.crown");
|
||||
private static final Cosmetic WAVE = cosmetic("emote.wave");
|
||||
|
||||
private final FakeService fake = new FakeService();
|
||||
|
||||
private static Cosmetic cosmetic(String id) {
|
||||
return Objects.requireNonNull(Catalog.byId(id));
|
||||
}
|
||||
|
||||
private Client started() {
|
||||
Client client = new Client(fake);
|
||||
client.service.start();
|
||||
return client.settle();
|
||||
}
|
||||
|
||||
private Client signedUp(Client client, String username) {
|
||||
Result<List<String>> result = client.await(done -> client.service.signUp(username, PASSWORD, done));
|
||||
assertThat(result.ok()).isTrue();
|
||||
return client.settle();
|
||||
}
|
||||
|
||||
/** Lets the equip interval pass and settles. */
|
||||
private static void later(Client client) {
|
||||
client.now += OnlineService.EQUIP_INTERVAL_MILLIS;
|
||||
client.settle();
|
||||
}
|
||||
|
||||
private List<JsonObject> sent(String type) {
|
||||
return fake.received.stream()
|
||||
.filter(m -> m.get("t").getAsString().equals(type))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCatalogIsConsistent() {
|
||||
for (Cosmetic each : Catalog.all()) {
|
||||
assertThat(Catalog.byId(each.id())).isSameAs(each);
|
||||
assertThat(each.id()).matches("[a-z]+\\.[a-z0-9_]+");
|
||||
}
|
||||
for (Cosmetic.Slot slot : Cosmetic.Slot.values()) {
|
||||
assertThat(Catalog.inSlot(slot)).isNotEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLoadoutKeepsOnePerSlotAndLeavesOutWhatItCantDraw() {
|
||||
Loadout loadout = Loadout.of(List.of("cape.frost", "cape.ember", "hat.crown", "emote.wave", "hat.unknown_hat"));
|
||||
assertThat(loadout.ids()).containsExactly("cape.frost", "hat.crown");
|
||||
assertThat(loadout.with(EMBER).ids()).containsExactly("cape.ember", "hat.crown");
|
||||
assertThat(loadout.without(Cosmetic.Slot.CAPE).ids()).containsExactly("hat.crown");
|
||||
assertThat(Loadout.of(List.of())).isSameAs(Loadout.EMPTY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whatsWornWithoutAnAccountIsKeptOnTheDevice() {
|
||||
Client client = started();
|
||||
client.service.wardrobe().wear(FROST);
|
||||
client.service.wardrobe().setShowOthers(false);
|
||||
client.service.wardrobe().saveOutfit("Snowy");
|
||||
assertThat(client.service.wardrobe().shared()).isFalse();
|
||||
assertThat(sent("equip")).isEmpty();
|
||||
|
||||
Client again = new Client(fake, client.storage);
|
||||
Wardrobe wardrobe = again.service.wardrobe();
|
||||
assertThat(wardrobe.worn().ids()).containsExactly("cape.frost");
|
||||
assertThat(wardrobe.showOthers()).isFalse();
|
||||
assertThat(wardrobe.outfits()).extracting(Wardrobe.Outfit::name).containsExactly("Snowy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewAccountTakesWhatTheDeviceWore() {
|
||||
Client client = started();
|
||||
client.service.wardrobe().wear(FROST);
|
||||
signedUp(client, "Frost");
|
||||
later(client);
|
||||
assertThat(client.service.wardrobe().shared()).isTrue();
|
||||
assertThat(fake.accounts.get("frost").equipped).containsExactly("cape.frost");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccountThatWearsSomethingReplacesTheDevices() {
|
||||
Client first = signedUp(started(), "Frost");
|
||||
first.service.wardrobe().wear(EMBER);
|
||||
later(first);
|
||||
|
||||
Client other = started();
|
||||
other.service.wardrobe().wear(FROST);
|
||||
Result<Void> signedIn = other.await(done -> other.service.signIn("Frost", PASSWORD, done));
|
||||
assertThat(signedIn.ok()).isTrue();
|
||||
other.settle();
|
||||
assertThat(other.service.wardrobe().worn().ids()).containsExactly("cape.ember");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clicksAreGatheredIntoOneEquip() {
|
||||
Client client = signedUp(started(), "Frost");
|
||||
later(client);
|
||||
int before = sent("equip").size();
|
||||
Wardrobe wardrobe = client.service.wardrobe();
|
||||
wardrobe.wear(FROST);
|
||||
client.service.tick();
|
||||
wardrobe.wear(EMBER);
|
||||
wardrobe.wear(CROWN);
|
||||
client.settle();
|
||||
later(client);
|
||||
List<JsonObject> equips = sent("equip");
|
||||
assertThat(equips).hasSize(before + 2);
|
||||
assertThat(equips.get(equips.size() - 1).getAsJsonArray("cosmetics").toString())
|
||||
.isEqualTo("[\"cape.ember\",\"hat.crown\"]");
|
||||
later(client);
|
||||
assertThat(sent("equip")).hasSize(before + 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void playersOnTheServerSeeAChangeAndTheAccountsOtherSessionsToo() {
|
||||
Client alex = signedUp(started(), "AlexAccount");
|
||||
Client steve = signedUp(started(), "SteveAccount");
|
||||
Client alexElsewhere = started();
|
||||
alexElsewhere.<Void>await(done -> alexElsewhere.service.signIn("AlexAccount", PASSWORD, done));
|
||||
Map<UUID, String> tab = Map.of(ALEX, "Alex", STEVE, "Steve");
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.service.tabList(tab);
|
||||
alex.settle();
|
||||
steve.service.joined("play.example.com", "Steve");
|
||||
steve.service.tabList(tab);
|
||||
steve.settle();
|
||||
IncariPlayer seen = steve.service.player(ALEX);
|
||||
assertThat(seen).isNotNull();
|
||||
assertThat(seen.cosmetics()).isEmpty();
|
||||
|
||||
alex.service.wardrobe().wear(CROWN);
|
||||
later(alex);
|
||||
steve.settle();
|
||||
alexElsewhere.settle();
|
||||
assertThat(Objects.requireNonNull(steve.service.player(ALEX)).cosmetics())
|
||||
.containsExactly("hat.crown");
|
||||
assertThat(alexElsewhere.service.wardrobe().worn().ids()).containsExactly("hat.crown");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emotesReachIncariPlayersOnTheSameServer() {
|
||||
Client alex = signedUp(started(), "AlexAccount");
|
||||
Client steve = signedUp(started(), "SteveAccount");
|
||||
Map<UUID, String> tab = Map.of(ALEX, "Alex", STEVE, "Steve");
|
||||
alex.service.joined("play.example.com", "Alex");
|
||||
alex.service.tabList(tab);
|
||||
alex.settle();
|
||||
steve.service.joined("play.example.com", "Steve");
|
||||
steve.service.tabList(tab);
|
||||
steve.settle();
|
||||
alex.settle();
|
||||
|
||||
assertThat(alex.service.playEmote(WAVE)).isTrue();
|
||||
// One every two seconds.
|
||||
assertThat(alex.service.playEmote(WAVE)).isFalse();
|
||||
alex.settle();
|
||||
steve.settle();
|
||||
assertThat(steve.service.takeEmotes()).containsExactly(new OnlineService.PlayedEmote(ALEX, WAVE));
|
||||
assertThat(steve.service.takeEmotes()).isEmpty();
|
||||
assertThat(alex.service.takeEmotes()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cosmeticsTheAccountOwnsAreOwnedOnlyWhileSignedIn() {
|
||||
// As one the backend gave the account, not every account.
|
||||
Cosmetic granted = new Cosmetic("cape.frost", Cosmetic.Slot.CAPE, "Frost", false);
|
||||
Client client = started();
|
||||
Wardrobe wardrobe = client.service.wardrobe();
|
||||
assertThat(wardrobe.owns(granted)).isFalse();
|
||||
signedUp(client, "Frost");
|
||||
assertThat(wardrobe.owns(granted)).isTrue();
|
||||
client.<Void>await(done -> client.service.signOut(false, done));
|
||||
assertThat(wardrobe.owns(granted)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantArrivesAsAWardrobeEvent() {
|
||||
Client client = signedUp(started(), "Frost");
|
||||
long before = client.service.revision();
|
||||
fake.grant("Frost", "hat.crown");
|
||||
client.settle();
|
||||
assertThat(client.service.revision()).isNotEqualTo(before);
|
||||
assertThat(client.warnings).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceWithoutCosmeticsLeavesThemOnTheDevice() {
|
||||
fake.cosmeticsSpoken = false;
|
||||
Client client = started();
|
||||
client.service.wardrobe().wear(FROST);
|
||||
signedUp(client, "Frost");
|
||||
later(client);
|
||||
assertThat(client.service.wardrobe().shared()).isFalse();
|
||||
assertThat(client.service.wardrobe().worn().ids()).containsExactly("cape.frost");
|
||||
assertThat(sent("equip")).isEmpty();
|
||||
assertThat(client.warnings).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void changesMadeOfflineGoOnceTheConnectionIsBack() {
|
||||
Client client = signedUp(started(), "Frost");
|
||||
later(client);
|
||||
fake.last().drop();
|
||||
client.settle();
|
||||
assertThat(client.service.wardrobe().shared()).isFalse();
|
||||
client.service.wardrobe().wear(EMBER);
|
||||
client.now += 1_000;
|
||||
client.settle();
|
||||
later(client);
|
||||
assertThat(client.service.wardrobe().shared()).isTrue();
|
||||
assertThat(fake.accounts.get("frost").equipped).containsExactly("cape.ember");
|
||||
}
|
||||
|
||||
@Test
|
||||
void outfitsAreReplacedByNameAndCapped() {
|
||||
Wardrobe wardrobe = started().service.wardrobe();
|
||||
wardrobe.wear(FROST);
|
||||
assertThat(wardrobe.saveOutfit("A")).isTrue();
|
||||
wardrobe.wear(EMBER);
|
||||
assertThat(wardrobe.saveOutfit("a")).isTrue();
|
||||
assertThat(wardrobe.outfits()).hasSize(1);
|
||||
assertThat(wardrobe.outfits().get(0).loadout().ids()).containsExactly("cape.ember");
|
||||
for (int i = 1; i < Wardrobe.MAX_OUTFITS; i++) {
|
||||
assertThat(wardrobe.saveOutfit("O" + i)).isTrue();
|
||||
}
|
||||
assertThat(wardrobe.saveOutfit("One too many")).isFalse();
|
||||
wardrobe.wear(Loadout.EMPTY);
|
||||
wardrobe.wear(wardrobe.outfits().get(0).loadout());
|
||||
assertThat(wardrobe.worn().ids()).containsExactly("cape.ember");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package incari.online;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import incari.framework.online.IncariPlayer;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The tab list's players and which are Incari players, when names repeat (ADR 0058). */
|
||||
class WorldPlayersTest {
|
||||
|
||||
/** A player in online mode: a version 4 UUID. */
|
||||
private static final UUID STEVE = UUID.fromString("5a1d4e2c-7b3f-4c1a-9d2e-0f1b2c3d4e5f");
|
||||
/** An NPC by the same name, as Citizens makes them: a version 2 UUID. */
|
||||
private static final UUID NPC = UUID.fromString("0f1e2d3c-4b5a-2968-8776-655443322110");
|
||||
|
||||
private static final IncariPlayer INCARI = new IncariPlayer("p1", false, List.of(), true);
|
||||
|
||||
private final WorldPlayers world = new WorldPlayers();
|
||||
|
||||
private WorldPlayers joinedWith(Map<UUID, String> tab) {
|
||||
world.join("play.example.com", "Alex");
|
||||
world.tabList(tab);
|
||||
assertThat(world.takeLookup(0)).containsExactly("Steve");
|
||||
world.seen("Steve", INCARI);
|
||||
return world;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anNpcByThePlayersNameGetsNoBadge() {
|
||||
joinedWith(Map.of(NPC, "Steve", STEVE, "Steve"));
|
||||
assertThat(world.player(STEVE)).isEqualTo(INCARI);
|
||||
assertThat(world.player(NPC)).isNull();
|
||||
assertThat(world.uuid("p1")).isEqualTo(STEVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anNpcLeavingKeepsThePlayersBadge() {
|
||||
joinedWith(Map.of(NPC, "Steve", STEVE, "Steve"));
|
||||
world.tabList(Map.of(STEVE, "Steve"));
|
||||
assertThat(world.player(STEVE)).isEqualTo(INCARI);
|
||||
assertThat(world.takeLookup(Long.MAX_VALUE)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anNpcArrivingKeepsThePlayersBadge() {
|
||||
joinedWith(Map.of(STEVE, "Steve"));
|
||||
world.tabList(Map.of(STEVE, "Steve", NPC, "Steve"));
|
||||
assertThat(world.player(STEVE)).isEqualTo(INCARI);
|
||||
assertThat(world.player(NPC)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePlayerLeavingTakesTheBadgeFromTheNameAndAsksAgain() {
|
||||
joinedWith(Map.of(NPC, "Steve", STEVE, "Steve"));
|
||||
world.tabList(Map.of(NPC, "Steve"));
|
||||
assertThat(world.player(NPC)).isNull();
|
||||
assertThat(world.players()).isEmpty();
|
||||
assertThat(world.takeLookup(Long.MAX_VALUE)).containsExactly("Steve");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLastOneLeavingForgetsTheName() {
|
||||
joinedWith(Map.of(NPC, "Steve", STEVE, "Steve"));
|
||||
world.tabList(Map.of());
|
||||
assertThat(world.players()).isEmpty();
|
||||
assertThat(world.uuid("p1")).isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
{
|
||||
"comment": "Shared with the online service's own tests (ADR 0058). Server hashes are SHA-256 of serverHashPrefix + normalized; proof of work hashes the 16-byte challenge then the nonce as 8 bytes big-endian.",
|
||||
"serverHashPrefix": "incari-server-v1\n",
|
||||
"serverHashes": [
|
||||
{
|
||||
"address": "play.example.com",
|
||||
"normalized": "play.example.com",
|
||||
"hash": "60c7ef8098b204588d5356f7ed8421d75d6e864581bb492c0ea3acdc41d30c76"
|
||||
},
|
||||
{
|
||||
"address": "Play.Example.COM",
|
||||
"normalized": "play.example.com",
|
||||
"hash": "60c7ef8098b204588d5356f7ed8421d75d6e864581bb492c0ea3acdc41d30c76"
|
||||
},
|
||||
{
|
||||
"address": "play.example.com:25565",
|
||||
"normalized": "play.example.com",
|
||||
"hash": "60c7ef8098b204588d5356f7ed8421d75d6e864581bb492c0ea3acdc41d30c76"
|
||||
},
|
||||
{
|
||||
"address": "play.example.com.",
|
||||
"normalized": "play.example.com",
|
||||
"hash": "60c7ef8098b204588d5356f7ed8421d75d6e864581bb492c0ea3acdc41d30c76"
|
||||
},
|
||||
{
|
||||
"address": "play.example.com:25566",
|
||||
"normalized": "play.example.com:25566",
|
||||
"hash": "0822754bc117883eaf02048b993e73fea4c795485f31f9a661e2c5a06e7b1dfa"
|
||||
},
|
||||
{
|
||||
"address": " mc.example.net ",
|
||||
"normalized": "mc.example.net",
|
||||
"hash": "ca62db78ef8e253a3d787e2c1c9fbb26ea4e39e0301c2b927e09954711b171ab"
|
||||
},
|
||||
{
|
||||
"address": "203.0.113.7:25565",
|
||||
"normalized": "203.0.113.7",
|
||||
"hash": "b22cba69d806e7e834d28a59c28f3afab280925ba5f97083504c709372429087"
|
||||
},
|
||||
{
|
||||
"address": "[2001:db8::1]:25565",
|
||||
"normalized": "[2001:db8::1]",
|
||||
"hash": "5475f1ccabd33757b3468bb3edd69d42148db7d789b3b47043e14691ae92336a"
|
||||
},
|
||||
{
|
||||
"address": "[2001:DB8::1]:19132",
|
||||
"normalized": "[2001:db8::1]:19132",
|
||||
"hash": "03ef620aa36eac75597b42336feffa9f1c7799f5046c0585b7d3a96baf234947"
|
||||
},
|
||||
{
|
||||
"address": "wss://Eagler.Example.com/",
|
||||
"normalized": "wss://eagler.example.com",
|
||||
"hash": "caf265f24fe2e0c5cf459d1ba0fc55a51f4fed785d897edb05f43cccd2a21f05"
|
||||
},
|
||||
{
|
||||
"address": "wss://eagler.example.com:443/play/?x=1",
|
||||
"normalized": "wss://eagler.example.com/play",
|
||||
"hash": "c6c67c1b4bd4157416b963a8e200a780135726b35ff6f44f80bd712bc9f3a43b"
|
||||
},
|
||||
{
|
||||
"address": "ws://127.0.0.1:8081",
|
||||
"normalized": "ws://127.0.0.1:8081",
|
||||
"hash": "cbb8f3cc4f8cf4002c0f0a1567e11cd4d904f91c234503549f7717962b9991cd"
|
||||
},
|
||||
{
|
||||
"address": "ws://localhost:80/",
|
||||
"normalized": "ws://localhost",
|
||||
"hash": "22271d8c33149e8d33d789d0e9bf3cc331b2de6530513e12ac09c5a9c07ffaa3"
|
||||
},
|
||||
{
|
||||
"address": "WSS://eagler.example.com/Path#frag",
|
||||
"normalized": "wss://eagler.example.com/Path",
|
||||
"hash": "9d0db5ba8f7a319d62d352f6d3b0bc6be186a7c4a5a1dd6f92b7a86780090d8a"
|
||||
},
|
||||
{
|
||||
"address": "relay:AbC123",
|
||||
"normalized": "relay:AbC123",
|
||||
"hash": "3ebe3866d320caa2bd08ffb76eb813d52103d9e01f0f67ad79253eb844124eaf"
|
||||
},
|
||||
{
|
||||
"address": "RELAY: xyz9 ",
|
||||
"normalized": "relay:xyz9",
|
||||
"hash": "a24c4919b86a113f26e971e6b5b3f40cf6f2489c3a1b949eff9451c54f933819"
|
||||
}
|
||||
],
|
||||
"proofOfWork": [
|
||||
{
|
||||
"challenge": "fkxMOk0V3Jjf2djP8lQ1LQ",
|
||||
"bits": 8,
|
||||
"nonce": 256,
|
||||
"hash": "0088ddcce4ad2a5bf0c292787e39305d9ccae0d6236f52d818f18a13e3d32e2f"
|
||||
},
|
||||
{
|
||||
"challenge": "nO5ExBsYUor2_UYg5XVh6Q",
|
||||
"bits": 12,
|
||||
"nonce": 210,
|
||||
"hash": "000a276364209952182a5caac7cfab6fa0545fe4768e01c9a972039afe648af5"
|
||||
},
|
||||
{
|
||||
"challenge": "LbgcpKdxNS-cAARSw3Frzw",
|
||||
"bits": 16,
|
||||
"nonce": 5123,
|
||||
"hash": "000094a57e6f276308ee5428312f225901df2047539da6673440bddae8edc760"
|
||||
},
|
||||
{
|
||||
"challenge": "kDM5FBh1Dk_VY49pTV4a2Q",
|
||||
"bits": 18,
|
||||
"nonce": 222891,
|
||||
"hash": "0000129b14fc1236f2c8120a173c7ce2a5072aae717f0727d058b06a98bd9d1d"
|
||||
}
|
||||
],
|
||||
"recoveryCodes": {
|
||||
"valid": [
|
||||
[
|
||||
"abcd-efgh-jkmn",
|
||||
"ABCD-EFGH-JKMN"
|
||||
],
|
||||
[
|
||||
"ABCDEFGHJKMN",
|
||||
"ABCD-EFGH-JKMN"
|
||||
],
|
||||
[
|
||||
"0123 4567 89ab",
|
||||
"0123-4567-89AB"
|
||||
],
|
||||
[
|
||||
"oi1l-0000-zzzz",
|
||||
"0111-0000-ZZZZ"
|
||||
]
|
||||
],
|
||||
"invalid": [
|
||||
"abcd-efgh-jkm",
|
||||
"abcd-efgh-jkmnp",
|
||||
"abcd-efgh-jkmu",
|
||||
"abcd-efgh-jk!n",
|
||||
""
|
||||
]
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user