Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
e9c2488
feat: read Mirror's wire format and ids for the live game feed
CodySimonds65 Oct 6, 2026
528c912
feat: decode the live game feed's allowlisted messages strictly
CodySimonds65 Oct 6, 2026
6670b4c
fix: keep the live feed's skill-text parsing and kill reason within t…
CodySimonds65 Oct 6, 2026
b32ba82
feat: define what plugins may receive from the live game feed
CodySimonds65 Oct 6, 2026
67128c0
feat: add the Live game feed setting, on by default
CodySimonds65 Oct 6, 2026
bf15563
feat: count whether the live feed's XP matches the profile poll
CodySimonds65 Oct 6, 2026
ea14891
feat: tap each game panel's socket read-only and decode it off the UI…
CodySimonds65 Oct 6, 2026
f7a14fd
fix: keep the live feed on when a panel closes mid-attach and count o…
CodySimonds65 Oct 6, 2026
79f4cb1
feat: give plugins live battle, skill, location and session events (A…
CodySimonds65 Oct 6, 2026
26cc510
feat: add the Live game feed switch and its counters to Settings
CodySimonds65 Oct 6, 2026
ce3ca3d
fix: drop the always-false victory flag and keep the XP evidence honest
CodySimonds65 Oct 6, 2026
e26bba5
fix: accept any battle result level above zero
CodySimonds65 Oct 7, 2026
9fc3d61
docs: document the live game feed for plugin authors (API 3)
CodySimonds65 Oct 7, 2026
25bc3f3
feat: count XP/hr from the live game feed's fights while it watches a…
CodySimonds65 Oct 7, 2026
090a319
feat: show each fight's exact level and XP over the last profile poll
CodySimonds65 Oct 7, 2026
8068e64
feat: let the live game feed drive the XP tracker, with the profile p…
CodySimonds65 Oct 7, 2026
024eb7c
fix: queue the XP tracker's live calls in the order the feed's state …
CodySimonds65 Oct 7, 2026
7ae99ea
fix: fall back to polling when battle results stop arriving
CodySimonds65 Oct 7, 2026
7744d5f
fix: keep idle time, reset from the press and don't double-count afte…
CodySimonds65 Oct 7, 2026
481e258
fix: combine a frame's battle results and keep a bad tracker call fro…
CodySimonds65 Oct 7, 2026
ecf8fb1
docs: say what follows each fight in the plugin authors' limits and s…
CodySimonds65 Oct 7, 2026
6cc1fc6
fix: don't count a timing pair's closing window as missed battle results
CodySimonds65 Oct 7, 2026
f5920c9
fix: only give up on the feed when no battle results arrive at all, a…
CodySimonds65 Oct 7, 2026
1246531
fix: let the live XP tracker visibly fall between fights and show its…
CodySimonds65 Oct 7, 2026
20d50d7
fix: keep the live status, the fallen rate and clicks steady while th…
CodySimonds65 Oct 7, 2026
1b7f9b7
fix: redraw a live XP tracker once a second, like the rate it shows
CodySimonds65 Oct 7, 2026
2eea76a
fix: keep the XP tracker's Reset menu working while live rows redraw
CodySimonds65 Oct 7, 2026
d822948
docs: say xp.onUpdated also fires on a reset, and that a live scene c…
CodySimonds65 Oct 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions PLUGIN_AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load,
| `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. |
| `author` | yes | 1 to 40 characters. |
| `description` | no | At most 200 characters. |
| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1` and `2`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." |
| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1`, `2` and `3`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, and `3` if it can't work without the [live game feed](#live-game-feed), so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." |
| `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. |
| `icon` | no | Path to a `.png` file inside the plugin folder, at most 256 by 256 pixels and 64 KB. Forward slashes only. Without one, the strip shows a default icon. |
| `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. An international host name is fine: FourFold converts it to its `xn--` form, and that form is what it shows users. After the conversion the host can contain only letters, digits, dots and dashes, so a name with an underscore or any other punctuation is refused. |
Expand Down Expand Up @@ -134,15 +134,17 @@ fourfold.xp.onUpdated(({ accountId }) => console.log('new XP data for', accountI
| `nextLevelXp` | number or null | XP the current level needs in total. |
| `xpUntilNextLevel` | number or null | `nextLevelXp - currentXp`. |
| `hoursUntilNextLevel` | number or null | At the current XP/hr. `null` when there is no rate yet. |
| `xpPerHour` | number or null | The current rate. |
| `xpPerHour` | number or null | The current rate, over the last hour. While the [live game feed](#live-game-feed) watches the account it follows each fight. |
| `sessionXp` | number | XP gained this session. `0` when unknown. |
| `classes` | array | `{ className, level, currentXp, nextLevelXp }` for every class. May be empty. |
| `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. |
| `isStale` | boolean | `true` when there is no XP data yet, when the last read failed, and for a closed account. |

FourFold reads an account's XP only while that account is open, and only if FourFold's own XP tracker can read it. If the XP tracker plugin shows no data for an account, neither will yours. For a closed account the number and text fields are `null`, `classes` is empty and `isStale` is `true`. An id that isn't one of the user's accounts is rejected with `invalid-argument`.

`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes, about once a minute for each open account.
While the [live game feed](#live-game-feed) watches an account, `className`, `level`, `currentXp`, `nextLevelXp`, `xpUntilNextLevel`, `hoursUntilNextLevel`, `xpPerHour`, `sessionXp` and the active class's row in `classes` follow each fight. `updatedAt` and `isStale` still describe the last read. Otherwise the values come from the read, about once a minute.

`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes: about once a minute for each open account, after each fight while the live game feed watches it, and when the user resets the XP tracker.

### Stats

Expand All @@ -151,7 +153,7 @@ const stats = await fourfold.stats.get(account.id);
if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack);
```

`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`.
`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. While the live game feed watches the account, `level` follows each fight; the stats themselves come from the last read. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`.

### Profile

Expand All @@ -173,6 +175,39 @@ if (!profile.isStale && profile.silver !== null) console.log(account.label, 'has

The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read `silver`, `gold`, `location` and `updatedAt` keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`.

### Live game feed

```js
fourfold.battle.onResult(({ accountId, expGained, silverGained, className }) => {
console.log(accountId, 'won', expGained, 'XP and', silverGained, 'silver as', className);
});
const status = await fourfold.live.getStatus();
if (status.state !== 'active') console.log('no live events:', status.reason);
```

API 3. FourFold reads what the game sends to the user's own game panels and passes on a few events as they happen: fights, skill hits and misses, where each account is, and logins. It only reads: it never sends anything to the game or changes what the game does. Plugins get only the fields below, for the user's own accounts. Never other players' data, chat or anything else the game sends.

The user can switch the feed off in FourFold's Settings, and a game update can stop FourFold reading it until FourFold is updated too. So treat live events as a bonus: keep `xp.get` and `profile.get` as the fallback, and check `live.getStatus()`. A plugin that does and keeps `"apiVersion": 2` also runs on an older FourFold, where `fourfold.battle`, `fourfold.location`, `fourfold.session` and `fourfold.live` don't exist: check for them before using them. Declare `3` only if the plugin can't work without the feed.

Every event has the account's `accountId` and `at`, the time FourFold received it, as an ISO 8601 date.

| Call | Fires | Data |
|---|---|---|
| `battle.onStarted(callback)` | A fight starts. | `{ accountId, enemyCount, at }` |
| `battle.onEnded(callback)` | A fight ends. | `{ accountId, at }` |
| `battle.onResult(callback)` | A fight is won. | See below. |
| `battle.onSkillResult(callback)` | A skill is used. | `{ accountId, skillName, outcome, targetsAffected, reason, at }` |
| `location.onChanged(callback)` | An account changes place. | `{ accountId, scene, inBattle, at }` |
| `session.onLoggedIn(callback)` | An account logs in to the game. | `{ accountId, at }` |
| `session.onDisconnected(callback)` | An account's game connection ends. | `{ accountId, reason, at }` |
| `live.onStatusChanged(callback)` | The feed's status changes. | `{ state, reason }` |

- **Fights.** The game doesn't say whether a fight was won: a win is a `battle.onResult` after `battle.onEnded`, and an end with no result is an escape or a loss. `battle.onResult` gives `expGained` and `silverGained` (any double-XP event is already included), `expNeededToNextLevel`, `leveledUp`, `reachedLevel`, `className` (or `null`), `unlockedSkillName` (`null` when none unlocked; comma-joined when several do, at most 64 characters) and `statGains`: `{ maxHp, maxSp, hp, sp, att, mag, skl, spd, def, res, lck }`, the points the fight added.
- **Skills.** `outcome` is `"hit"`, `"miss"` or `"rejected"`. The game rolls once per cast against the skill's chance, so a miss misses every target. A rejected cast (not enough SP, say) never rolled: `skillName` is `null` and `reason` is the game's text. Otherwise `reason` is `null`.
- **Places.** `scene` is the game's own scene name, such as `westhills_b2_dungeon_01`, or `null` when the game didn't name one. `inBattle` is `true` in a fight scene. `fourfold.location.get(accountId)` returns the same `{ accountId, scene, inBattle, at }` for the account's current place, or `null` when FourFold has no live data for it (a closed account, or one that hasn't changed place since the feed started). An unknown account id is rejected with `invalid-argument`.
- **Sessions.** `session.onLoggedIn` fires for a successful login only. `session.onDisconnected` fires on a kick, with the server's text in `reason`, and on a reload or a closed panel, with `reason` `null`. It also ends any fight in progress: a fight cut off by a reload never gets `battle.onEnded`, and after the login the game resumes it with a new `battle.onStarted`.
- **Status.** `fourfold.live.getStatus()` returns `{ state, reason }`. `state` is `"active"` while the feed is on and reading, `"off"` when the user switched it off, and `"unavailable"` when FourFold can't read the game, with the reason in `reason` (a game update FourFold can't read yet, say). `reason` is `null` otherwise. An account already in game when the feed is switched on sends nothing until its game reconnects.

### Timer

```js
Expand Down Expand Up @@ -405,9 +440,11 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve

## What plugins can't do

- Read or control the game, or see its pages, cookies or sessions.
- Control the game, or see its pages, cookies, sessions or traffic. The [live game feed](#live-game-feed)'s events are all a plugin gets from the game itself.
- See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either.
- Get real-time data. XP and profile data arrive about once a minute, and the timer sends no tick events.
- Get other players' data, chat, or anything the live game feed doesn't list.
- Get real-time profile data: silver, gold and location arrive about once a minute. (XP follows each fight while the live game feed watches the account.)
- Get timer ticks: the timer sends no tick events.
- Use shortcut keys, sounds or desktop notifications.
- Draw custom cards. Cards are FourFold's data cards.
- Add a settings page behind the cog. Keep settings in your own panel.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Text.Json.Nodes;
using FourFoldAccountManager.Core.Data;
using FourFoldAccountManager.Core.Models;
using Xunit;

namespace FourFoldAccountManager.Core.Tests.Data;

public sealed class SettingsStoreLiveFeedTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-live-feed-{Guid.NewGuid():N}");
private readonly SettingsStore _store;

public SettingsStoreLiveFeedTests()
{
Directory.CreateDirectory(_root);
_store = new SettingsStore(new LocalDataPaths(_root));
}

private string SettingsPath => Path.Combine(_root, "settings.json");

public void Dispose() => Directory.Delete(_root, recursive: true);

// Every settings file written before this feature lacks the switch; the feed is on by default.
[Fact]
public async Task OlderSettingsWithoutTheSwitchLoadWithTheFeedOn()
{
await _store.SaveAsync(PanelSettings.Default);
var json = JsonNode.Parse(await File.ReadAllTextAsync(SettingsPath))!.AsObject();
json.Remove("liveGameFeed");
await File.WriteAllTextAsync(SettingsPath, json.ToJsonString());

Assert.True((await _store.LoadAsync()).LiveGameFeed);
}

[Fact]
public async Task TurningTheFeedOffSurvivesARestart()
{
await _store.SaveAsync(PanelSettings.Default with { LiveGameFeed = false });

Assert.False((await _store.LoadAsync()).LiveGameFeed);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using FourFoldAccountManager.Core.LiveFeed;
using Xunit;

namespace FourFoldAccountManager.Core.Tests.LiveFeed;

public sealed class GameMessageDecoderTests
{
private static byte[] BattleResultPayload() =>
new MirrorWriter()
.Bool(true) // leveledUp
.VarInt(37) // silverGained
.VarInt(1250) // expGained
.VarInt(380) // expNeededToNextLevel
.VarInt(12) // reachedLevel
.String("Savage") // className
.String("Whirlwind") // unlockedSkillName
.VarInt(4) // gainedMaxSP
.VarInt(2) // gainedSKL
.VarInt(56) // gainedMaxHP
.VarInt(3) // gainedATT
.VarInt(1) // gainedMAG
.VarInt(2) // gainedSPD
.VarInt(1) // gainedDEF
.VarInt(0) // gainedRES
.VarInt(1) // gainedLCK
.VarInt(120) // gainedHP
.VarInt(9) // gainedSP
.ToArray();

// Wrong XP or silver numbers would reach every tracker plugin.
[Fact]
public void ABattleResultDecodesToItsExactValues()
{
var frame = MirrorWriter.Batch(
MirrorWriter.Rpc(GameMessageDecoder.BattleResultSignature, BattleResultPayload()));

var result = GameMessageDecoder.DecodeBatch(frame);

Assert.Equal(
new BattleResult(true, 37, 1250, 380, 12, "Savage", "Whirlwind",
new StatGains(MaxHp: 56, MaxSp: 4, Hp: 120, Sp: 9, Att: 3, Mag: 1, Skl: 2, Spd: 2, Def: 1, Res: 0, Lck: 1)),
Assert.Single(result.Events));
Assert.Equal(0, result.Failures);
}

// A payload that doesn't end exactly where the signature says it should is a different message wearing an
// allowlisted id (a 16-bit collision after a game update), so it must never become an event.
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void APayloadOfTheWrongLengthIsAFailureNotAnEvent(int lengthChange)
{
var payload = BattleResultPayload();
var altered = lengthChange < 0 ? payload[..^1] : [.. payload, 0x00];
var frame = MirrorWriter.Batch(MirrorWriter.Rpc(GameMessageDecoder.BattleResultSignature, altered));

var result = GameMessageDecoder.DecodeBatch(frame);

Assert.Empty(result.Events);
Assert.Equal(1, result.Failures);
}

// Chat, friends and every other message stay unread: nothing about other players reaches the feed.
[Fact]
public void MessagesOutsideTheAllowlistProduceNothing()
{
var chat = MirrorWriter.Message("Game.Chat.SceneChatMessage", new MirrorWriter()
.String("shikaakwa_b3").String("").String("scene").String("SomeoneElse").String("hello")
.Bool(false).Bool(false).Bool(false).ToArray());
var unknownRpc = MirrorWriter.Rpc(
"System.Void PlayerSpeech::RpcSay(System.String)", new MirrorWriter().String("hi").ToArray());

var result = GameMessageDecoder.DecodeBatch(MirrorWriter.Batch(chat, unknownRpc));

Assert.Empty(result.Events);
Assert.Equal(0, result.Failures);
}

// The game server's traffic is untrusted input; nothing in it may crash or hang the app.
[Fact]
public void GarbageNeverThrows()
{
var random = new Random(20261006);
string[] signatures =
[
GameMessageDecoder.OpenHudSignature, GameMessageDecoder.CloseHudSignature,
GameMessageDecoder.BattleResultSignature, GameMessageDecoder.SkillResultSignature,
GameMessageDecoder.LoadSceneSignature
];
for (var i = 0; i < 2000; i++)
{
var noise = new byte[random.Next(0, 300)];
random.NextBytes(noise);
GameMessageDecoder.DecodeBatch(noise);
GameMessageDecoder.DecodeBatch(MirrorWriter.Batch(MirrorWriter.Rpc(signatures[i % signatures.Length], noise)));
GameMessageDecoder.DecodeBatch(MirrorWriter.Batch(
MirrorWriter.Message(GameMessageDecoder.AuthResponseType, noise)));
}
}

// A digit from another script must not slip past the skill-text pattern into int.Parse and crash the feed.
[Fact]
public void ANonAsciiDigitInSkillTextIsAFailureNotACrash()
{
var payload = new MirrorWriter().Bool(true).String("Fireball affected ٣ targets.").ToArray();

var result = GameMessageDecoder.DecodeBatch(
MirrorWriter.Batch(MirrorWriter.Rpc(GameMessageDecoder.SkillResultSignature, payload)));

Assert.Empty(result.Events);
Assert.Equal(1, result.Failures);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.Text.Json;
using FourFoldAccountManager.Core.LiveFeed;
using Xunit;

namespace FourFoldAccountManager.Core.Tests.LiveFeed;

public sealed class LiveFeedPrivacyTests
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);

// The login message carries the game's account id, the username and the admin flag. A plugin must only ever learn
// that one of the user's own accounts logged in, and a failed login must not read as a login.
[Fact]
public void TheLoginEventCarriesNothingButTheAccountAndTheTime()
{
var accountId = Guid.NewGuid();
var frame = MirrorWriter.Batch(MirrorWriter.Message(GameMessageDecoder.AuthResponseType, new MirrorWriter()
.Bool(true).VarInt(987654).String("SecretLogin").Bool(true).String("").ToArray()));

var gameEvent = Assert.Single(GameMessageDecoder.DecodeBatch(frame).Events);
var post = LiveFeedPayloads.ForPlugins(accountId, gameEvent, DateTimeOffset.UnixEpoch);

Assert.NotNull(post);
Assert.Equal("session.loggedIn", post.Value.Name);
var json = JsonSerializer.SerializeToElement(post.Value.Data, post.Value.Data.GetType(), Json);
Assert.Equal(new[] { "accountId", "at" }, json.EnumerateObject().Select(property => property.Name).ToArray());
Assert.DoesNotContain("SecretLogin", json.GetRawText());
Assert.Null(LiveFeedPayloads.ForPlugins(accountId, new LoggedIn(false), DateTimeOffset.UnixEpoch));
}
}
Loading
Loading