218 Commits

Author SHA1 Message Date
funman300 bf6db98f0d Migrate club rename and numeric squad reads 2026-08-18 17:29:24 +00:00
funman300 fc55de19fa test(fifa17-tls): reproducible isolated confirmation of the roster-cert fix
Runs the REAL roster_server.py under `sudo unshare -n` (so port 8081 is free and
production is never touched) and validates its certificate BY THE DIALED IP, proving the
before/after the SAN fix (fbc0da2) targets:

  * OLD cert (DNS-only, production's current shape) -> a by-IP-verifying client is
    rejected with "IP address mismatch, certificate is not valid for '127.0.0.1'" — the
    certificate_unknown class the FIFA client hit.
  * NEW cert (fixed generator, DNS + IP SANs) -> verifies through the actual roster
    server and returns the roster XML (200, application/xml).

roster-cert-verify.py is the client probe (trusts the served self-signed cert as CA,
checks it against the dialed IP, then GETs /fifa17/fut/rosterupdate.xml).
roster-cert-iso-test.sh drives the real server with each cert and asserts new=pass,
old=fail. Two harness bugs were found and fixed while writing it (a shared /tmp log the
production run owns, and a subshell pid that left the first server alive so the "old"
probe hit a stale server presenting the new cert — the tell was "self-signed" instead
of "IP mismatch"), so the final before/after is clean.

Complements the in-process check: this exercises the production server code path, not a
hand-rolled server. Live production confirmation still needs the container rebuilt with
OPENFUT_ADVERTISE set (operator-gated).
2026-08-18 16:37:19 +00:00
funman300 6ae3364bd0 docs: remove docs/ — migrated into the OpenFUT-Vault (single source of truth)
The entire docs/ tree (24 top-level notes, 68 evidence captures, 2 plans, research) has
been migrated into ~/OpenFUT-Vault, the curated Obsidian vault, which is now the sole
home for project documentation. Merges preserved all detail (obsolete material kept
under "Superseded" sections); evidence/plans were copied byte-identical; every migrated
note records its Source: docs/<original>.md provenance. Vault commit f55a5ba.

Documentation lives in the vault from here on. Code/script comments that still reference
docs/ paths are stale pointers only (no build dependency); they can be repointed at the
vault opportunistically. References to fifa17-recon/docs/ are a different tree and are
unaffected.
2026-08-18 16:26:44 +00:00
funman300 5c40b4993f docs: mark the FUT Squad Update cert fix applied (fbc0da2)
Updates status from root-caused to fixed, and records that option 1 (IP SAN) was
taken across the three cert generators, with the verification and the operator-gated
production rebuild that remains.
2026-08-18 15:58:18 +00:00
funman300 fbc0da2a1b fix(fifa17-tls): carry the advertised IP in the roster/redirector cert SAN
The FUT hub failed to load with "An error occurred downloading the FUT Squad
Update" because the client dials the roster (https://<advertise>:8081) and the
redirector BY IP, while the served certificate carried DNS SANs only
(winter15.gosredirector.ea.com + wildcards). The client aborts that handshake with
fatal certificate_unknown. Root cause and evidence in
docs/FIFA17_FUT_SQUAD_UPDATE_TLS.md (commit 082246c): a wire capture shows the client
offering TLS1.2 with RSA suites, the server selecting them, then rejecting the cert —
and autopatch demonstrably patched both ProtoSSL gates in that process, so this
validation path is NOT one of the two the client-side patch covers. The SAN is the fix.

Three generators produced the cert and none put the advertised IP in the SAN:

* docker entrypoint.sh — the production path. The advertised IP is a RUNTIME value
  (OPENFUT_ADVERTISE), unknown at image-build time, so the cert is now reconciled at
  startup: reissued with IP:$ADV,IP:127.0.0.1 in the SAN only when the current cert
  lacks it. That makes a restart reuse the same cert (no per-start fingerprint churn,
  which would otherwise recreate the Aug-13 surprise) and self-heal if $ADV changes.
* Dockerfile — installs openssl unconditionally so the entrypoint can reissue at
  runtime (previously it was dropped with the apt lists), and bakes a loopback-IP
  baseline cert so a plain `docker build` still yields a usable image.
* openfut-fut.sh — the local orchestrator. ensure_cert now defaults the SAN IP to this
  host's primary LAN IP (OPENFUT_ADVERTISE overrides) and reissues when the cert lacks
  it, instead of only generating when the file is absent.

Verified without the client, which is the strongest evidence obtainable here: a
verifying TLS client checking the cert BY IP rejects the old DNS-only cert ("IP address
mismatch, certificate is not valid for '10.10.0.120'") and accepts the new
IP-bearing cert; and the entrypoint reconcile is idempotent end to end — an old cert is
reissued to carry IP:$ADV, a simulated restart leaves the fingerprint unchanged, and
the final SAN carries both the advertised and loopback IPs.

Live confirmation needs the production container rebuilt with OPENFUT_ADVERTISE set
(operator-gated); production is otherwise untouched.

entrypoint.sh carries unrelated pre-existing uncommitted work (env-based component
selection) that is not on any branch; only the cert-reconcile block is committed here,
and that work is left intact in the working tree.
2026-08-18 15:57:19 +00:00
funman300 750d6c2e18 feat(companions): port the launcher's two Python services to Rust
The launcher spawned `python3 lsx_responder_v2.py` and `python3 autopatch.py`. Both are
now Rust workspace crates, and the launcher spawns the binaries (gitlink 1cd4f18).

openfut-lsx (2244 lines, 57 tests) — EA Origin LSX emulator on loopback 4216.
Dependency-light on purpose: `aes` for the one security-shaped primitive, parking_lot
per the project lock rule. AES-128-ECB is the whole cipher requirement, so the
surrounding framing (PKCS7, lowercase hex, NUL-termination) stays explicit and separate
because it is protocol, not cryptography.

openfut-autopatch (43 tests) — ProtoSSL cert gates plus the CardsDLL store patches,
applied over /proc/<pid>/mem. Deliberately dependency-free: a tool that writes another
process's memory should be auditable end to end without a dependency tree. std has no
getuid and no local-time formatting, so it carries a small TZif reader rather than
pulling in chrono to reproduce Python's strftime('%H:%M:%S').

The Python remains in fifa17-recon/tools. It is NOT dead: the docker entrypoint,
client_arm.sh, the runbooks and test_autopatch_guard.py still use it. Only the
launcher's dependency on Python is gone, which is what was asked for; deleting the
recon toolchain's implementation would have broken unrelated workflows.

VERIFICATION — the ports are checked against the Python, not against themselves:

* Crypto parity across THREE implementations. The Rust tests assert the Rust's own
  constants, which proves consistency, not parity, and the Python cannot run here
  (pycryptodome absent) with the client host unreachable. So the LCG and key derivation
  were transcribed from the Python and run as plain arithmetic, and every AES value came
  from the openssl CLI. All agree: msvcr_rand(7)==61, _TAIL_CONST
  954f64f2e4e86e9eee82d20216684899, the 96-hex emu challenge shape, the derived session
  key 6a9da3e78615153cc2f10eec25ae6382, the framing rule at both boundaries (an aligned
  payload gains a whole block), and the port's pinned 4-block login-frame ciphertext.
* LSX end to end on the real port. 4216 here is a docker forward into the production
  netns, so the smoke test runs under `unshare -n` — the real binary on the port the
  client actually dials, with no port-override hack and no risk to production. A
  hand-written client read the unprompted <Challenge>, completed the handshake, and
  decrypted the GetProfileResponse (PersonaId 33068179, Persona CAGE) with a session key
  derived INDEPENDENTLY of the Rust, then observed the Login pushes across all three
  candidate senders.
* autopatch behaviourally. The startup banner, the --launcher-pid watchdog exiting with
  the exact Python message, dual stdout+logfile output, and a missing value rejected
  with Python's own "invalid --launcher-pid". The subagent additionally cross-checked
  every constant by executing the Python module and drove the binary against a synthetic
  client (correct comm, a CardsDLL mapping, gates mmapped at their absolute VAs),
  confirming all eleven patches byte-exact in table order.
* The `[store-guard] verified capability …` line is byte-identical to openfut-launcher's
  own parser fixture, so backend capability registration still works.

Workspace builds; openfut-lsx 57, openfut-autopatch 43, openfut-launcher 74 tests green.
2026-08-18 05:31:00 +00:00
funman300 082246c085 docs: root-cause the FUT Squad Update download failure (client rejects the roster cert)
Recovered the client's own dialog text from memory rather than inferring from the
server, which is what finally identified the subsystem: "An error occurred downloading
the FUT Squad Update" is the ROSTER update, not the player's lineup. Four squad-shaped
fixes before that were aimed at the wrong thing.

Wire capture shows the client aborting the handshake itself: it offers TLS1.2 with RSA
suites, the server selects TLS1.2 and sends its certificate, and the client replies
fatal certificate_unknown. So protocol and ciphers are compatible and the certificate
is the problem. That certificate is DNS-SAN-only while the advertised ROSTERUPDATE_URL
is an IP literal, and it was regenerated Aug 13 -- after the Aug 12 session being used
as the known-good control, which therefore says nothing about the current cert.

Notably autopatch DID patch both ProtoSSL gates in the failing process (log line plus
live bytes reading back patched) and the client still rejected, so those gates do not
govern this path -- contradicting roster_server.py's standing comment that they make
self-signed certs acceptable.

Documents what was ruled out with evidence (hub route shapes, squad shape, squad
round-trip, advertised hosts, TLS version, Blaze health), the probing gotcha that a
default modern TLS context misreports this server as broken, the unresolved question of
why production appears unaffected, and three fix options with a recommendation. No fix
applied.
2026-08-18 05:12:00 +00:00
funman300 16771b0b33 test(scripts): recover the client's error text, and diff hub shapes against production
Three diagnostics from chasing a FUT error that four server-side fixes failed to
resolve, kept because the technique generalises.

client-error-string.py recovers FIFA's on-screen message from /proc/<pid>/mem,
read-only, scanning ASCII and UTF-16LE (FIFA UI strings are wide). This ended the
guessing: the dialog reads "An error occurred downloading the FUT Squad Update.
Please try again." -- a CONTENT DOWNLOAD failure, not the player's lineup. Every
squad fix before it was aimed at the wrong subsystem, because "squad update" in FIFA
means the roster update, and the server-side symptom (a squad the client would not
accept) was consistent with both readings. When the server says 200 and the client
says no, the client's own words are the cheapest evidence available and should have
been the FIRST thing recovered, not the fifth.

hub-dump.py + hub-diff-prod-staging.py diff every hub route between production
(known-good, same client accepts it) and staging, comparing key presence and JSON
types rather than values, since values legitimately differ. Result: 0 structural
differences across 14 routes, which retired the whole "a missing field breaks
bootstrap" line of investigation in one run instead of one restart at a time.

Also ruled out with evidence: cert gates ARE patched (autopatch logs
"pid 56298: PATCHED cert gates", and the gate bytes read back as the patched
patterns); the roster server serves the FUT Squad Update fine (TLS1.2
AES256-GCM-SHA384, HTTP/1.0 200, application/xml) once probed with
ALL:@SECLEVEL=0 -- a default modern context gets SSLV3_ALERT_HANDSHAKE_FAILURE and
would have been a false alarm; production and staging Blaze advertise identical
roster/POW hosts; the Blaze session is healthy and answering PINGs; and the squad
round-trips exactly through PUT/GET.
2026-08-18 04:30:08 +00:00
funman300 022634704a fix(scripts): staging squad now matches production's known-good shape exactly
Adds the manager reference, the last remaining difference from the squad the same
client demonstrably accepts. Staging's squad shape is now identical to production's:
zero missing keys, zero type differences, zero empty-vs-populated mismatches.

The manager looked unfixable. Production points at instance 100000427 while the
staging club holds 11 players and zero staff, so there was apparently nothing to
reference, and inventing an id would have pointed at a non-existent item.

Checking production properly dissolved the problem: 100000427 is absent from
production's OWN club listing too. /club/staff returns 1975 items spanning ids
100000001..100004826 and 100000427 is not among them, and the type=staff/type=manager
filters are ignored (200 players either way). Production's manager reference is
dangling and the client accepts that squad anyway, which proves the client does not
validate the manager id against the club -- only a populated array matters.

So the reference is mirrored verbatim, dangling id included. That replicates the
known-good state exactly and is better than pointing the manager slot at a player,
which would have been a guess dressed up as a fix.

Method note: every step here came from diffing against production rather than reading
the client. The host reported squad-active 200 outcome=ok throughout, and 200 with the
right players was never evidence the client accepted the body.
2026-08-18 03:49:39 +00:00
funman300 96ca7c0484 fix(scripts): the seeded squad was structurally valid but the client still refused it
First seed sent only squadName/formation/captain/players. The host logged squad-active
200 outcome=ok and /squad/0 showed 11 occupied slots, yet the client still threw a FUT
squad update error -- a 200 with the right players is not proof the client accepts the
body.

Diffed against production's known-good squad, which the same client accepts, comparing
key presence and JSON TYPES rather than values. Staging returned null for exactly the
five fields the PUT never carried, because the extension stored nothing for them:
squadType (a string enum), chemistry, rating, starRating (ints) and custom (the opaque
33-int tactics array the client definitely parses). kicktakers was empty where
production carries five.

Now sends all of them: squadType REGULAR_SQUAD, chemistry, rating/starRating derived
from the XI's mean rating, production's custom array verbatim (opaque server-side, only
its shape matters), and five kicktakers. Re-diff leaves exactly one difference --
manager, which production points at owned staff instance 100000427 while the staging
club holds 11 players and zero staff. Left empty rather than inventing an id that
references a non-existent item; recorded in the code as the one known remaining gap.

Also fixes a KeyError from the rewrite dropping the players key.
2026-08-18 03:33:42 +00:00
funman300 202366611e test(scripts): front-load the hub preconditions instead of finding them one restart at a time
The sold A/B stalled twice on preconditions no headless check exercised: the staging
identity had no squad (the hub refuses to open, showing a squad update error), and any
route without a Rust owner falls through to a deliberately dead Python upstream and
answers 502. Each cost a full operator cycle.

Sweeps the routes the client is observed to request and separates three failure classes
that need different fixes: 502/PYTHON_FALLBACK (no Rust owner), missing_integrity (200
but the underlying state is absent -- exactly 'no extension stored' before the squad
was seeded), and 200-but-unusable (a squad with zero occupied slots). A 200 is not
proof the client is satisfied, so squad responses are judged on occupied slots.

Also reads the host's own classification for the requests just made, since the host is
the authority on ownership and integrity rather than the response body.

Every path is verified against what the client actually sends. A first pass flagged
five 'fatal' routes that were my own guesses -- /accountinfo (client uses
/user/accountinfo), bare /squad (uses /squad/active), and /watchlist (camelCase
watchList). Crying wolf about the stack is worse than not checking, so the list now
carries only observed paths and that trap is written down in the comment.

Current result: 14 ok, 0 integrity warnings, 0 fatal.
2026-08-18 03:14:29 +00:00
funman300 ea92057e53 test(scripts): seed the staging seller an XI so the FUT hub will open
The A/B identity had owned items but no squad, because the sold-row work only ever
needed the tradePile wire. Every headless check passed -- none of them asks for a
squad -- but the real client refuses to enter the FUT hub with an empty one and shows
a squad update error. A squad is a hub precondition, not a Transfer-List detail.

Seeds via the real PUT /ut/game/fifa17/squad/0, the same request the client sends, so
parse_squad_put/build_squad_write produce exactly what a genuine save would. Writing
Core rows by hand could yield a shape the live path never emits, which is the kind of
divergence that quietly invalidates an experiment.

Picks one owned player per 4-3-3 slot, best rating first, without reusing an instance;
fills the fixed 23-slot array with 0..=10 as the pitch and empty slots as
itemData.id == 0; refuses to write a partial XI and reports any out-of-position
substitution loudly rather than silently reproducing the broken state. Verified
0 -> 11 occupied with no substitutions and a {"id":0} ack.
2026-08-18 03:07:42 +00:00
funman300 c71593b286 test(scripts): enable the hook on the deployed launcher without a rebuild
Bridges openfut-launcher c542415 onto the already-built launcher on .105 by writing
WINEDLLOVERRIDES=version=n,b into game_profile.env, which that build does apply.
Forward-compatible: the fixed launcher defers to a profile that already pins
version=, so this value simply wins.

Records the prior value -- including its absence, as the literal <absent> -- to a
sidecar before mutating, so revert restores the real previous state instead of
assuming the key was missing. Refuses to edit while the launcher runs, since it holds
its config in memory and would write the stale value back.
2026-08-18 02:59:41 +00:00
funman300 413ad901fb launcher: bump gitlink to c542415 (hook WINEDLLOVERRIDES fix)
Without version=n,b the launcher's own launch path never loaded the version.dll hook
proxy, so the Blaze ports it writes to openfut.cfg were ignored and the client
silently reached production via /etc/hosts instead of the configured server.
2026-08-18 02:57:38 +00:00
funman300 e0e46d8a57 fix(scripts): the port switcher was editing a derived file, so the A/B ran on production
openfut.cfg is not the source of truth for the client's Blaze ports -- the launcher
is. It reconciles openfut.cfg from ~/.config/openfut-launcher/config.json,
fail-closed, immediately before every launch. So `staging` set the ports, verified
them, and the next launch silently reverted them.

Caught only because the capture harness cross-checks instead of trusting the screen.
The operator reported "the Transfers tile does not show Sold" -- which looked like a
clean negative result about the sold counter, and was in fact a reading of their
PRODUCTION club, where sold:0 is correct. Evidence chain:

  * route-log delta contained 5 lines, all of them the harness's own GETs; the
    client issued nothing to staging at all;
  * `ss -tnp` on the client showed FIFA17.exe pid 39482 ESTAB to 10.10.0.120:42130
    (production Blaze) plus TIME-WAIT to :8099 (production UTAS);
  * the hook logged `blaze_redir=42127 blaze_main=42130`;
  * openfut.cfg mtime was 2s before process start, sha back to the production value.

Had the harness reported the tile at face value, the sold counter recovered from
CardsDLL would now be recorded as refuted by a run that never reached the code.

Fixes: own the launcher config (source) before openfut.cfg (derived), with the same
record-before-mutate sidecar discipline on both; refuse to edit while the launcher is
running, since it holds config in memory and would write the stale values back;
report both files and both guards in `show`. launcher_running() matches the
kernel-truncated comm "openfut-launche" -- the full name exceeds 15 chars, which has
bitten this project before.

No production change; staging stack and its variant-A sold row untouched.
2026-08-18 02:40:31 +00:00
funman300 fbe29da05b fix(scripts): sold-client-ports guard self-matched its own shell, wedging it ON
`pgrep -f FIFA17.exe` matched the remote shell executing it -- the SSH command line
contains the literal pattern -- so fifa_running() always returned True and the port
switcher could never edit openfut.cfg. It refused with "REFUSING to edit ... while a
FIFA client is running" moments after FIFA had actually exited.

Fail-closed, so nothing unsafe happened, but the guard was permanently stuck and
blocked the A/B entirely.

Now matches /proc/<pid>/comm exactly, which is the executable name: the invoking
shell reads as zsh and cannot self-match, while a genuine FIFA process still does.
Validated both directions with the same loop -- it found pid 36958 while FIFA was up,
and reports gone once it exited. Still fail-closed on read errors.

The lesson generalises: a pattern-matching process guard checked over a transport
that carries the pattern in its own argv is self-satisfying, and a guard that can
only ever say "yes" is not a guard.
2026-08-18 02:33:53 +00:00
funman300 9ffbd651b1 test(market): one-command live capture for the sold A/B, with in-run validation
Turns the operator's job into "navigate, say go" and removes any chance of a
half-recorded variant. One command captures and labels: the staging wire surfaces,
the client's OWN auction record decoded read-only from /proc/<pid>/mem (STATE,
YOURBID, COINS_AWARDED, MIN_CREDITS, IS_GLOW, INBOX, CARD_OFFERSTATE), and the
staging host route-log DELTA since the last capture -- which is how a client-issued
DELETE .../trade/sold gets OBSERVED rather than assumed.

The part that matters is the wire-vs-memory cross-check. It validates the
observation mechanism against a known-positive in the SAME run: if the wire says
bidState "highest" and the client's memory decodes 2(highest), the probe is
demonstrably reading the right struct this time. It also recomputes the native
IS_GLOW/INBOX formulas from the wire and compares them to what the client stored.

Proven honest on first run: with the client attached to PRODUCTION and not on the
Transfer List, it reported the staging sold row on the wire, 0 client records, and
INSTRUMENTATION NOT VALIDATED -- refusing to draw a conclusion from an empty read.
Two earlier sessions were misled by exactly that (a sampler bug printing
"countdown NO", and auction containers read while the screen was unbound), so an
empty container is explicitly not treated as an empty pile.

Probe base-address discovery was separately confirmed against the live client
(pid 36958, FNV control=MATCH, model resolved, containers read cleanly), and
production's wire independently agreed at total=0.

No production change. Client config untouched (still production Blaze ports).
2026-08-18 02:29:17 +00:00
funman300 aa5fb2cc40 test(market): make the sold A/B one-field attributable, add classified differential
The brief's gate: if the harness varies bidState AND coinsProcessed together, the
client's reaction is attributable to neither. The env knobs were already orthogonal
(--variant and --coins-processed are independent, cp defaults to 0), but
sold-wire-check.py was flipping BOTH for variant B as a convenience, which is exactly
the contaminated A/B the brief forbids. Fixed: the primary pair now holds
coinsProcessed at 0 and asserts the differing-field set is exactly ['bidState'].

New scripts/sold-ab-differential.py is the pre-live gate. It settles ONE synthetic
sale, then re-reads every seller-facing surface under each variant by restarting only
the host (same Core, same DBs, same sale), and diffs with explicit classification --
MISSING / EXTRA / TYPE_MISMATCH / VALUE_MISMATCH -- rather than a boolean "equal?".
Two orthogonal pairs:

  PRIMARY     bidState highest vs buyNow, coinsProcessed held at 0
  ORTHOGONAL  coinsProcessed 0 vs 1,      bidState held at highest

Result, 36/36: the ONLY finding on /tradePile is
VALUE_MISMATCH auctionInfo[0].bidState A='highest' B='buyNow'; /trade/status differs
in exactly the same one path; counts are byte-identical. The orthogonal pair's only
finding is auctionInfo[0].coinsProcessed. C_cp0's sha256 equals A_highest's, so the
capture is reproducible rather than merely consistent.

Counts states the live run has to interpret, measured not guessed:
  S1  0 active + 1 sold -> count 0, selling 0, sold 1
  S2  1 active + 1 sold -> count 1 (active mode) vs 2 (membership mode)
That divergence IS the open question for the client; production is unchanged.

scripts/sold-client-ports.py switches ONLY the two client Blaze port lines, and is
built so restoration cannot depend on memory: it records the production values to a
sidecar on the client BEFORE the first edit and restore reads that sidecar, refusing
if it is absent. It rewrites only known keys (a missing key is an error, never a
silent append), re-reads and verifies afterwards, and REFUSES to edit while a FIFA
client is running because the hook reads the file at connect time.

Phase 0 evidence under docs/evidence/sold-ab-2026-08-18/ with a sha256 per surface,
one file per variant so A can never overwrite B.

Live client A/B NOT run: a production FIFA session is currently live on 10.10.0.105
(pid 32188), and live-session mutual exclusion applies. The client config was NOT
touched -- the switcher's guard refused, as designed.

Production untouched: prod-host pid 3631953, coins 29,843,976, /tradePile 0,
counts.sold 0, club 1966; nothing under /home/alex/openfut-promotion/state/ opened.
2026-08-18 02:22:12 +00:00
funman300 468bc0fba9 feat(market): isolated two-identity SOLD-row A/B harness (staging only, not promoted)
Static RE exhausted CardsDLL on the one open question: for a closed row
IS_GLOW = (bidState != none) and INBOX = (bidState in {highest, buyNow}), so
closed/highest and closed/buyNow are BIT-IDENTICAL natively. But bidState is
published to the movie verbatim as YOURBID, so the FUT ActionScript CAN separate
them. This builds the controlled experiment that asks the client which one it
treats as the seller's sale.

PRODUCTION SAFETY IS THE FIRST CONCERN
New module openfut-utas-host/src/sold_experiment.rs. Every knob is OFF unless its
env var is set, an unrecognised value is OFF rather than a default token (silently
picking one would fabricate the answer being measured), and the host logs a startup
banner naming the active variant so a staging capture can never be mistaken for a
production one. With no env set, /tradePile and /trade/status emit only real active
auctions (the Fix A invariant) and counts still report sold: 0. The entire existing
test suite now passes SoldExperiment::OFF explicitly, making it a regression guard.

  OPENFUT_FIFA17_SOLD_EXPERIMENT      = highest | buyNow   (else OFF)
  OPENFUT_FIFA17_SOLD_COINS_PROCESSED = 1                  (else 0)
  OPENFUT_FIFA17_SOLD_COUNT_MODE      = active_plus_sold    (else active)

WHAT THE EXPERIMENT PROJECTS
Uncleared sold listings appear in /tradePile and /trade/status as tradeState
"closed" with the token under test and currentBid = the sale price; counts report
the real sold tally. There is ONE record builder, so the A/B changes only what is
passed into it, and a test asserts that EXACTLY ONE field differs between the two
variants -- without that control the client's reaction is not attributable to the
token and the whole experiment is void. coinsProcessed (Flash COINS_AWARDED) varies
independently so the third pass cannot be confounded with the first.

CLEAR-SOLD, PE-PROVEN
New EconomyRoute::MarketClearSold for DELETE .../trade/sold, classified BEFORE the
generic trade cancel arm -- a `sold` tail carries no id, so the cancel handler would
have parsed nothing and acked while clearing nothing. Builder 0x1801647c0 emits
"/sold" when the tradeId field is zero and "/%lld" otherwise; the client calls it
RemoveAllSoldFromTradePile. New market-store column cleared_at records the seller's
acknowledgement SEPARATELY from the sale, so clearing can never be mistaken for
re-settling: it is presentation only, moves no coins and no ownership, and is
idempotent for client retries.

FOUND AND FIXED A LATENT STORE BUG
Adding a column via the additive ALTER path immediately after CREATE TABLE in the
same open() desynced sqlx's per-connection schema cache: a fresh store then read a
12-column row while metadata said 13, panicking a pool worker with an index
out-of-bounds and silently returning zero listings. Declaring cleared_at in
CREATE_LISTINGS fixes it; the ALTER now only serves pre-existing stores. This would
have bitten the next column too.

STAGING, WITHOUT TOUCHING PRODUCTION
The client learns the UTAS base from BLAZE (blaze_responder_v3b.py:646 hardcodes
:8099), and it dials that port directly, so redirecting UTAS means changing Blaze or
port 8099 -- both production. 10.10.0.121 is unreachable. The compliant path is a
parallel stack on spare ports plus a one-line change to the CLIENT's own config:
  * scripts/sold-staging-up.py / sold-staging-down.py -- staging Core 18081,
    utas-host 8299, Blaze 42327/42330/42331 advertising :8299, two seeded identities,
    own DBs under /home/alex/openfut-sold-staging/. Patches a COPY of the Blaze
    responder and asserts every substitution applied, so a silent no-op cannot leave
    it pointing at production. Kills only recorded pids whose cmdline contains the
    staging dir (openfut-utas-host matches BOTH, so pkill-by-pattern is banned).
  * docs/SOLD_STAGING_RUNBOOK.md -- the exact client change and its revert.
  * src/bin/staging_sell.rs -- the synthetic Buyer B, running the REAL settlement
    (CoreEconomy::settle_sale) then mark_sold. Settle-first ordering: a failure
    leaves the listing live with nothing moved. Refuses any path containing
    openfut-promotion or the production ports.
  * scripts/sold-wire-check.py -- proves the whole flow headless before any operator
    time is spent.

WIRE CHECK: 35/35 PASS on the canonical 150-coin sale. Seller 1,000 -> 1,143 (fee 7,
proceeds 143), buyer 20,000 -> 19,850, ownership transferred, exactly ONE
authoritative instance, economy shrank by exactly the fee. Sold row: closed,
currentBid 150, expires 0, twelve atoms, counts sold 1 / selling 0, /trade/status
agreeing. Variant B differs only in bidState and coinsProcessed. Clear: 200 {}, row
gone, counts.sold 0, no coins moved, buyer keeps the item, second clear a safe no-op.

Gates: 104 host lib tests (+9), all 7 host targets green, clippy clean, zero fmt
diffs in the new code. Settlement candidate unchanged. NOT PROMOTED.

Production untouched: prod-host pid 3631953 uptime 2h44m restarts=0, coins and
/tradePile unchanged, nothing under /home/alex/openfut-promotion/state/ opened.

The A/B itself is NOT yet run: it needs a real FIFA client, which is operator work.
2026-08-18 02:14:18 +00:00
funman300 571c5f9261 docs(market): recover the FIFA17 sold wire contract from CardsDLL (Ghidra)
Task A, static phase. Ghidra 12.1.2 headless via the repo's own pyghidra harness
over CardsDLL_Win64_retail.dll (13,382 functions). Queries and raw decompiler
output committed under docs/evidence/market-sold-re-2026-08-17/.

RECOVERED FROM THE BINARY

1. No sold token, now EXHAUSTIVELY: both vocabularies dumped to their sentinels
   rather than sampled. tradeState is exactly 4 rows; itemState is exactly 12
   (invalid/free/WAITING_FOR_GAME/inGame/forSale/offered/activeBadge/
   activeHomeKit/activeAwayKit/activeBall/activeStadium/active=255). A sold row
   MUST therefore be a combination of existing atoms.

2. What closed does, complete, from the auctionInfo deserializer 0x18013e410:
     IS_GLOW = (tradeState==closed) ? bidState != none
                                    : bidState in {outbid, buyNow}
     INBOX   = bidState in {highest, buyNow}

3. The full record -> Flash map from the publisher 0x1801bf030, superseding the
   partial list. The prize: record +0xbf is published as COINS_AWARDED, fed by the
   coinsProcessed atom 0x2f4. The corpus had recorded that atom's type and noted
   its consumer was never found; it is now traced. DURATION also renders the
   localised FUT_AUCTION_EXPIRED when expires underflows.

4. highest vs buyNow on a closed row is UNDECIDABLE from CardsDLL, by proof: both
   yield IS_GLOW=1/INBOX=1, bit-identical. But bidState is ALSO published verbatim
   as YOURBID alongside STATE and COINS_AWARDED, so the movie does receive the raw
   values - the discrimination exists and lives entirely in unread ActionScript.
   This retires the question as a static target, and it contradicts the
   third-party lore that a seller's sold row is closed+buyNow (the corpus's own
   lifecycle table says closed+highest and assigns buyNow to the buyer).

5. The clear-sold verb EXISTS. Builder 0x1801647c0 emits "/sold" when the tradeId
   field is zero and "/%lld" otherwise, on route base ut/delete/%s/trade, response
   class RS4 FutISRemoveTradeServerResponse. Confirmed by the client's own
   request-name table entry RemoveAllSoldFromTradePile. A BULK clear-sold verb only
   makes sense if sold rows PERSIST in the seller's pile until cleared, which is
   incompatible with our Fix A invariant - so the sold path will require revisiting
   it under live validation.

6. The seller's SOLD counter is real, proven end to end with no inference: the hub
   tradePile sub-deserializer 0x18013ead0 writes atom sold 0x2c9 to +0x1d8, and the
   tile publisher 0x1800b1dc0 renders +0x1d8 as Flash TEXT3 under the localised
   caption FUT_TF_SOLD. Siblings: selling -> +0x1d2 -> FUT_TF_SELLING,
   count -> +0x1d4 -> FUT_UC_ITEMS, plus FUT_TF_WINNING/FUT_TF_OUTBID on the
   Transfer Targets tile. We and the Python oracle both hardcode sold:0, so that
   bucket can never fill.

7. Reusable method: an atom id is the INDEX into the alphabetical atom-name pointer
   table at base 0x1802d2760. Validated 12/12 against the known auctionInfo atoms
   and cross-checked against fifa17-recon/docs/fut_atoms.tsv. Documented gotcha:
   resolve a name by the pointer slot INSIDE the table, never by the first matching
   string in the binary, or you get confident nonsense.

8. An auction-outcome vocabulary exists (auctionSoldBid 0x39, auctionSoldBuyNow
   0x3a, auctionWon*/auctionLost*) but NO deserializer consumes it - every
   candidate function was checked for the value-SKIP/atom-loop signature and none
   qualifies. Server-side or telemetry only; it does not carry sold state here.

TASK B IS UNDECIDABLE FROM THE CLIENT, and this is a proof of absence: no 0.95 or
0.05 constant of either width, no tax/fee/net/proceeds caption, and no fee
arithmetic anywhere. The client never computes or displays a net, so no experiment
against our own server can measure the rounding - whatever we credit is what it
displays, and there is no oracle. Only an original EA-era seller-balance capture
could settle it. The rule stays an explicit CHOICE (floor the fee, so
fee + proceeds == gross exactly) and is now pinned at the requested boundaries
100/101/119/120/149/150/151/199/200 plus 15,000 and i64::MAX.

Settlement NOT promoted. No production process, port or database was touched.
2026-08-18 01:32:02 +00:00
funman300 cb32fe9b84 docs(market): close Gap 2 and freeze the transfer-list lifecycle as known-good
Return to Club is durable across a full FUT exit/re-entry — the last claim the
forSale promotion could only make server-side.

Same disposable card as Gap 1 (75 ST, res 212188, wire 100000178, tradeId
1000000178), after the 1h auction expired NATURALLY. No timestamp was mutated in
either gap; a read-only sampler watched the whole hour (55 samples), because
`expires` is derived from created_at + duration and watching is the only honest way
to see expiry:

  active   expires 3175 -> counting down -> expired expires 0, itemState forSale
  (absent) total 0                                  <- Return to Club

itemState stayed forSale across active -> expired, the one state change Fix B had
never been watched through live.

The host log then shows the coupled transition and TWO session boundaries:

  route=move-items wire=100000178 pile=club auction_cancelled=1
  route=auth-delete
  route=auth ... sid_opened=true      (fresh session, x2)
  route=hub clubPlayers=1966 auctionCount=0
  route=club total=1986 emitted=1966

auction_cancelled=1 is cancel_active_for_core_item firing, so pile membership and
auction lifecycle cannot disagree. Two independent fresh sessions each rebuilt the
state from durable storage and the operator confirmed the card was still in My Club;
one boundary was the requirement.

18/18 server checks pass IDENTICALLY before and after re-entry: /tradePile total 0,
counts all zero, tradeId -> closed with expires 0 (still resolves, correctly
terminal), /club 1966 with itemState free, 0 duplicate ids, market store cancelled
with 0 active and 0 reserved, coins 29,843,976 unchanged throughout.

No code change was required for EITHER gap. Both tests existed to find out whether
the promoted implementation was already correct on paths it had not been exercised
on, and it was.

Also freezes the full CLUB -> list -> active -> expired -> Return to Club -> CLUB
lifecycle as the reference baseline, with the eight invariants it pins, so a future
change that alters any line is a regression until proven otherwise. Explicitly NOT
established: the SOLD path, /tradePile/counts semantics, the AVM1 gate.
2026-08-18 01:12:46 +00:00
funman300 fbe9804d3e core: quick-sell FK fix (gitlink 637a21e)
Quick-selling a card that was in any squad failed with SQLite 787 FOREIGN KEY
constraint failed, on the live FIFA 17 path (economy_store -> econ.sell_item ->
POST /economy/sell-item). Reproduced, then fixed by evicting the item from every
lineup inside sell_item's existing transaction. routes/cards.rs::delete_owned_card
folded into the same authority, which also gives it the transaction it never had.

Not deployed.
2026-08-18 01:01:20 +00:00
funman300 f6606accb3 feat(market): FIFA 5% transfer fee policy, host settle_sale capability, isolated staging harness
Core gains the generic settlement (gitlink 31ab4a6); the FIFA-specific parts live
here.

FEE (openfut-adapter-fifa17/src/fut/economy_policy.rs), beside pack_price and
match_reward_total because 5% is a game policy constant and Core must stay
game-neutral — Core only validates 0 <= fee <= gross and never computes a rate:

  TRANSFER_MARKET_FEE_PERCENT = 5
  transfer_market_fee(gross)  = floor(gross * 5 / 100), i128 intermediate
  seller_proceeds(gross)      = gross - fee

Integer only. Floating point is never used for coin settlement: 0.05 is not
representable in binary and a f64 round trip can create or destroy a coin at large
prices. Widening to i128 makes overflow unreachable for any i64 price, so no price
ceiling has to be assumed.

ROUNDING IS A CHOICE AND IT IS NOT CONFIRMED. The fee is floored, so the seller
keeps the fractional coin, chosen because it makes fee + proceeds == gross hold
exactly at every input — the property the accounting invariant rests on. The
discriminating case against flooring the seller's 95% instead is a gross of 150:
this rule pays 143, the alternative 142. Nothing in the corpus or the client binary
settles which the real server did (the client is only ever told the gross; no
tax/netPrice/sellerProceeds wire field exists). Pinned at 0/1/19/20/21/39/40/100/
150/200/1_000/15_000/15_000_000/i64::MAX plus a fee+proceeds==gross sweep.

HOST: CoreEconomy gains settle_sale + EconomySale/EconomySaleReceipt, implemented on
HttpCoreClient as POST /economy/settle-sale. Request field names were checked
against Core's actual SettleSaleRequest/SaleReceipt rather than assumed. Absent club
ids are OMITTED from the body (not null), which is what Core's Outside/active-club
defaults depend on, so a unit test pins that body shape. handle_market_buy is
deliberately untouched: the synthetic buy path has no counterparty, so minting there
is correct.

HARNESS: scripts/settlement-staging.py, stdlib only, drives a REAL Core over real
HTTP on an ephemeral port against a throwaway DB (production 8099/8199/18080 in a
hard deny-list checked in three places), seeds the canonical two-party fixture,
prints BEFORE/PURCHASE/AFTER with PASS-FAIL lines, cleans up in a finally. 31/31
pass. It found the rejection-precedence bug fixed in Core, and that Core's content
preflight aborts startup on an owned card whose CardDefinitionId no pack defines.

Gates: Core 194, adapter 217, host 127, harness 31/31, clippy clean, new code
fmt-clean. Nothing deployed; no production process, port or database was touched.
2026-08-18 00:51:37 +00:00
funman300 0a007f4941 docs(market): close Gap 1 — active seller row under forSale is live-confirmed
The one claim the Fix B promotion left open: no active listing existed during
that session, so only the expired path had been exercised.

Closed with a disposable card (75 ST, res 212188, wire id 100000178 — one of
three identical copies, not in the squad) listed through the real FIFA 17 client
at 150/200 for 1h, so expiry arrives naturally. No timestamp touched.

Wire: itemState=forSale, tradeState=active, 12 atoms, prices intact, expires
3562 -> 3556 over a 6s sample (live clock), /trade/status coherent, counts
{count:1, selling:1}, coins unchanged, zero inactive rows (Fix A intact).

The decisive evidence is client-side, not ours: a read-only /proc/<pid>/mem
decode of the live trade-pile auction record returned
  itemState=5(forSale)
on the very field that read -1(<unrecognised>) under listFS. Direct A/B on the
only changed field, taken from the client's own memory.

Operator confirmed the row renders under LISTED ITEMS with correct prices, a
counting-down timer, normal art, and correctly non-actionable while active.

No code change required — the promoted implementation was already correct on the
active path. Claim boundary unchanged: this proves the client DECODES the token
and says nothing about the Flash action-gate term.
2026-08-18 00:15:51 +00:00
funman300 0c4aee6164 market: promote forSale — live-confirmed on the expired path
Operator drove the expired row 1000000155 (res 158023, 93 RW) in FIFA 17 with the
candidate deployed: the row was still actionable, Return to Club was offered, and
it worked — "the card is back in my club".

Server-verified durable afterwards, which is what a fresh session reconstructs:
/tradePile total 0 with zero rows, /tradePile/counts all zero, the card present in
/club (1965 -> 1966 items, itemState "free"), zero duplicate ids, no stale active
listing anywhere in the store (both rows cancelled), and the ended auction
projecting as `closed` (4) on /trade/status. Fix A intact: zero `inactive` rows.

So `listFS` -> `forSale` is protocol-correct AND behaviour-preserving on the path
that matters, and `listFS` is gone from production serialization.

Also worth recording what the result rules out: CARD_OFFERSTATE is NOT a gate term
that requires -1. Every actionable row we had ever seen carried itemState -1, which
looked like a possible client rule; it was a coincidence of our own invalid token.
An expired row decoding CARD_OFFERSTATE = 5 stayed actionable.

Deliberately NOT claimed: anything about the Flash action gate itself. STATE and
the RESERVEDPRICE/MAX_CREDITS pair are untouched and still confounded, so the gate
remains Category C / STRONGLY SUPPORTED / not proven, and AVM1 disassembly of
tradepile.isInActiveAuction is still the separate next investigation.

One gap left open honestly: no ACTIVE seller row existed during the session, so
active-row rendering under `forSale` is unverified. /transfermarket has always
emitted `forSale` on active rows, so it is expected-safe, but it has not been seen.
2026-08-17 23:58:29 +00:00
funman300 a57f4930f0 market: emit FIFA 17's own forSale itemState, not the oracle's listFS
Single-field protocol-correctness fix, deployed as a candidate for a live A/B.

`itemData.itemState: "listFS"` on the seller's own auction rows is not a FIFA 17
token at all: zero occurrences in `CardsDLL_Win64_retail.dll` (md5
4de3493131d7d2ff7f8b360c5ac9b655), zero in 4.26 GiB of live client memory, and it
decodes to -1 through `FUN_180166660` — so the client was handed an unrecognised
`CARD_OFFERSTATE`. FIFA 17's value for an item offered for sale is `forSale` (5),
from the 12-row table at 0x180229cc0.

Changed only where the invalid token was emitted: `handle_market_query`
(GET …/tradePile) and `handle_market_status` (GET …/trade/status). The market
search path already emitted `forSale` and is untouched — which is also why the
risk here was lower than it looked: the client has been decoding `forSale` on a
live route all along, and only the seller's own pile carried the bad value.

Wire A/B on the same expired row: EXACTLY one field differs. tradeId, tradeState,
expires, startingBid, buyNowPrice, currentBid, bidState, sellerName,
sellerEstablished, watched, coinsProcessed, the twelve-atom count and the whole
itemData card are byte-identical; coins unchanged at 29,843,976; Fix A's zero
`inactive` rows intact.

The differential asserted PARITY on this field and therefore passed while BOTH
sides were wrong — the exact mechanism by which the defect survived every run.
`market query tradePile` is now DIFFERENT-BY-DESIGN, pinning oracle == "listFS"
and rust == "forSale" so the divergence cannot silently close again. Where the
FIFA 17 binary contradicts the Python oracle, the binary wins.

Gates: 126 host tests, 214 adapter tests, fmt clean, clippy clean.

NOT claimed: that this preserves the list -> expire -> Return-to-Club lifecycle.
That needs an operator FIFA 17 session and has NOT been observed yet. Also not
claimed: anything about the Flash action gate — `CARD_OFFERSTATE` is one of three
still-confounded candidates and this change does not test it. Revert is one line
if the live test fails.
2026-08-17 23:26:06 +00:00
funman300 f9ca901a50 market: stop advertising unlisted pile members as tradeState:"inactive"
RE of the FUT front-end closed the question the Actions-panel investigation left
open, and the answer retracts Q2 rather than completing it.

`tradeState` reaches exactly ONE native branch in CardsDLL — `cmp …,0x4` at
`0x18013e619`, "is it closed?" — and `inactive`(2) and `expired`(3) take the same
edge, producing bit-identical `flagA`/`flagB` (exhaustive 22-site census of
`[reg+0x88]` reads across the PE; confirmed live, both classes read glow=0
inbox=0). The value is then handed to the movie verbatim as the Flash property
`STATE`, and the action gate lives in the APT/ActionScript FUT front-end: the
trade-pile class partitions rows with `getCardsInAuction`/`isInActiveAuction`
(traces `initPile() - IN AUCTION:` / `- NOT IN AUCTION:`) and only auction rows
reach `PreCheckCardOptions` -> `handleTradeCardAction`. A non-auction row renders
and can never be acted on, which is exactly what the operator saw.

So the rows were never usable. "LIVE-CONFIRMED" established that they RENDER,
which is not the same claim, and I treated it as if it were.

The corpus said this before any of it was built —
`plan-2026-08-06-transfer-market.md:731-733`: "`inactive` decodes but no client
path treats it specially; do not emit it." The earlier note explaining that the
warning "was written about the PRESENTATION function" was motivated reasoning.
This also fires the corpus's own pre-registered falsifier E3 (:368-373).

Removed: the `inactive` projection from `GET …/tradePile` and `…/trade/status`,
`UnlistedCandidate`, `resolve_unlisted_pile`, `unlisted_record`,
`Server::resolve_trade_pile`, and the two helpers that existed only to feed them
(`MarketStore::blocking_core_items`, `Fifa17IdentityResolver::wire_for_owned_id`).
Unlisted trade-pile membership is now internal state with no wire expression.

Nothing is stranded: `/club` excludes only items with an ACTIVE listing, so an
unlisted pile member stays visible in the club, which is where the client can act
on it. Verified live after deploy — `/tradePile` total 7 -> 1 with zero `inactive`
rows, `/trade/status` resolving only the real auction, coins unchanged at
29,843,976, and all six former rows present in `/club` (1965 items).

Tests: 126 pass, fmt + clippy clean. Two guards replace the three tests that
pinned the old behaviour: `the_trade_pile_advertises_only_real_auctions` and
`trade_status_answers_only_about_real_auctions`.

NOT fixed here, deliberately: `itemData.itemState: "listFS"` is not a FIFA 17
token (0 occurrences in CardsDLL md5 4de3493131d7d2ff7f8b360c5ac9b655, 0 in
4.26 GiB of process memory, decodes to -1; the real value is `forSale` = 5, and
the Python oracle emits `listFS` too — which is why the differential never caught
it). `CARD_OFFERSTATE` is one of three unresolved action-gate candidates and
every actionable row observed carried -1, so that change ships alone with its own
live A/B.
2026-08-17 23:14:35 +00:00
funman300 3ce69f8951 launcher: one-button launch flow with an explicit state machine (gitlink 3174fe4)
Normal users press Launch FIFA 17; LSX, autopatch, client preparation and the
pre-launch checks are orchestrated automatically, reusing whatever is already
healthy, and every manual control moves under Advanced / Diagnostics. Service
ownership is tracked so a service the launcher did not start is never killed.
2026-08-17 22:44:30 +00:00
funman300 acd1def00d launcher: machine-independent preflight tests (gitlink 504ceee)
Bumps openfut-launcher past two test-hygiene fixes found by running the suite on
the game machine (.105) instead of only on the server host: the new hook-config
check added a second warning on any box with a hook deployed, and the
shadowed-hostname test was asserting, via backend_reachable's live sockets, that
the local machine has the OpenFUT ports open. Suite now passes on both hosts.
2026-08-17 22:06:58 +00:00
funman300 5ec9c7f8bf launcher: guided first-run flow + hook-config reconcile (gitlink 357501f)
Bumps openfut-launcher to 357501f: Welcome/"Get started" onboarding, Settings as
the single owner of the server address, server-authoritative account claiming,
and `openfut.cfg` reconciled before every launch so a settings change can no
longer leave FIFA pointed at the previous server. Cargo.lock picks up
parking_lot for the launcher (already used by openfut-utas-host and
openfut-identity).
2026-08-17 21:47:05 +00:00
funman300 11c028e6eb fix(market): /trade/status must resolve the unlisted ids /tradePile advertises
Explains and fixes the Phase C partial failure WITHOUT changing a single wire field.

The operator saw a difference between the one-item probe (Time Remaining "-") and the
generalized rows (Time Remaining "Expired"). Cause: route coverage, not encoding.
/tradePile advertised the unlisted tradeIds while ISVIEWTRADE (GET .../trade/status)
resolved ids from the market store only -- and an unlisted pile member has no listing
row, so the poll returned an empty auctionInfo. Observed live as
`route=market-status requested=1 returned=0` repeating for the row the operator had
selected, while that same id was present in /tradePile. The client polls status for
the row it displays and degrades it when the answer is empty, which is also why no
actions were offered. The probe showed "-" only because the client had not yet polled
that id (logs of the time show only tradeIds=1000000097).

So expires, tradeState, itemData.itemState and pile were all innocent. Nothing was
guessed and no field changed: both routes now share one pile enumeration
(Server::resolve_trade_pile), so an id advertised by /tradePile always resolves on
/trade/status. The corpus predicted exactly this -- tradeId must resolve across
/transfermarket, /tradePile, /watchList AND /trade/status; we had stability but not
coverage. Same defect class as the original empty-trade/status bug.

Status still answers only the ids actually asked about, and a real auction always wins
over an inactive row for the same tradeId. Regression test covers all four cases.

Records the downgraded conclusion: "inactive" is a CONFIRMED section/lifecycle
discriminator; whether the full actionable contract is now complete is the operator's
next test. itemState/pile recovery was queued on the assumption the encoding was
incomplete -- neither was touched, and both remain the next candidates if actions are
still absent.

342 tests pass, 0 failed, clippy clean. Verified live: the six inactive ids went from
returned=0 to returned=6.
2026-08-17 21:01:07 +00:00
funman300 afadb13de4 feat(market): PHASE C — expose every unlisted trade-pile item as tradeState "inactive"
Q2 is LIVE-CONFIRMED (operator saw the inactive row under TRANSFER LIST with Start
Price 0 and no Buy Now / Current Bid / timer, active rows still separate under LISTED
ITEMS, and the state survived a full FUT exit/re-entry). Promoting from the bounded
one-item probe to the real behaviour: the env gate is gone and /tradePile now
enumerates the whole trade pile.

Mechanism: read the pile (async), resolve each member to a shaped card (sync, because
the identity/Core resolvers are not `Send`), then build the response (async). The
core->wire lookup is `wire_for_owned_id`, which uses the identity store's
NON-allocating `external_for` -- enumerating a pile is a READ and must never mint a
wire id for an item the client has not seen. Items with no mapping, no Core record or
no resolvable FIFA identity are skipped, never faked.

Includes a bug the DIFFERENTIAL caught and unit tests did not: a pile row OUTLIVES its
auction, so after a sale the seller's `trade` row is stale, and filtering only on
ACTIVE listings re-advertised a SOLD card as an owned unlisted item. Suppression is now
by listing state via `blocking_core_items()` -- active (real auction shown instead),
reserved (sale in flight) and sold (card gone) -- while `cancelled` is deliberately NOT
suppressed, because a cancelled listing means the card came back to the pile. New test
covers all three plus the store-level rule.

counts semantics deliberately unchanged: `count`/`selling` still track auctions only.

341 tests pass, 0 failed, clippy clean. Deployed: the 6 previously stranded pile items
now render, alongside the 1 active listing, with Ronaldo correctly in /club and out of
the pile. Body preserved as phase-c-full-pile-exposed.json.
2026-08-17 20:50:51 +00:00
funman300 b6398c44e6 docs: record the LIVE-CONFIRMED inactive UI contract and the expired->Club transition
Operator confirmed in the real client that a tradeState "inactive" row lands under the
right-hand TRANSFER LIST section and renders Start Price 0 with Buy Now, Current Bid
and Time Remaining all absent, while an active row in the same body continued to
render separately under LISTED ITEMS. That is the Q2 representation confirmed live,
with the token itself dumped from the client's own string table rather than guessed.

Records the observed wire->UI contract as a table plus a fixture
(inactive-row-live-confirmed.json), and names the regression tests that pin it,
including the two guards that the row is never emitted for an item outside the trade
pile and never duplicates a real auction.

Also records the expired->Club coupled transition verified server-side: the listing
went to `cancelled`, the pile went to `club`, /tradePile dropped the item, /club
regained it, and clubPlayers went 1964 -> 1965. That is durable store state rather
than a client-local view, so it survives a session boundary by construction; tagged
pending the operator's final exit/re-enter confirmation.

Adds the counts observation table. `count` currently tracks AUCTION entries and not
total Transfer List membership; semantics deliberately left unchanged until the full
state set has been observed.

No behaviour change in this commit.
2026-08-17 20:31:20 +00:00
funman300 a2bd048ace feat(market): bounded Q2 candidate — one unlisted pile item as tradeState "inactive"
PHASE A settled the token from the CLIENT ITSELF, so this is not a guessed enum.
vocab_dump.py (new; static, read-only, VA->offset through the real PE section table)
dumps CardsDLL's NULL-terminated {const char*, int} vocabularies. The tradeState
table at 0x180229e40 reads exactly:

    'active' = 1   'inactive' = 2   'expired' = 3   'closed' = 4

The sibling tables (type/zone/lev/pos) match the corpus verbatim, which validates the
dumper. So "inactive" is a token the client's own parser decodes.

PHASE B, bounded as instructed. `OPENFUT_FIFA17_UNLISTED_PROBE=<wire id>` exposes
EXACTLY ONE unlisted trade-pile item on /tradePile as a non-active record; unset,
behaviour is byte-identical to before. The other stranded pile items are untouched --
no bulk migration.

Why this shape is forced rather than chosen: the route table has exactly one
trade-pile route, it carries only twelve-atom auction records, `pile` (0x226) has no
deserializer arm so membership comes from the owning list, and of those atoms only
tradeState expresses lifecycle. The row carries tradeState "inactive" with
expires/prices/bid all zero so it cannot render a countdown or a price, and reuses the
item's stable tradeId because the client keys its record store on tradeId and
re-parents itemData -- so listing the item later UPDATES the row instead of leaving a
duplicate ghost.

Both preconditions are re-checked at response time: the item must actually be in the
`trade` pile, and it must not already own a listing. Two tests cover exactly those.
counts semantics deliberately unchanged -- the inactive row is not counted.

340 tests pass, 0 failed, clippy clean. Deployed; the wire now carries all three
lifecycle states at once (expired 1000000097, active 1000000155, inactive 1000000059)
and that body is preserved as a fixture.
2026-08-17 20:25:46 +00:00
funman300 2e97ff1461 docs+tools: dump the CardsDLL route table; narrow Q2 to one candidate by elimination
Re-entry discriminator came back a CONFIRMED BUG: an unlisted transfer-list item does
not survive a fresh FUT session, so our representation cannot reconstruct trade-pile
membership. Evidence acquisition per instruction, corpus and PE first, no guessing.

Adds route_table_dump.py: static read-only dump of CardsDLL's route table from the
on-disk PE, resolving VA->file offset through the real section table instead of
assuming a single .text mapping. Output preserved as evidence. It settles "is
/tradePile the only relevant route?" -- the table holds 45 routes plus 3 empty admin
slots, and row 30 `ut/%s/tradePile` is the ONLY trade-pile route. There is no
trade-pile items route.

That plus three existing PE facts narrows the representation to exactly one candidate
by ELIMINATION rather than choice: the route carries only twelve-atom auction records;
`pile` (0x226) has no arm in the item deserializer so membership is conferred by the
owning list and cannot be added as a field; of the twelve atoms only tradeState
expresses lifecycle; and tradeState's closed vocabulary (active=1 inactive=2
expired=3 closed=4) has exactly one value not already spoken for.

So an unlisted item can only be an auctionInfo record with tradeState "inactive".
Tagged INFERRED-BY-ELIMINATION, not CONFIRMED: the remaining unknown is whether the
Flash Transfer List RENDERS such a record in the unlisted section. Records the
acceptance test (survive a full FUT reload) and the revised invariant that a
transition is complete only when a fresh session reconstructs the same visible state.

No behaviour change in this commit.
2026-08-17 20:10:26 +00:00
funman300 7f37b37be3 docs: capture the unlisted transfer-list state and model the pile/auction boundary
Q2 measured, not guessed. The operator moved a card Club -> Transfer List without
listing it (PUT /item, no POST /auctionhouse) and the state was captured read-only.

Finding: we do not represent the unlisted state on the wire AT ALL. Such an item is
byte-identical to a club item -- itemState `free`, no `pile` field emitted, still
returned in /club and counted in clubPlayers -- while an actively-listed item is
correctly excluded from /club and present in tradePile. Only the host's own pile
store knows the difference. Trade pile held 6 items: 1 listed, 5 unlisted.

The FIFA 17 ENCODING of that state stays UNKNOWN on purpose: returned itemData.pile
is numeric with an unrecovered mapping, and tradeState is a closed table walk where
an unrecognised bidState is silently swallowed as `none`, so a wrong enum produces a
plausible-looking but wrong UI. The corpus warns `inactive` decodes but no client
path treats it specially. One client-only discriminator is recorded instead.

Also models the domain boundary both limbo bugs came from: pile membership and
auction lifecycle are separate facts requiring coordinated transitions. States the
testable invariant -- an item must never be simultaneously excluded from /club and
absent from /tradePile -- with the two ways it was reachable and the commits that
closed each.
2026-08-17 20:01:51 +00:00
funman300 4e31fb98a2 fix(market): returning an item to the club ends its auction; close the panel probe
CLOSES the active-own-auction Actions-panel investigation. Live client plus the RE
corpus plus historical FUT behaviour all agree: an active auction is COMMITTED until
sale or expiry and is not seller-actionable, while an expired unsold item becomes
actionable (relist / return to club). Every observation fits that lifecycle --
active+frozen expires was non-selectable, expired was selectable and relisted fine,
relisting made it active and non-selectable again, and the client never emits a
cancel. Documented with confidence tags, and the dead ends are named so they are not
retried: MAY_BE_REMOVED is a constant 1, and the eight-flag array is the CLUB-CARD
menu with no auction-cancellation flag in it.

Implements the return-to-club transition that closure exposes. A pile move to `club`
now cancels any ACTIVE listing on that item, because the auction that put the card
in the pile has to end with it. Otherwise the pile reads `club` while the row stays
`active`, so the card is filtered out of /club (exclusion keys on active listings)
AND still rendered in the Transfer List: the move appears to do nothing. This is the
same limbo class as the earlier pile-vs-listing bug, found by reasoning about the
transition rather than by another live failure.

Scoped to `active` only: a `reserved` row is mid-sale and a `sold` row is already
gone, so cancelling either would let one card be both sold and returned. Two tests
cover exactly that boundary.

338 tests pass, 0 failed, clippy clean.
2026-08-17 19:56:06 +00:00
funman300 6cc22e5cc5 docs: freeze the known-good auction state and mark tradeOwner DISPROVEN
Records the live-client resolution so the market shape is now a fixture rather than
folklore, and so a future agent cannot burn deployments on tradeOwner again.

Confidence notes updated: tradeOwner remains FIFA17-HISTORICAL (it does exist in
the FIFA 17-era API) but "required by FIFA17.exe Transfer List Actions" is now
DISPROVEN for this client path -- it is not among the twelve atoms the client's
auctionInfo deserializer reads, and it was implemented, deployed, observed inert
and removed.

The real blockers are recorded as CONFIRMED live-client findings: trade/status
polling is load-bearing, `expires` must EVOLVE with wall-clock time (a frozen
value is structurally valid and behaviourally broken), and relist must persist
through the PK conflict that FIFA's re-sent ISStart necessarily causes.

Freezes the known-good bodies under docs/evidence/market-lifecycle-2026-08-17/
with a machine-checkable countdown proof (_index.json._countdown_proof records
expires decrementing, frozen:false) rather than asserting the clock in prose.

States the general rule this cost us: a response can pass differential parity and
render perfectly while still being wrong, because FIFA expects an evolving
server-side state machine, not a static object that resembles one.
2026-08-17 19:42:15 +00:00
funman300 b1d7ed2570 fix(market): relisting an expired auction actually relists it
The client's relist arrives as a fresh ISStart (`POST /auctionhouse`) for an item
that ALREADY has a listing row, so `create_listing` hit a primary-key conflict. The
handler treated `Err(Conflict)` as success: it logged `listed=true`, handed the
client its trade id, and persisted nothing. The stale row kept its old `created_at`,
so the card stayed expired and the relist appeared to do nothing -- observed live,
with the client's price-limits fetch and the ISStart POST both in the log.

The PK conflict IS the relist path. `relist_listing` now resets `created_at` to now
and takes the new prices and duration, so the auction actually returns to the market
with a fresh countdown.

Refuses to revive a `sold` or `reserved` row: re-opening a sold auction would sell
the same card twice. `cancelled` rows ARE relistable (the card is back in the pile).
Missing rows report NotFound rather than silently succeeding. The failure paths still
ack so the screen cannot wedge, but they now say `relisted=false reason=...` in the
log instead of claiming success.

Three store tests: the clock/price reset, the sold+reserved revival guard (plus the
cancelled-is-relistable case), and NotFound.

336 tests pass, 0 failed, clippy clean.
2026-08-17 19:17:35 +00:00
funman300 dcbef721f2 docs+tools: measure the FIFA 17 market gate bytes in the live client
Adds trade_gate_probe.py (read-only: /proc/<pid>/mem O_RDONLY + pread, slide proven
against the on-disk FNV prologue), extending gate_byte_probe.py to vtable slot
+0x270 exactly as the transfer-market analysis asked for.

Measured: IS_TRADING_ENABLED=1 (was 0 in the Python era), TRADE_PILE_SIZE=100
(was 0), watchListSize=50 (was 0), with four controls reading 1. So every
CardsDLL-supplied input that analysis named as a market blocker is now OPEN, which
the Rust host achieves by construction -- it emits userInfo.feature as {} so the
kill switch at 0x180174f19 never arms, and it already sends pileSizeClientData
keys 2 and 4.

This narrows the Actions-panel question to the exe-side UI script term, and rules
out ownership fields, the gate bytes, the cancel route and the state vocabularies
as candidates -- each on measured or PE-derived evidence rather than inference.
2026-08-17 19:09:03 +00:00
funman300 772f8a615a fix(market): pin auctionInfo to FIFA 17's twelve atoms, add the real auction clock
Corrects the record against the CLIENT BINARY rather than library hearsay, using
the project's own reverse-engineering record
(fifa17-recon/docs/plan-2026-08-06-transfer-market.md, read out of the on-disk PE).

REVERTED (refuted): `tradeOwner`, `sellerId`, `offers`. FIFA 17's auctionInfo
deserializer (0x18013e410) reads exactly TWELVE atoms -- bidState, buyNowPrice,
currentBid, expires, itemData, sellerEstablished, sellerName, startingBid,
coinsProcessed, tradeId, tradeState, watched -- and value-SKIPs everything else at
0x180135ff0. Those three fields were added last commit on the strength of
contemporaneous FIFA 17 libraries; the PE says the client never reads them, so they
were inert and could not have been the Actions-panel gate. A preservation emulator
must not emit fields the client does not consume. New test pins the exact set.

ADDED: the auction clock. `expires` is SECONDS REMAINING (never an epoch) and the
client renders a LIVE COUNTDOWN it expects to reach 0. We hardcoded 3600, so no
auction ever aged or ran out. Now `duration` is taken from the ISStart body
(additive `duration_secs` column, defaulting to 3600) and `expires` is derived from
created_at + duration - now, clamped at 0. An active listing whose clock has run
out projects as `expired`/`none`/`expires: 0` -- FIFA 17's relistable state, per the
lifecycle table (active=1 inactive=2 expired=3 closed=4; none=0 outbid=1 highest=2
buyNow=3, both closed vocabularies). Pure projection: no row is mutated, so no
sweeper and no race with the economy.

ADDED: `duplicateItemIdList: []` on GetTradePile, which shares one deserializer
(0x18013e7f0) with ISSearch/ISWatchList over four members and we were omitting one.

CONFIRMED by the same source, so kept: `GET ut/{ns}/trade/status?tradeIds=a,b,c` is
real (ISVIEWTRADE) and my handler matches it exactly, including the comma list.
`ISREMOVETRADE` is `DELETE ut/delete/{ns}/trade/{tradeId}` -- our ORIGINAL spelling
was right. The plain-DELETE arm stays because the same source advises dispatching
on path and being method-agnostic (HTTP verbs are not statically recoverable).

Differential returns to strict key-set parity, with a comment recording WHY parity
is not sufficient: a field absent from both sides is invisible to it.

333 tests pass, 0 failed, clippy clean. Verified live: the twelve-atom record, the
four-member envelope, and the listing correctly reading expires=0 / expired after
aging past its hour.
2026-08-17 19:06:33 +00:00
funman300 bf9ae20367 docs: FIFA 17 transfer-market wire findings with confidence tags
Records the auction-record field set, route spellings, pile encoding and the four
open UNKNOWNs so future agents neither reopen settled questions nor re-guess enum
values. Each claim tagged CONFIRMED / FIFA17-HISTORICAL / INFERRED / UNKNOWN.

Captures the key methodological lesson: oracle parity is necessary but NOT
sufficient for a flow the oracle itself never served -- our auction record matched
the oracle key-for-key while both omitted the FIFA 17 ownership fields.
2026-08-17 18:51:13 +00:00
funman300 58d1f9426f fix(market): add FIFA 17 tradeOwner/sellerId, answer trade/status, route plain DELETE
Three defects behind "selecting my own Transfer List listing opens no dialog".
Pressing the card emits NO HTTP at all, so the gate is a field in what we already
return -- the client decides locally from the auction record.

1. OWNERSHIP FIELDS (FIFA17-HISTORICAL). FIFA 17 auctionInfo carries `tradeOwner`
   (bool), `sellerId` and `offers`; we emitted none of them. `tradeOwner` is the
   purpose-built "this auction is mine" flag, and without it the Transfer List has
   nothing to key owner actions (Remove / Re-list) on. `sellerId` now carries the
   configured persona so it agrees with `tradeOwner` and `sellerName` instead of
   telling three different stories. Persona is threaded from config, never baked in.

2. `GET …/trade/status` ANSWERED EMPTY (CONFIRMED from our own live logs). The
   Transfer List polls this continuously to refresh live auction state. The tail has
   no numeric id, so it fell through `t.starts_with("trade")` into the buy/view arm,
   where `trade_id_from_path` fails and the reply is `{"auctionInfo": []}`. The
   client asked for the state of its own listings and was repeatedly told there was
   none. Now a real handler: `tradeIds` filter, or the whole active pile unfiltered;
   unknown ids are absent rather than an error, so a poll never fails closed.

3. PLAIN `DELETE …/trade/<id>` WAS A SILENT NO-OP. Contemporaneous FIFA 17 clients
   cancel via `DELETE /ut/game/<sku>/trade/<id>`; only the oracle's
   `/ut/delete/game/…` spelling mapped to MarketCancel, so the plain form landed in
   the buy/view arm and "cancelled" nothing while returning 200. Both spellings now
   map to MarketCancel. Kept the oracle spelling: the differential exercises it.

Why the differential missed all of this: our record's key set was IDENTICAL to the
oracle's, so parity was green. The oracle omits the ownership fields too, because
its own remove flow was never driven by a real client either. The differential now
asserts we COVER every oracle key and that our extra keys are EXACTLY
{offers, sellerId, tradeOwner} -- so an unexplained new divergence still fails,
while the deliberate superset is pinned.

Deliberately NOT changed (no evidence): itemState stays "listFS", expires stays
3600 seconds-remaining, bidState stays "none" for active/unbid, counts stays
count=1, and no FIFA 18+ price fields were added.

332 tests pass, 0 failed, clippy clean. Deployed and verified live: tradeOwner=true
sellerId=33068179 sellerName='CAGE' offers=0 on /tradePile AND /trade/status
(filtered and unfiltered).
2026-08-17 18:50:19 +00:00
funman300 3cd31c4322 fix(market): stamp the player's persona as sellerName, not EA's house name
A card listed on the Transfer Market rendered correctly in the Transfer List but
pressing it opened NO Actions panel, so Remove / Re-list were unreachable. The one
field where our auction record diverged from the oracle was the seller: we stamped
"EASFC" while the oracle stamps the account's persona name. `fut_account.py`
annotates that very property as "Blaze PDTL.DSNM / LSX GetProfileResponse Persona /
UTAS sellerName", so EA's house name on the player's OWN listing is simply wrong,
whether or not it proves to be the gate on the Actions panel.

Introduces `non_economy::PERSONA_DISPLAY_NAME` as the single source of truth and
uses it both for the `account/sync` default (previously a bare "CAGE" literal) and
as the market seller. Every listing in this store is the player's own -- there is no
NPC seller in a single-account emulator -- so the fallback is the player.

Also strengthens the differential: it compared only auctionInfo LENGTH and
tradeState, so it was structurally blind to this. It now compares the record key
set and each shared field against the live Python oracle, asserts the seller is the
persona rather than EA, and asserts itemData is the full card rather than a stub.

That strengthened comparison passes against the real oracle subprocess, which
establishes two things: our record's key set is IDENTICAL to the oracle's (we are
missing no field relative to it), and sellerName was the only divergence.

NOTE the limit of that evidence: the oracle's own Transfer List remove flow has
never been confirmed against a real client either (the only live datapoint is a
counts-tile bug), so parity is necessary but may not be sufficient. If the client
still offers no dialog, the missing field is missing on BOTH sides and must come
from client instrumentation, not from the oracle.

14 targets green, clippy clean. Deployed and verified live: sellerName='CAGE',
listing intact, coins unchanged.
2026-08-17 18:29:19 +00:00
funman300 ae5feb05b7 docs: record the external FIFA 17 FUT hub behavioural spec + cross-check
Operator-supplied research document (authored outside this repo) describing the
player-visible FUT hub state machine. Stored verbatim so it cannot drift, with a
provenance header pinning its standing: it is a BEHAVIOUR target, never a protocol
reference. Its own §43 already forbids inventing route/field/sentinel/empty-state
details from it, which matches project policy (guessing wire spellings is the
documented client-freeze class).

Appended a repo-grounded cross-check that tags each relevant claim CONFIRMED /
CONFLICT / GAP / UNVERIFIED, so a future agent cannot mistake the aspirational
parts for observed behaviour. Notably it CONFLICTS with the recovered client
tables twice (Manager League is deliberately excluded from the consumable
overlay; there is no apply-consumable endpoint upstream at all), and it usefully
confirms that "sent to the Transfer List but not currently listed" is a real FUT
state -- which is exactly the limbo f2c4927 worked around.
2026-08-17 18:25:23 +00:00
funman300 f2c4927ea6 fix(club): hide only ACTIVELY-LISTED cards, not the whole trade pile
Keying the club exclusion on the `trade` pile put cards in limbo: the pile can
hold cards with no active listing (a bare "Place on Transfer Market" move, or a
listing later cancelled/sold), and `/tradePile` renders ONLY active listings — so
those cards were invisible in BOTH views. Live prod had 5 trade-pile rows but 1
active listing, so 4 owned cards had no reachable screen (clubPlayers 1966->1961).

Key on the ACTIVE LISTING instead (market store `core_item_id` of `state=active`).
This is self-healing: the moment a listing stops being active the card is back in
the club, with no extra transition to maintain and no need to invent an
"unlisted transfer-list" wire shape (`tradeState` has no verified spelling for
that state, and guessing enum spellings is the documented client-freeze class).

A bare pile move therefore no longer hides a card. That is deliberate: our
`/tradePile` shows only active listings, so hiding on the move alone would
reintroduce the limbo it is meant to prevent.

Verified live: clubPlayers 1961 -> 1965 (exactly the one listed card hidden, the
4 stranded cards recovered); listed wire still absent from /club; counts and
tradePile unchanged. 14 targets green + clippy clean.
2026-08-17 18:10:32 +00:00
funman300 aa2abc2772 fix(market): make the transfer market work end-to-end (live-verified)
Four defects found by driving a real FIFA 17 client. Each was independently
sufficient to break listing, so all four had to go:

1. Every owned card was shaped `untradeable: true` (adapter item.rs), so the
   client greyed out "Place/List on Transfer Market" for the whole club. Owned
   and pack-pulled cards are TRADEABLE in FIFA 17; the oracle forces this off
   for owned copies too (item_def keeps `true`; instances do not).

2. `POST /auctionhouse` required `itemData.resourceId`, which the client's
   FutISStart body never sends (the oracle lists by wire id ALONE). Missing it,
   the handler fail-closed and returned 200 while persisting NOTHING. It now
   resolves server-side: wire id -> Core owned instance -> its card_id (minted on
   a synthetic buy) + FIFA resourceId (the auction record). This also enforces
   that a listing can only name a card the club actually owns.

3. An auction record's `itemData` was a 4-field STUB, so the Transfer List had a
   row the client could not draw -> "1 item listed" but no visible sale. A
   listing now persists a full shaped-card SNAPSHOT (new `listings.item_json`,
   additive migration) built by the same `shape_item` shaper `/club` and the
   squad projection use, so the auction card renders identically to the club
   card. The seller's own pile stamps `itemState: listFS`; market search keeps
   `forSale` (the oracle distinguishes these).

4. `/tradePile/counts` shared a handler with `/tradePile`. They are DIFFERENT
   deserializers: `/counts` is FutGetAuctionCount, five scalar ints
   (count/maxAuctionsAllowed/offered/selling/sold) that it reads and skips
   everything else. Served the `auctionInfo` body it left every count at 0, so
   the Transfer List screen showed no active sale while the hub tile showed one.
   New Route::MarketCounts, classified BEFORE the base tradePile matcher (which
   also accepts the /counts path).

Also: a listed card no longer appears in the club. `/club` and the hub's
`clubPlayers` now exclude the transfer pile. Pile membership is host-owned state
Core cannot filter on, so when anything is hidden `/club` reuses the existing
local-filter path (the one `rare=SP` already needed) and paginates the
club-visible set -- letting Core paginate would return short pages. With nothing
hidden the fast Core-paginated path is untouched, and only an EXPLICIT non-club
pile hides a card, so no-pile-row items still default to the club.

Fixed 5 pre-existing test fixtures across 4 targets that listed FABRICATED wire
ids -- only "valid" because the old handler skipped the ownership check.

Tests: 14 targets green + clippy clean, incl. new coverage for the 5-int tally
(asserting it must NOT carry auctionInfo), the full-card snapshot + listFS, and
club pile-exclusion with full-width pagination. The differential test against the
live Python oracle passes.

Verified live on prod: listed=true with a 21-field snapshot; counts
{count:1,selling:1,maxAuctionsAllowed:100}; tradePile renders the 94-rated card;
clubPlayers 1966 -> 1961 (exactly the 5 trade-pile items); listed wire absent
from the club page. Operator confirmed the card is visible in the Transfer List.
2026-08-17 18:03:06 +00:00
funman300 1aa84afa9a feat(host): migrate item-defs + marketdata UTAS reads to Rust
Two more real client-hit reads move off the Python proxy:

- GET /item/resource, /defid (Route::ItemDefs): build {itemData:[item_def…]}
  for every >=3-digit id in the query, replicating the oracle's item_def
  (assetId = resourceId & 0xffffff; hardcoded Ronaldo asset 20801 + a generic
  "Player" 75 CM placeholder). The client renders the real card from its local
  DB, so the placeholder is exact parity.
- GET /marketdata (+ /marketdata/pricelimits) (Route::MarketData): suggested
  pricing, constant band 150..15000. /pricelimits returns a BARE ARRAY (one
  {defId,minPrice,maxPrice} per queried defId); plain /marketdata returns an
  OBJECT {minPrice,maxPrice}. The container type is load-bearing — object-where-
  array froze a live client at the listing screen, so the handler picks it from
  the path.

Adds extract_long_ints / extract_defid_param query parsers, shape+parser unit
tests (incl. the freeze-critical container-type assertions), and classify-table
coverage. Deployed to prod-host 2026-08-17; verified owner=RUST 200 for all four
(Ronaldo/placeholder resolve, pricelimits=array, marketdata=object).

Docs: PRODUCTION_AUTHORITY_MATRIX + PYTHON_RETIREMENT_PLAN updated. Remaining
Python tail is now only mutation (user/club), no-Core-model (squad/<n>), and
unimplemented modes (draft/leaderboards/sbs).
2026-08-17 16:21:17 +00:00
funman300 33e9118329 feat(host): migrate flag-off UTAS reads (season/tournament/champion/clubUser/user-list) to Rust
FUT modes (Seasons/Tournaments/FUT Champions) and the club-identity service are
disabled in this emulator, so these GET reads return {} verbatim from the Python
oracle. Serve them directly from Rust via a new Route::FeatureOffEmpty +
non_economy::feature_off_body() -> {} (byte-identical to the flag-off oracle),
reducing the proxied Python surface.

- The mutating club rename (user/club) stays on Python (needs a Core write).
- Enabling a mode later requires a real Rust handler here, never a Python
  fallback (no split authority).
- classify tests: 5 routes owned + user/club/wrong-method lookalikes stay
  Passthrough; updated the stale clubUser assertion.
- Deployed to prod-host 2026-08-17; verified owner=RUST 200 {} for all five.

Docs: PRODUCTION_AUTHORITY_MATRIX + PYTHON_RETIREMENT_PLAN updated.
2026-08-17 16:10:53 +00:00
funman300 e06fd57211 feat(host): migrate non-economy UTAS routes to Rust + launcher redesign
Host/adapter (deployed to prod-host):
- POST /ut/auth (+/ut/delete/auth): Rust mints sid, opens Rust session, adopts
  persona from body; POST /openfut/account/sync full Rust envelope.
- GET /userMassInfo: full Rust (was proxy+overlay), shared build_user_mass_info.
- GET/PUT /clientdata/<key>: new clientdata_store.rs (JSON-persisted).
- GET /club/stats/{country,league,team}: context-aware club_stats_body
  (nation/league/team buckets).
- GET /store,/match/keepalive,/captcha,/tfa,/livemessage,/activeMessage: StaticAck.
- GET /watchList, /squad/0, /user: Rust handlers.
- host_test.rs updated for the new routing.

Launcher: bump gitlink to c277213 (shareholder-grade redesign + live account panel).

Docs: PRODUCTION_AUTHORITY_MATRIX, PYTHON_RETIREMENT_PLAN, MATCH_LIFECYCLE, and
route-shapes-2026-08-17 reference fixtures for the still-Python tail.
2026-08-17 16:04:20 +00:00
funman300 42fd3c7e90 core: deploy correctness fixes (SBC exploit + economy TOCTOU) + docs
Bump openfut-core gitlink to 68d1065 (correctness fixes: SBC duplicate-card
exploit, non-atomic economy CAS guards, season/checkin panics, sbc_submissions
club_id migration 0019). Deployed to prod-core (DB migration ver 18 -> 19).

Add docs/CORE_CORRECTNESS_ISSUES.md (audit + Resolution) and
docs/OVERNIGHT_HANDOFF_2026-08-17.md.
2026-08-17 16:01:27 +00:00
funman300 0bc71dbd74 docs(evidence): capture full-length UTAS responses + userMassInfo envelope
Fix extractor truncation (bound each HTTP message by Content-Length): userMassInfo
(8 KB) and purchasegroup responses are now complete in the committed corpus, not
cut at 4 KB. Document the userMassInfo envelope contract (target shape for a future
full-Rust migration; needs the clubAbbr/established account triad Core lacks).
2026-08-17 04:13:55 +00:00
funman300 2ecd830d75 docs(evidence): commit fresh sanitised UTAS wire captures (2026-08-15 live A/B)
Rebuilds the primary-capture corpus lost to .gitignore (Known Issues #200): 10
real-client requests + 12 responses captured during the post-P1 staging A/B on a
real FIFA 17 client, sanitised (SID/authCode/deviceId/MAC/tokens redacted; raw pcap
withheld). Documents the account/sync, empty-My-Packs 65534 sentinel, and userMassInfo
contracts, incl. the finding that account/sync is coupled to Python active-profile
selection (so it can't migrate standalone from the userMassInfo hybrid).
2026-08-17 04:09:56 +00:00
funman300 3a51b0ebd4 docs: correct wrong Fire2 header traps in heat2.py + fifa-blaze frame.rs
Both files documented a wrong Fire2 header layout as authoritative, the reader
trap called out in Known Issues:
- heat2.py's module docstring labelled its >IHHHHB3s header 'VALIDATED'. The
  round-trip only validates the payload length + TDF body; decode->encode with the
  same mislabelled header trivially reproduces the capture, so it never tested the
  [10:16] field boundaries. Marked superseded; cite the proven layout; warn at
  build_fire2_frame. Code unchanged (dead tooling).
- fifa-blaze frame.rs: see submodule commit f4f3396.

Bumps fifa-blaze submodule eccd46f -> f4f3396 (FIFA23 stub; not in the prod
container; no prod impact).
2026-08-16 21:29:52 +00:00
funman300 ad406f21bd fix(tls): share bare-probe classification across all FIFA-facing TLS hosts
A reachability probe (TcpStream::connect then drop; the launcher preflight makes
them) reaches a TLS acceptor as 'unexpected EOF' — byte-identical to the
certificate mismatch that cost three live gates. The redirector classified the
opening before the acceptor to keep a benign probe from forging a TLS fault, but
the roster host (the second FIFA-facing TLS host) did not, so the documented
hazard 'remains in any other TLS host that has not adopted it' was live there.

Lift the pure policy (PeerOpening + classify_opening) plus a peer_opening(&TcpStream)
peek helper into the shared openfut-tls crate (game-independent; +unit tests).
The redirector now re-exports them (public API + its probe_classification test
unchanged; behaviour identical). The roster host adopts them: a ProbeCount, a
probes() handle, and a pre-acceptor peek that logs PROBE and returns instead of
failing the handshake. New roster probe_classification integration test (3 cases:
bare probe classified, real client after a probe still served 200, speaks-then-
fails still reported as a fault). Full workspace tests green; clippy -D clean.
2026-08-16 20:30:50 +00:00
funman300 12fb9fc38b chore: update workspace Cargo.lock after excluding openfut-hook
openfut-hook (now its own workspace root) and its windows-sys deps are no longer
part of this workspace's lockfile.
2026-08-15 19:32:18 +00:00
funman300 7b580a0070 chore: bump openfut-hook clippy -D warnings cleanup (0d3f33c -> d1a71bd) 2026-08-15 19:31:25 +00:00
funman300 22443a3810 build(hook): exclude openfut-hook from workspace so its release profile applies
openfut-hook (Windows version.dll injected into the FIFA client) declared a
[profile.release] with panic=abort/strip/opt-level=s that Cargo silently ignored
because it was a non-root workspace member (per-package `panic` overrides are
forbidden). Move it out of `members` into `exclude`; the submodule now carries a
matching empty [workspace] table so it builds as its own root. Fixes cross-FFI
panic-unwind UB in the injected DLL, shrinks it 1200126 -> 861696 B, and lands the
artifact in openfut-hook/target/ (matching launcher config.rs hook_dll_path).

Bumps openfut-launcher submodule ca7ce26 -> 0d3f33c.
2026-08-15 19:25:19 +00:00
funman300 0fce1e521c docs: mark club/stats/{year,consumables} Rust-owned in authority matrix
Global MY-CLUB stat set now Rust (staging-verified RUST route=club-stats
owned=1982 players=1962); only club/stats/{country,league,team} nation-bucket
context sub-screens remain proxied (low value, inert atoms).
2026-08-15 18:04:23 +00:00
funman300 71fcf5e251 feat(fifa17): own club/stats/{year,consumables} in Rust (Core-accurate)
Migrate the MY CLUB stat set from the Python proxy to a Rust handler computing
Core-accurate counts: player tiers + rare from the collection, staff/consumable
families from catalog kind+subtype, per-nation buckets via the reverse entity
resolver. Faithful port of fut_club_stats.py (VOCAB + global_counts +
context_rows). Unlike the oracle (stale profile + synthetic consumable shelf),
this reflects the real imported content (incl. the content-gap consumables/staff).
Fail-closed 503 on Core error. club/stats/country|league|team sub-screens remain
Python (documented). Adds adapter club_stats module (5 tests), host handler +
classify arm + resolver subtype_of/rareflag_of, ownership + integration tests;
reachability tool splits club/stats global(migrated) vs context(residual).
2026-08-15 17:56:37 +00:00
funman300 979e71fbea docs: record precise blockers for remaining Python non-economy routes 2026-08-15 17:31:15 +00:00
funman300 45e0b0bd95 docs: mark hub + club/stats/staff migrated in authority matrix 2026-08-15 17:18:55 +00:00
funman300 70eb3fc13f feat(fifa17): own FUT hub tile counts in Rust
Migrate GET /hub from the Python proxy to a Rust handler deriving counts from
authoritative state: clubPlayers = owned PLAYER cards in Core (consumables/staff
excluded via catalog kind; may be lower than Python's profile count by the
deferred Legend instances = DIFFERENT-BY-DESIGN), auction/tradePile counts from
the durable market store via the async bridge. Fail-closed 503 on Core error;
market read failure degrades cosmetic counts to 0. Adds classify arm, handler,
ownership + integration tests; reachability tool marks hub migrated.
2026-08-15 17:18:06 +00:00
funman300 b30aa352f6 docs: record post-P1 candidate migration status + clientdata Core blocker 2026-08-15 17:13:47 +00:00
funman300 67cc33cfee feat(fifa17): own club/stats/staff (empty stat set) in Rust
Migrate GET club/stats/staff from the Python proxy to a Rust static handler.
The production oracle returns {} for the staff-bonus stat set (deliberately
empty); the Rust host now owns it (owner=RUST route=club-stats-staff). Updates
classify(), the pre-existing near-miss test (now club/stats/year), the ownership
matrix test, and the no-fallback integration test. club/stats/{year,consumables}
remain Python (aggregation) pending the Core-derived club-stats migration.
2026-08-15 17:13:16 +00:00
funman300 6eec3b9ec7 test(fifa17): add UTAS route-reachability reporter (Python-hit gate)
Parses the host owner= dispatch log into per-owner + per-domain counts and gates
on the post-P1 invariants: economy Python hits == 0 (P1 regression), migrated
non-economy routes (accountinfo/settings/leaderboards/match-reset/phishing) ==
0, and residual Python domains == documented set. Read-only; staging-preflight
and Phase 40 live-ownership use.
2026-08-15 17:01:11 +00:00
funman300 57773b98ec docs: Python retirement readiness classification (post-P1) 2026-08-14 05:36:32 +00:00
funman300 fe9b899a0e docs(fifa17): record .105 Legends unrecoverable verdict (dcplayernames empty) 2026-08-14 05:26:02 +00:00
funman300 abe9e663c1 feat(fifa17): import consumable + staff content as first-class Core content
Close 20 of the 33-record content gap (17 consumables + 3 staff; 13 Legends are
unrecoverable from PC data). Verdict A (no Core change): consumables/staff become
ordinary Core CardDefinitions (neutral player fields + honest family/role names)
and owned instances via the SAME generic import path; a catalog kind lets the
adapter exclude them from the player-only /club projection.

- adapter fut::content_taxonomy: evidence-based cardsubtypeid->family/label
  (Ghidra-derived ranges) + staff role map; unknown subtype => defer, never fabricate.
- adapter catalog: Fifa17CardIdentity/RawCard gain optional kind+subtype
  (backward-compat: legacy catalogs load as player); kind_of/subtype_of lookups.
- adapter item/club_response: shape_club_response excludes non-player kinds
  (ShapeStats.excluded_non_player); ItemIdentityResolver::kind_of default=Player.
- host Fifa17IdentityResolver overrides kind_of to delegate to the catalog so
  /club excludes consumables/staff in production.
- import: Item gains cardsubtypeid/cardassetid/amount/contract; plan_non_player_definitions
  (resourceId-grouped, subtype-consistency gated); emit_content writes non-player
  defs + catalog kind + manifest; apply mints owned instances via owned_item_id.

Real profile 33068179: 1962 players + 20 non-player = 1982 owned; 18 non-player
defs (16 consumable + 2 staff, dup resourceIds shared); 0 deferred non-player; 0 blockers.
2026-08-14 05:26:02 +00:00
funman300 f5a33eb58c test(fifa17): prove non-economy routes are Rust-owned with no Python fallback 2026-08-14 05:08:37 +00:00
funman300 a85090c3c6 feat(fifa17): own non-economy static + security-question routes in Rust
Migrate 5 non-economy UTAS route families from the Python oracle proxy to
Rust host ownership: user/accountinfo, settings, leaderboards/options,
match/reset, and phishing/{trusteddevice,question,validate}.

- adapter fut::non_economy: pure IO-free shapers matching the observed prod
  oracle bodies + a verbatim port of security_question_route (stateless ack;
  answer never stored/compared; trusted-device is an invariant constant).
- host: Route variants + classify() arms + owner=RUST dispatch; the
  security-question X-UT-SID gate reuses SessionStore::session_known.
- tests: 9 adapter unit tests (contract) + host non_economy_route_ownership
  (classify + classify_economy negatives).
2026-08-14 04:57:28 +00:00
funman300 97d48d8371 docs: record post-P1 production authority matrix + FIFA17 content completeness 2026-08-14 04:57:28 +00:00
OpenFUT Agent 5020137050 docs(fifa17): record retail economy route grammar (purchased/items, tradePile) 2026-08-14 00:50:03 +00:00
OpenFUT Agent cf05ab2a9e test(fifa17): replay retail purchased/items BUY + route matrix via dispatch
- pure_economy_routes (NEVER-BOTH + no-fallback) gains POST/GET purchased/items,
  lowercase tradepile, tradePile/counts -> all asserted Rust-owned, proxy 0.
- retail_purchased_items_buy_debits_core_through_dispatch: the exact round-2
  live failure -> POST /purchased/items now debits Core, reveal shows minted
  items, repeat reveal idempotent, Python proxy count 0.
2026-08-14 00:50:03 +00:00
OpenFUT Agent a6416a3f1d fix(fifa17): classify full retail economy route shapes
Round-2 live staging (candidate 47ced22) showed the CONFIRMED retail Store BUY
uses POST /ut/game/fifa17/purchased/items (reveal GET .../purchased/items),
which the exact-tail 'purchased' match missed -> Python (Core coins unchanged).
Comprehensive audited fix in classify_economy:
- is_purchased_tail: 'purchased' AND 'purchased/items' (POST->PackOpen,
  GET->PackReveal); bounded (rejects purchasedfoo, purchased/items/extra).
- is_tradepile_tail: 'tradePile' family CASE-INSENSITIVE incl 'tradePile/counts'
  (hub tile polls lowercase; oracle routes via re.I); allocation-free.
- (kept) v1/v2 prefix normalization + store/transaction[/<digits>].
Adds retail_route_matrix unit test = the machine-auditable route contract gate
(all economy shapes + negative near-misses). Host lib 75.
2026-08-14 00:50:03 +00:00
OpenFUT Agent 47ced228de docs(route-authority): record v1/v2 economy URL prefix contract
Accepted prefixes /ut/game/<sku>/ and /ut/v2/game/<sku>/ for every economy
route; StoreBuy accepts store/transaction and store/transaction/<txn-id>.
2026-08-13 23:53:44 +00:00
OpenFUT Agent b8beeba98d test(fifa17): cover retail v2 Store route shapes
Through real handle_with_ip dispatch against live Core:
- pure_economy_routes gains the retail v2 Store family (transaction/0,
  purchasegroup, purchased GET/POST) so NEVER-BOTH + no-fallback assert them
  Rust-owned (Python proxy count 0) and fail-closed 503 on dead Core.
- Part-7 repro: PUT /ut/v2/game/fifa17/store/transaction/0 returns a Rust
  createPackResponse + debits Core (NOT the Python TRANSACTIONCANCEL no-op).
- retail_v2_store_flow_matches_v1_through_dispatch: v1 and v2 BUY of the same
  pack debit + mint identically; v2 purchasegroup + reveal Rust-owned.
2026-08-13 23:53:44 +00:00
OpenFUT Agent df6994c957 fix(fifa17): classify retail v2 economy routes
Live staging (S2) showed the retail FIFA17 client issues the Store family
under /ut/v2/game/<sku>/... (PUT /ut/v2/game/fifa17/store/transaction/0),
which escaped Rust economy authority to Python. Fix classify_economy:
- ut_tail() normalizes both /ut/game/<sku>/ and /ut/v2/game/<sku>/ to the
  same tail (generic sku, never hard-coded fifa17); delete family likewise
  accepts /ut/v2/delete/game/.
- StoreBuy matches store/transaction and store/transaction/<digits> via a
  bounded is_store_transaction_tail (never store/transactions, ...foo, or
  .../<id>/extra), mirroring the Python bare /store/transaction regex.
Adds table-driven ut_tail + is_store_transaction_tail + classify_economy v2
unit tests (lib 74).
2026-08-13 23:53:44 +00:00
OpenFUT Agent d74e86c065 docs(fifa17): record Rust economy authority proof (E1 cutover ready)
Final per-route authority table: every economy route owner=Rust, Python
proxy=NO (userMassInfo the one hybrid: Python envelope + Rust economy/squad
overlay). Barrier 93a46d4; from_config 43917a0. Proofs: differential 15 PARITY
+ 1 DIFFERENT-BY-DESIGN, concurrency 8x50, failure 10 (complete-sale SAFE, no
E3), importer 5-step, from_config E2E, NEVER-BOTH / no-fallback / stale-reader.
Python source byte-unchanged; oracle suite 32/32.
2026-08-13 22:44:12 +00:00
OpenFUT Agent 76512f6048 test(fifa17): prove post-barrier economy authority (never-both / no-fallback / stale-reader)
barrier_never_both_no_fallback_and_stale_reader drives the REAL post-barrier
handle_with_ip against a live in-process Core + a mock Python upstream that
counts every request and answers with a coins=111 marker:
- STALE READER: credits + userMassInfo show the Core balance, never 111
  (userMassInfo proxies the Python envelope but the Rust economy overlay wins).
- NEVER BOTH (Core up): every pure economy route returns a Rust body (no
  __python__ marker) and the Python proxy call-count stays 0.
- NO FALLBACK: a server pointed at a dead Core port (built without probing Core:
  empty catalog + empty pool) fails closed (credits/match -> 503) and STILL never
  proxies to Python (call-count unchanged).

Also parametrizes build_econ_server's pass URL so the mock upstream can be
injected. host 71 lib + 4 integration + differential + concurrency + failure +
24 host_test all green; clippy -D warnings + fmt clean.
2026-08-13 22:39:45 +00:00
OpenFUT Agent 93a46d4de7 feat(fifa17): cut over FUT economy authority to Rust
The economy authority barrier. `handle_with_ip` now dispatches every
economy-touching route to Rust/Core via `try_handle_economy` BEFORE consulting
`classify()`, so a migrated route can never also reach the Python passthrough
(NEVER BOTH). With economy services wired (production `from_config`) an economy
route ALWAYS returns Some — fail-closed 503 on any Core error — so there is no
Python economy fallback. `userMassInfo` stays a hybrid by design: Python
supplies the non-economy envelope; Rust overlays BOTH the squad and the economy
fields (coins + unopened-pack count from Core), so no stale Python economy value
is visible.

Routing only — no handler/test changes buried here. Routes now Rust-owned:
/user/credits, /store/purchasegroup, /store/transaction, POST+GET /purchased,
PUT /item, item DELETE forms, /match (ut/delete), /auctionhouse, /tradePile,
/trade, ut/delete trade; plus the userMassInfo economy overlay.
2026-08-13 22:39:36 +00:00
OpenFUT Agent 3ba24a0faf test(import): verify durable FIFA17 economy migration
openfut-import-fifa17/tests/durable_import.rs drives the REAL import pipeline
(analyze -> Report dry-run; emit_content; plan_apply -> GenericImportRequest +
deterministic identity mappings + watermark; the staging/preflight/seed/
post-validate gates over a real JsonIdentityStore; openfut_core::services::
import::apply_profile_import in one Core SQLite tx) against a disposable
temp-file Core DB, from a small sanitized in-test fixture (750000 coins, 3
resolvable base players, unopenedPackIds [70,70,101], one squad).

Five ordered steps on one durable target, all green:
  A dry-run: report exposes persona/coins/inventory/unopened/fingerprint; ZERO
    DB mutation (all Core tables COUNT=0, identity store empty).
  B apply: coins=750000 exact, owned=3, packs=3 (opened=0), squad_players=2,
    deterministic owned ids, import_fingerprint recorded, identities reverse-
    resolve both ways, watermark=100000600.
  C restart: close+reopen the SAME sqlite file -> identical state.
  D re-apply same source -> AlreadyImported (fingerprint), no doubling.
  E conflict (coins 750000->750001 flips the fingerprint for the same game)
    -> apply fails closed ('different source'); DB unchanged.

Fingerprint = FNV-1a-64 hex of the source snapshot, carried into
ProfileImportRequest.source_fingerprint = Core profiles.import_fingerprint, the
per-game rerun-identity key. dev-deps added to openfut-import-fifa17
(openfut-core path, tokio, sqlx). No production/live data.
2026-08-13 22:31:01 +00:00
OpenFUT Agent 6926bb9528 test(fifa17): add Python-oracle economy differential coverage
economy_differential.rs boots the REAL Python oracle (fifa17-recon/tools/
utas_server.py) as an isolated subprocess (env FUT_PROFILE/FUT_ACCOUNT_PATH/
FUT_PORT into a temp dir + loopback port; no production container/port/save;
killed on Drop) AND the real Rust stack (seeded in-process Core + a real Server
with EconomyServices), seeds a semantically-aligned fixture on both, and drives
16 ops through the REAL surfaces (oracle over HTTP; Rust via
Server::try_handle_economy on the off-runtime thread).

Result: 15 PARITY, 1 DIFFERENT-BY-DESIGN.
- PARITY: credits, userMassInfo economy, purchasegroup (pack70/sentinel/clean-v1
  incl. the real SessionStore capability handshake), Store BUY, POST /purchased
  open, GET /purchased reveal (VERIFIED: durable single-profile purchased pile
  on BOTH — the hypothesised per-SID cache does NOT exist, so PARITY not
  DIFFERENT-BY-DESIGN), quick-sell (both forms), move, match WIN (+400 byte
  shape), market list/query/cancel.
- DIFFERENT-BY-DESIGN: market second-buy. First buy debits buyNowPrice + closes
  on both. Rust's MarketStore is a crash-consistent single-debit ledger (second
  buy of a sold listing = no-op, pinned by assertion); the oracle's buyable
  market is a stateless PACK_POOL sample that re-debits on repeat. Compat impact
  NONE (buy-now is one-shot); Rust is a strict correctness improvement.

No Python source changes; no classifier changes. Deterministic (3 runs).
2026-08-13 22:30:47 +00:00
OpenFUT Agent b1643309f6 test(fifa17): prove host economy concurrency and failure rollback
Two real host-dispatch test files (no fakes) driving Server::try_handle_economy
against a live in-process Core over the real blocking client + durable
MarketStore/PileStore + JsonIdentityStore, each racer its own OS thread
(off-runtime pattern).

economy_concurrency.rs — 8 races x 50 iterations:
  A two BUYs (coins for one) -> exactly one 200 + one 461, final 0, one debit.
  B duplicate owned-pack open -> one redemption, +11 once, entitlement once.
  C duplicate quick-sell -> one sell + one credit + one removal.
  D two market buyers -> one win, one debit, one mint, sold once.
  E reward+BUY -> no lost update (Core relative UPDATE under BEGIN IMMEDIATE).
  F move+quick-sell / G list+quick-sell -> one coherent transition.
  H 1000 concurrent mints -> unique + reversible wire ids, monotonic watermark.

economy_failure.rs — 10 fault-injection sub-cases, all fail-closed:
  BUY/open-redeem/generator/pile/identity, quick-sell, move, market
  reserve/purchase/complete. CRITICAL complete-sale-after-commit = SAFE: the
  listing is left `reserved` (not active), so the active->reserved reserve CAS
  can never win again -> not buyable, exactly one debit + one mint. No E3.

Fault injection uses test-file CoreEconomy/ExternalIdentityStore doubles plus a
NARROW, inert-by-default `StoreFault` seam in market_store.rs + pile_store.rs
(the concrete stores have no trait boundary; 3 `tripped()` checks + a field,
zero behaviour unless a test arms it). `parking_lot` promoted to a normal dep
(the seam's Mutex is used at lib scope). Classifier/ROUTE_AUTHORITY/Python
untouched. host lib 71/71; both new tests pass.
2026-08-13 22:30:35 +00:00
OpenFUT Agent 43917a0051 feat(fifa17): attach economy services in Server::from_config
Wire the PRODUCTION constructor so the economy authority is not test-only.
Server::from_config now builds one process-lifetime AsyncBridge, opens the
durable MarketStore + PileStore (paths from config), shares one HttpCoreClient
as both CoreAccess and CoreEconomy, builds the content pool from Core, and
attaches EconomyServices via with_economy. Stores/bridge are host-lifetime, never
per request.

- config.rs: required OPENFUT_MARKET_DB / OPENFUT_PILE_DB (durable file paths;
  must survive host restart — no temp defaults).
- Fail-closed startup: a bridge/store that cannot initialize returns Err from
  from_config (host refuses to start) — NEVER a silent omission or a Python
  economy fallback.

Test: from_config_constructs_and_serves_economy — builds the Server via the REAL
from_config (disposable config: temp market/pile/identity + a catalog file
derived from seeded content + the real tables dir) against a live Core, drives
credits / purchasegroup / Store BUY / market list-query-buy through it, then
rebuilds from the SAME config after a Core restart and asserts the balance
persisted. host 71 lib + 3 integration + 24 host_test green; clippy/fmt clean.
2026-08-13 21:59:29 +00:00
OpenFUT Agent 1fac71e3ef docs(route-authority): market resourceId mapping + reveal contract landed
Records fe72f0d (resourceId->Core card_id reverse mapping; listings carry both
identities; full Core+store restart E2E) and 747cc23 (GET /purchased reveal =
durable purchased pile, idempotent). Both pre-barrier correctness gaps closed.
Remaining: Python differential, host concurrency matrix, failure injection,
importer, from_config attachment, then the classifier barrier + reachability.
2026-08-13 21:51:52 +00:00
OpenFUT Agent 747cc234c1 fix(fifa17): preserve owned-pack reveal state for GET /purchased
Closes the reveal contract gap: POST /purchased opens a pack and returns
metadata; the client then polls GET /purchased for the opened items. Store BUY
returns items inline, but owned reward-pack (e.g. pack 70) opens had no reveal
read path, so a real FIFA session would show nothing after opening.

Faithful to the Python oracle (fut_store.last_pack / purchased pile): the reveal
is the set of owned items currently in the FIFA "purchased" pile — durable,
idempotent on repeat GET, cleared per-item when a card is moved to the club, and
appended-to by each open. Not a replay cache; presentation state derived from
the durable pile store + Core inventory.

- pile_store.rs: `list_by_pile(pile) -> Vec<core_item_id>` (reveal membership).
- economy_store.rs: `PurchasedPileSink` trait + optional `StoreDeps.purchased`;
  handle_store_buy/handle_pack_open record each minted item into the "purchased"
  pile. `shape_purchased_reveal` (pure): filter Core inventory to the purchased
  pile, shape with the SAME `shape_club_response` /club uses. Grants nothing,
  consumes no entitlement, allocates no id, moves no coins.
- lib.rs: EconomyRoute::PackReveal + classify_economy (GET purchased);
  BridgedPurchasedSink (records via the runtime bridge from the sync dispatch
  thread); dispatch reads the pile async + Core inventory sync + pure-shapes.

Scoping: single fifa17 profile/club (like the Python oracle), so all sessions
share one purchased pile — DIFFERENT-BY-DESIGN vs a per-SID cache, matching the
oracle's single-profile model.

Tests: pile_store::list_by_pile_filters_and_reflects_moves; and the dispatch E2E
now opens pack 70 (entitlement seeded via the Core economy API) and asserts GET
/purchased reveals the opened items and is idempotent on repeat. host 71 lib +
2 integration + 24 host_test green; clippy -D warnings + fmt clean.
2026-08-13 21:51:12 +00:00
OpenFUT Agent fe72f0def2 fix(fifa17): map market resource ids to authoritative Core card ids
Closes the market correctness gap: handle_market_list recorded listing.card_id
from the raw FIFA wire resourceId, so a synthetic buy minted a card_id Core
could not resolve — it survived the immediate response but Core's content
preflight rejected it on reboot.

- catalog.rs: keep the by_resource reverse index (was built then discarded) and
  expose `card_id_for_resource(resource_id) -> Option<&str>` — exact reverse of
  the card_id->asset catalog, no heuristics, unknown => None.
- lib.rs: `impl MarketCardResolver for Fifa17IdentityResolver` delegates to the
  same catalog /club shaping uses; Core never sees a FIFA resource id.
- market_store.rs: listings now carry BOTH `card_id` (authoritative Core content,
  what a buy MINTS) and `wire_resource_id` (the FIFA wire id, echoed in the
  auction record). New column; create_listing takes both; row/Listing updated.
- market.rs: `MarketCardResolver` trait; handle_market_list resolves resourceId
  -> Core card_id and fails closed (persists nothing) on an unmappable resource;
  auction_record emits `resourceId` from wire_resource_id. Dispatch passes the
  resolver.

Tests: list_unknown_resource_fails_closed_no_listing (B),
list_persists_core_card_and_wire_resource_across_reopen (C), catalog reverse
lookup; and the dispatch E2E now RESTORES the full Core+store restart
(economy_full_sequence_through_dispatch_and_restart) — the synthetic buy mints a
real reverse-mapped card_id, so Core's content preflight passes on reboot (A+D).
market 23 lib + catalog 15 + 2 integration green; clippy -D warnings + fmt clean.
2026-08-13 21:43:48 +00:00
OpenFUT Agent 884ecbba64 docs(route-authority): async bridge + dispatch wiring + real E2E landed (580d80a)
Records the AsyncBridge + classify_economy + try_handle_economy dispatch
(unrouted) and the economy_full_sequence_through_dispatch E2E, the
reqwest-blocking-in-async fix (off_runtime), and narrows Remaining to: Python
differential, host concurrency matrix, failure injection, importer, then the
from_config attachment + classifier barrier + reachability proofs. Flags the
two market-handler gaps (resourceId->card_id mapping; GET /purchased reveal
cache).
2026-08-13 21:30:56 +00:00
OpenFUT Agent 580d80a86e feat(fifa17): wire async economy handlers into the host via a runtime bridge (unrouted)
Bridges the synchronous thread-per-connection host to the async
transfer-market/pile handlers WITHOUT flipping the classifier. classify()
is untouched; production still proxies every economy route to Python. The
new dispatch is exercised only by the integration harness via
Server::try_handle_economy — handler wiring, not authority cutover.

async_bridge.rs: AsyncBridge owns ONE process-lifetime multi-threaded Tokio
runtime, shared by every connection via Arc. block_on() runs a future from
the sync dispatch thread; if invoked from within an ambient runtime it
offloads onto its own runtime + a std channel instead of panicking
("cannot start a runtime from within a runtime"). 4 unit tests incl. the
nested-runtime-safety case and concurrent multi-thread drivers.

lib.rs: EconomyRoute + classify_economy (mirrors the Python route table:
credits, purchasegroup, store/transaction, purchased, item DELETE/PUT,
ut/delete match/item/trade, auctionhouse/transfermarket, tradePile, trade).
EconomyServices (Core econ transport + durable MarketStore/PileStore + the
bridge + the pack-content pool), attached via Server::with_economy (kept out
of `new`/`from_config` so existing tests build a DB-less Server; production
from_config attachment is the barrier step). Server::try_handle_economy
dispatches: sync handlers (credits/purchasegroup/store-buy/pack-open/
quick-sell/match) inline; async handlers (market list/query/buy/cancel,
move) on the bridge via owned `async move` blocks. build_content_pool
derives the resolvable FIFA∩Core candidate pool from Core content.

market.rs: FIX the load-bearing hazard the FakeEconomy tests missed — the
async market handlers call the BLOCKING reqwest Core client, which panics
(reqwest::blocking::wait::enter) when run while a Tokio runtime is entered.
off_runtime() hops each Core call to a fresh OS thread with no runtime
entered, so blocking is legal. handle_move_items resolver gains `+ Sync`
(future must be Send for the bridge).

tests/economy_integration.rs: economy_full_sequence_through_dispatch drives
the WHOLE cluster through the REAL Server dispatch + bridge against a live
in-process Core (seeded with fifa17 dev content: 100k coins + owned cards),
on a plain OS thread (direct bridge path), over the real blocking
HttpCoreClient — no fakes: Store BUY (pool draw + shape + debit 400 + mint 5),
credits, quick-sell (reverse-resolve + credit), match WIN (+400), market
list->query->buy->query(sold)->second-buy-fails(no double debit), cancel
(cancelled not buyable), move-items, then reopen the durable market/pile
stores from disk (sold + pile persist). Deterministic. start_core_seeded
loads fifa17 dev content so /collection renders real definitions.

Tests: host 68 lib (+4 bridge) + 2 economy_integration + 24 host_test, all
green; adapter unchanged-green; clippy -D warnings + fmt clean.
2026-08-13 21:30:10 +00:00
OpenFUT Agent 0e2ca5a7c3 docs(route-authority): record landed Store/Market/pack handlers (unrouted)
Update cutover progress: Store BUY/pack-open/quick-sell, market
list/query/cancel/buy + move-items, durable listing/pile stores, and the
pack-content generator are implemented + tested (4d2b8b9) but NOT routed.
Remaining before the single classifier barrier: sync<->async Server wiring +
classify() routes, host<->Core writer E2E, Python differential, host
concurrency matrix, importer restart/idempotency, then the barrier + no-fallback
proofs.
2026-08-13 20:48:39 +00:00
OpenFUT Agent 4d2b8b9be3 economy(fifa17): land Store + Market writer handlers + pack generator (unrouted)
Implements the FIFA17 economy WRITER cluster on top of the landed Core
economy authority + host CoreEconomy client + identity/item-shaper infra.
Handlers are pub, unit-tested, and NOT yet routed: classify() and
ROUTE_AUTHORITY are untouched — the classifier barrier is a later single
coherent flip. No stubs; real Core-backed behavior; fail-closed on CoreError.

Pack generator (adapter fut/pack_content.rs):
  generate_pack_contents(&PackDef, &mut impl Rng, &[GeneratedCandidate])
  -> Vec<GeneratedCard>. Pure, seeded (deterministic), gold-tier split +
  special_chance gate as documented OPENFUT PLACEHOLDER policy (Python
  open_pack/_pack_body parity note inline). Fail-closed empty on empty pool.

Store/item writers (host economy_store.rs), matching oracle wire shapes:
  - handle_store_buy   PUT /store/transaction -> purchase_items (debit+mint N)
    -> createPackResponse; cancel/unknown/owned_only -> 200 {}; insufficient
    -> 461 {reason,credits}; CoreError -> 503.
  - handle_pack_open   POST /purchased -> owned_only consumes the unopened
    entitlement (redeem_entitlement, consume-once); normal packs debit+mint.
  - handle_quick_sell{_path,_body}  DELETE .../item/<id> + POST /ut/delete/.../item
    -> reverse-resolve wire->Core id (SquadWireResolver) -> sell_item ->
    {items:[{id}],totalCredits}; not-owned skipped.
  Production OwnedItemLookup = CoreItemLookup over CoreAccess.

Market (host market_store.rs / pile_store.rs / market.rs), synthetic-seller:
  - MarketStore over sqlx SQLite (WAL-once + busy_timeout=5s + BEGIN IMMEDIATE
    for writes, mirroring openfut-core::db). listings(active/reserved/sold/
    cancelled), owner-checked cancel, CAS reserve/complete_sale/rollback.
    Typed errors NotFound/Sold/Cancelled/WrongOwner/Conflict.
  - PileStore: durable pile/location metadata keyed by Core item id.
  - handle_market_{list,query,cancel,buy} + handle_move_items. Buy-now =
    reserve (CAS) -> balance precheck (461) -> Core purchase_item (mint+debit)
    -> complete_sale; any Core failure rolls the reservation back active.
    Two concurrent buyers -> exactly one sale + one debit.

Deps (additive): rand 0.8 (adapter+host), sqlx 0.7 sqlite/runtime-tokio (host).
Tests: adapter +7 (pack_content), host +43 (economy_store 20, market/store 23
incl two_reservers_exactly_one_wins, two_buyers_exactly_one_sale_one_debit,
state_survives_reopen, move_persists_across_reopen). All green; clippy
-D warnings clean; rustfmt clean.
2026-08-13 20:47:57 +00:00
OpenFUT Agent 0b31abe1d1 test(fifa17): run economy harness on a real multi-connection Core pool
The fresh-DB write-lock race is fixed (core fbb54ea: BEGIN IMMEDIATE writes),
so the E2E+restart harness now uses max_connections=5; 10/10 deterministic.
2026-08-13 20:20:58 +00:00
OpenFUT Agent 6b652cb0a2 chore(core): BEGIN IMMEDIATE write transactions (75b1830 -> fbb54ea) 2026-08-13 20:20:21 +00:00
OpenFUT Agent 3507c5714d feat(fifa17): add purchase_items to host CoreEconomy client
Complete the transport contract: purchase_items (atomic debit + mint N) on the
CoreEconomy trait + HttpCoreClient (POST /economy/purchase-items) + FakeEconomy.
This is the open-on-buy primitive the Store BUY handler will use (createPackResponse
returns the minted itemList). Fail-closed like the rest of the client.
2026-08-13 20:06:54 +00:00
OpenFUT Agent 4f78b9a875 test(fifa17): keep economy harness serialized; document multi-conn blocker
WAL-establish-once + busy_timeout (core 75b1830) reduced but did not eliminate a
brand-new-DB multi-connection warm-up 'database error'; the E2E+restart harness
stays on a single serialized connection for determinism, and the residual
multi-connection concurrency issue is documented as the remaining Part-T blocker.
2026-08-13 20:05:34 +00:00
OpenFUT Agent f3aebafcc7 chore(core): serialize WAL establishment (75b1830) 2026-08-13 20:03:40 +00:00
OpenFUT Agent 1df0bc4f00 test(fifa17): make economy integration harness deterministic
Serialize Core access with a single pooled connection (the harness drives Core
sequentially via the blocking client) to avoid a WAL-mode-establishment race
across connections warming up on a brand-new DB file, and raise the readiness
ceiling for heavy parallel test-binary load. 10/10 deterministic. (Fixed
alongside a real Core robustness fix: per-connection pragmas + busy_timeout,
core 0360135.)
2026-08-13 19:57:53 +00:00
OpenFUT Agent 7d5d0cff06 chore(core): sqlite busy_timeout + per-connection pragmas (bcc4f51 -> 0360135) 2026-08-13 19:55:13 +00:00
OpenFUT Agent 8d752cb0e4 test(fifa17): real host<->Core economy integration harness
Spawn Core (axum) on an ephemeral loopback port backed by a disposable temp-file
SQLite, seed a fifa17 profile via the real Core HTTP API, then drive the HOST's
REAL transport (HttpCoreClient: CoreEconomy) + handlers against it — no fakes:
credits reads Core balance; match-reward writer credits via Core grant_reward;
purchasegroup full-gen renders the owned pack from a Core entitlement (no
sentinel); userMassInfo overlay derives coins from the same Core state
(credits==massinfo==Core invariant). Restart phase reboots Core from the same
on-disk DB and proves coins + entitlements persist. Temp dir + 127.0.0.1:0 only;
no prod DB/ports/containers/.105. dev-deps: openfut-core, tokio, axum.
2026-08-13 19:50:42 +00:00
OpenFUT Agent 96e80ab293 feat(import-fifa17): seed unopenedPackIds as Core entitlements
Carry unopenedPackIds through the importer: Profile model -> Report ->
ApplyPlan. GenericImportRequest now emits entitlements[] (one definition_id
per unopened pack instance, order+duplicates preserved), which Core's import
seeds as unconsumed packs rows in the same transaction. Closes the economy
import gap so a migrated profile's unopened packs become Core entitlements
(feeding purchasegroup/credits/userMassInfo). Idempotency unchanged (import
fingerprint). +1 test; 26 pass, clippy -D warnings clean.
2026-08-13 19:38:04 +00:00
OpenFUT Agent 49c5185ae3 docs(utas-host): update economy cutover progress (readers + match writer landed)
Core API + purchase_items + entitlement import + host reader handlers
(credits/purchasegroup/userMassInfo) + match reward writer landed and tested;
classifier still unflipped (barrier pending BUY/pack-open/quick-sell item shaping,
market listing state, differential/concurrency/restart).
2026-08-13 19:32:45 +00:00
OpenFUT Agent 181bd94341 feat(fifa17): Rust purchasegroup, userMassInfo economy, match reward handlers
All Core-backed, fail-closed (503, never Python), NOT yet classifier-routed
(coherent barrier pending full cluster + Core seed):
- handle_purchasegroup: full Rust body from Core entitlements + StoreMode via
  the oracle-fixture-tested build_purchasegroup (no Python body dependency).
- overlay_massinfo_economy: set userInfo.currencies coins + unopenedPacks
  recoveredPacks from Core, preserving all other fields.
- handle_match_end + build_match_reward_body: derive outcome from endReason,
  credit via Core grant_reward, oracle-shaped destroy_match_body.
Invariant test: credits == userMassInfo == purchasegroup all read one Core state.
7 new host tests (+ FakeEconomy write methods honor fail flag).
2026-08-13 19:31:23 +00:00
OpenFUT Agent 09675a9f7f feat(fifa17): economy policy mappers (match reward, pack price)
Pure FIFA17 policy: match_result_coins/match_reward_total (oracle MATCH_COINS
won 400/draw 200/loss 100 + participation 0), result_from_end_reason (endReason
enum -> outcome, draw default), pack_price (catalogue buy-now, None for
unknown/owned-only). 3 unit tests.
2026-08-13 19:31:23 +00:00
OpenFUT Agent 56c364e4c9 chore(core): purchase_items + entitlement import (d32dc6e -> bcc4f51) 2026-08-13 19:27:06 +00:00
OpenFUT Agent 3021a4e761 docs(utas-host): record economy cutover progress in route-authority gate
Core economy HTTP API + host CoreEconomy client (fail-closed) + credits reader
landed; classifier not yet flipped (coherent barrier pending full cluster + Core
seed).
2026-08-13 19:14:39 +00:00
OpenFUT Agent d240a61157 feat(fifa17): host Core economy client + credits reader vertical
Add CoreEconomy transport (trait + HttpCoreClient impl over Core /economy/*):
balance, entitlements, purchase_entitlement, redeem_entitlement, sell_item,
grant_reward, purchase_item. Fail-closed by contract: any transport/status/parse
error surfaces a controlled error and NEVER falls back to Python (a fallback
would be a second writer).

Add the credits reader vertical: build_credits_body (byte-shape-identical to the
Python oracle: credits + currencies[].funds/finalFunds + optional
unopenedPacks.recoveredPacks) and handle_credits (coins = Core balance,
recoveredPacks = Core entitlement count; 503 fail-closed on Core error). Not yet
classifier-routed: the coins cluster flips as one coherent barrier once every
writer+reader moves together and Core is seeded. FakeEconomy double + 3 tests
(oracle shape, Core-backed read, fail-closed).
2026-08-13 19:14:13 +00:00
OpenFUT Agent d7c5307045 chore(core): expose economy HTTP API (c8269d0 -> d32dc6e)
Advance openfut-core gitlink to d32dc6e: generic /economy/* HTTP routes over
services::economy, server-side club resolution (game-scoped active profile, no
client-supplied club id), + list_unopened_entitlements reader. This is the
transport the FIFA17 economy cutover binds to. Core matrix 43 lib + 115
integration green; clippy clean; boundary audit clean.
2026-08-13 19:11:04 +00:00
OpenFUT Agent 838d76f95e docs(utas-host): add economy route-authority cutover gate
Machine-auditable ownership table for every FIFA17 UTAS route touching the
economy cluster (coins/inventory/entitlements), plus the writer->Core-primitive
map and the single-writer rule. Grounded in the Python economy writer audit:
4 coin-mutation routes (match reward, pack BUY, quick-sell, market buy-now),
synthetic-seller market (no sale-credit/expiry/fee), dead grant_coins/
grant_unopened_pack, no points writer. This is the deployment gate: no proxied
Python route may touch Core-owned state before R1.
2026-08-13 18:59:46 +00:00
OpenFUT Agent 9791eee67b chore(core): add generic purchase_item economy primitive (ee2caa0 -> c8269d0)
Advance openfut-core gitlink to c8269d0, which adds services::economy::purchase_item
(atomic debit + mint) — the generic Core primitive the FIFA17 synthetic-seller
transfer market needs. Evidence: the Python economy audit proved market buy-now
mints a new item with no real counterparty, so debit+mint (not two-party transfer)
is the correct generic model. Core matrix + clippy green.
2026-08-13 18:58:49 +00:00
OpenFUT Agent 5d119f5555 chore(core): reconcile Core to validated trunk + generic economy
Advance the openfut-core gitlink 3084a46 -> ee2caa0. This does two things:

1. Reconciliation: moves the canonical Core lineage onto the committed,
   validated migration trunk (66c88fb: game-scoped opaque extension,
   inventory service, squad-ext routes, content-pack loader, generic
   transactional profile-import service). The divergent local Core refactor
   that was dirtying the eab522a checkout is preserved verbatim on branch
   wip/core-local-development (f70cf44) for separate reconciliation; nothing
   is lost.

2. Economy foundation: ee2caa0 adds services::economy, a generic atomic
   profile-economy authority (currency/inventory/entitlements over the
   existing durable tables, single-transaction compound ops, fail-closed).
   The FIFA17 adapter economy engine sits on top of these primitives.

Core builds green; full matrix 41 lib + 111 integration + 16 = all pass;
clippy clean.
2026-08-13 18:45:21 +00:00
funman300 46e5f612c8 feat(fifa17): add authoritative economy engine + fut_profile importer
Adds openfut-adapter-fifa17 fut::economy — the single-writer FIFA 17 economy engine
the eventual cluster cutover needs: coins + unopened-pack entitlements + owned
inventory + stable item ids, with all-or-nothing transactional mutations faithfully
ported from the Python oracle's fut_store.Store primitives.

Atomic ops: debit (fail-closed), credit, grant_pack/consume_pack (consume-once),
allocate_item_id (unique/monotonic), add_item, and composed transactions buy_pack,
open_pack, quick_sell, market_buy_now, grant_reward. Fail-closed everywhere; the
65534 sentinel can never be bought/granted/opened (defense at the grant primitive,
mirroring grant_unopened_pack rejecting non-catalogue ids). from_fut_profile importer
round-trips coins/unopenedPackIds/items/nextItemId and floors nextItemId past the
highest existing id so re-import cannot mint a duplicate. 10 unit tests (atomicity,
sentinel safety, consume-once, quick-sell, item-id uniqueness, import round-trip).

NOT wired (R3): the live coin balance is one indivisible writer set spanning Store
BUY, pack-open, quick-sell, match rewards AND the transfer market, all in
fut_profile.json; and the generic home (OpenFUT Core) is a preserved-dirty/frozen
submodule. So a safe single-writer cutover cannot be wired yet — this engine +
importer is the coherent prerequisite. No dual-write introduced. No deployment.
2026-08-13 18:26:09 +00:00
funman300 41494bd18f feat(fifa17): port Store pack catalog + purchasegroup wire model (oracle parity)
Adds openfut-adapter-fifa17 fut::store_catalog — a pure, faithful Rust port of the
Python oracle's PACK_CATALOG + _pack_body + store_catalog assembly at production
flag defaults (FUT_STORE_DISPLAYGROUP=1, GROUPID=0, PRICE_PROBE=0):

- PackDef + PACK_CATALOG (ids 1/5/6/7/70; economy numbers are OpenFUT PLACEHOLDER,
  wire shape is oracle-verified; 65534 deliberately absent).
- pack_body() (_pack_body port), sentinel_body() (id-65534 compatibility shim),
  build_purchasegroup(unopened_ids, StoreMode) mirroring store_catalog(3627).
- Differential parity: fixtures generated from the Python oracle
  (tests/fixtures/purchasegroup_{zero_sentinel,zero_clean,pack70}.json); Rust output
  matches semantically (6 tests). Adapter 140 tests, host 24, fmt/clippy clean,
  Python A-R oracle green.

PURE wire shaping — NOT wired into the live host. Serving purchasegroup from Rust
requires an authoritative Rust owner of unopenedPackIds, which is blocked on the
economy-authority prerequisite (R3): coins are one shared balance written by many
Python-oracle routes (BUY spend, quick-sell credit, SBC/match/objective rewards)
persisted to fut_profile.json, so no single coin-touching route can move without a
whole-cluster migration. No dual-write introduced; no production deployment.
2026-08-13 18:16:47 +00:00
funman300 40ebf7c1e7 feat(fifa17): own UTAS auth/capability/purchasegroup session vertical in Rust
openfut-utas-host now classifies and owns three routes, wiring the landed
adapter store_session state machine while keeping the Store economy Python's:

- POST /ut/auth: proxy to Python (which mints X-UT-SID, adopts persona, refreshes
  save), OBSERVE the returned sid, and open a Rust session bound to peer IP +
  configured persona. Account/economy authority stays Python.
- POST /openfut/fifa17/capability: Rust-owned, no proxy — validate + register into
  SessionStore (bound/pending/ignored-late); fail-closed 400 on unsupported.
- GET .../store/purchasegroup: proxy to Python for the authoritative economy body,
  then overlay ONLY the empty-My-Packs topology from the frozen session mode —
  strip the 65534 sentinel for a verified clean-v1 SID, keep it otherwise. Rust
  never writes economy state.

Session state (Arc<Mutex<SessionStore>> + monotonic clock) lives on Server; new()
and from_config() initialise it (signatures unchanged). handle() gains a peer-IP
variant (handle_with_ip) threaded from handle_conn. Strict never-both routing is
preserved. Pure helpers (observe_sid, parse_capability_request, overlay_empty_mypacks)
+ classifier are unit-tested; adapter+host tests + Python A-R oracle all pass.

STOP-GATE: Store BUY / coins / unopenedPackIds NOT migrated — Rust has no
authoritative FIFA17 economy-mutation path (Python fut_profile.json is the source;
Core's economy is separate/unwired), so moving BUY would split store authority.
That cluster migration is the remaining R2 gap. No production deployment.
2026-08-13 17:38:59 +00:00
funman300 c7609252d2 feat(fifa17): add Rust FUT session/capability state machine (empty My Packs)
Ports the novel per-session empty-My-Packs capability negotiation — proven live
on staging and currently Python-only (fifa17-recon/tools/utas_server.py) — into
the production Rust FIFA17 adapter as a pure, dependency-free state machine
(openfut-adapter-fifa17 fut::store_session).

It owns: per-login X-UT-SID session table, single-use (ip,persona) launcher
capability hand-off (pending), capability binding (bound/pending/ignored-late),
the once-per-session clean-v1 vs sentinel freeze, TTL reaping, and fail-closed
rules (unknown/expired/ambiguous/late/cross-session/sid-ip-mismatch -> sentinel).
The clock and SID entropy are injected so it is fully unit-testable.

The full Python capability-negotiation matrix A-R is ported as Rust unit tests
(21 pass). Python remains the behavioural oracle. The delicate _pack_body UTAS
wire shaping, /ut/auth persona-adoption, /store/purchasegroup catalogue assembly
and the store BUY path are deliberately NOT ported here (documented gap); wiring
the three routes into openfut-utas-host without splitting store authority is the
remaining bounded slice toward full Rust authority. No production deployment.
2026-08-13 16:52:13 +00:00
funman300 4cf388dd3b chore: reconcile openfut-launcher submodule
Point the launcher gitlink at the reconciled merge ca7ce26
(integration/fifa17-launcher-capability-sbc), which retains BOTH launcher lineages:
  - 13339c1  FIFA 17 verified patched-client capability reporting
  - 958ff245 openfut-hook SBC request tracing / RE instrumentation

The previously-uncommitted openfut-hook WIP that blocked this move is preserved on the
submodule branch wip/openfut-hook-local (commit 4e44a37) + /tmp/openfut-hook-wip-preserved.patch
(sha256 8e65de2c…) + the untracked server.rs copy. Gitlink-only change; no other superproject
dirt staged. Backend/production unchanged.
2026-08-13 15:11:18 +00:00
funman300 00d85aa6e4 docs(fifa17): finalize capability deployment candidate
Record the overnight launcher-lineage reconciliation (merge ca7ce26 retaining both
feat/launcher-arming 13339c1 and feat/sbc-hook-tracing 958ff24; only src/process.rs
conflict, resolved keep-deleted), the deferred superproject gitlink bump (blocked by
uncommitted openfut-hook WIP overlapping the merged hook content), the validated
deployment-candidate commit tuple + local build artifacts, and the controlled A/B/C
deployment sequence. Production stays P2 active-sentinel until the A/B passes.
2026-08-13 05:18:14 +00:00
funman300 d9e80a774a test(fifa17): add explicit per-SID topology-freeze regression
Case R makes the F3 session-topology invariant explicit alongside the A-Q matrix:
for a single X-UT-SID the frozen empty-My-Packs mode never flips in either
direction (Sentinel stays Sentinel even if a capability later appears; Clean stays
Clean even if the capability is wiped), while a fresh SID from the same IP decides
independently. Complements F/G/K.
2026-08-13 05:18:13 +00:00
funman300 a82407c686 docs(fifa17): harden patched-client session binding
Record the per-IP -> per-session correction: why source-IP-only was unsafe (two
FIFA processes share an IP), the authoritative per-login X-UT-SID key with IP and
persona as auxiliary, the Capability/StoreMode state machine, the single-use
short-TTL launcher->session pending hand-off, activity-based session cleanup, and
the documented fail-closed residual for genuinely simultaneous same-(ip,persona)
logins. Design history is retained; the per-IP prototype is marked superseded.
2026-08-13 04:39:53 +00:00
funman300 805d754dc8 fix(fifa17): isolate patched-client capability per session
Harden the empty-My-Packs capability binding so a verified FIFA process can never
enable clean/no-sentinel Store topology for another unverified process that merely
shares its source IP. The prototype keyed the decision by source IP alone; two FIFA
processes (concurrent, or a relaunch) share an IP, so an unpatched process could
inherit a patched one's clean-v1 mode and crash. Source IP is now auxiliary only.

- Authoritative key = the per-login UTAS session id (X-UT-SID). /ut/auth now mints
  a fresh unique SID per login (was a shared constant) and opens a session record
  keyed by that SID; the client echoes it on every later call incl.
  /store/purchasegroup (live-confirmed). The legacy constant is still accepted by
  the retired security-question gate only, never to grant clean-v1.
- Session state: _FIFA17_SESSIONS[sid] = {ip, persona, resolver, mode, created,
  last_seen}. Store mode freezes at the first /store/purchasegroup of the session
  and is immutable thereafter. Fail-closed: unknown SID, or a SID presented from a
  different source IP than it was opened on, resolves to the sentinel.
- Launcher capability (out-of-band; cannot know the SID) is matched by (ip, persona)
  as a SINGLE-USE, short-TTL pending, bound to exactly one session at whichever comes
  first: its login (pending predates auth), the registration (session already live),
  or its first store request. Ambiguous same-(ip,persona) concurrent registration is
  ignored-late -> both sentinel (never a wrong clean).
- Session cleanup: activity-based TTL sweep (sessions 3600s idle, pendings 120s);
  reaping only removes expired entries and never affects another live session.
- account_sync now clears only stale pending for the machine (pre-launch hygiene);
  it no longer resets a per-IP mode (there is no per-IP mode any more).

Backend-only: the launcher registration payload (already carries personaId) is
unchanged. Additive; P2 sentinel remains the else-branch and the default.

Tests: matrix A-Q incl. same-IP concurrent (K), same-IP+persona relaunch (L),
same-IP failed-patch (M), late-registration-vs-frozen-sessions (N), TTL expiry (O),
duplicate/idempotent registration (P), and register-before-login pending (Q).
2026-08-13 04:39:53 +00:00
funman300 d4c3811665 docs(fifa17): document patched-client store negotiation
Design + cross-component contract for verified patched-client capability
negotiation: architecture inventory, transport choice (autopatch stdout ->
launcher, sibling /openfut/fifa17/capability endpoint), the versioned capability
and its VERIFIED semantics, autopatch verification states, launcher per-process
state, source-IP binding, the session-stable freeze point, the additive store
switch, the trust model (local preservation, not attestation), the fail-closed
matrix, and P2 retention.
2026-08-13 04:03:37 +00:00
funman300 b25761ea31 feat(fifa17): negotiate clean empty My Packs mode
Backend side of the handshake: suppress the synthetic 65534 My-Packs sentinel
ONLY for a session whose client has registered a verified resolver-guard
capability. Additive; the P2 active-sentinel path is retained as the else-branch
and the universal default. Fail-closed everywhere.

- Per-client state keyed by source IP (client_address[0]; the only per-connection
  discriminator in this single-account, stateless backend): _FIFA17_STORE[ip] =
  {resolver, mode}; mode in {None, "sentinel", "clean-v1"}, guarded by a lock.
- New POST /openfut/fifa17/capability endpoint: accepts only
  {"capability":"empty_mypacks_resolver","version":1,...}; unknown capability or
  version => 400 and records nothing (=> sentinel).
- account_sync (the launcher's required per-launch call) resets the per-ip record
  => a new FIFA process starts unfrozen with no inherited capability.
- Store topology is frozen at the FIRST /store/purchasegroup per session:
  clean-v1 iff a v1 capability is registered, else sentinel; immutable thereafter
  (late capability logged + ignored this session; a disappeared capability does
  not un-freeze a clean session). This enforces the SESSION-STABLE invariant.
- store_catalog zero-owned-packs branch: clean-v1 emits NO mypacks group (the
  client guard routes category -1 to Browse); every other case emits the existing
  active 65534 sentinel verbatim. PACK_CATALOG / pack 70 / normal packs / profile
  untouched. FIFA-17 only; not lifted into game-independent Core.
- Tests: full matrix A-J incl. concurrency isolation (two IPs, no global leak) and
  no cross-process capability leak.

Design: docs/plans/FIFA17_PATCHED_CLIENT_CAPABILITY.md.
2026-08-13 04:03:37 +00:00
funman300 1c396dd562 feat(fifa17): report verified client patch capability
autopatch side of the verified patched-client capability handshake: prove, at
runtime, that the empty-My-Packs resolver guard is active for a specific FIFA
process, and advertise it once on stdout for the launcher to relay.

- Add a per-pid guard verification state derived by a pure, testable
  guard_state_after(cur_before, orig, patch, wrote_ok, cur_after) returning one
  of VERIFIED / UNSUPPORTED_BUILD / WRITE_FAILED / VERIFY_FAILED (NOT_ATTEMPTED
  is the pre-evaluation constant). VERIFIED means the live bytes at RVA 0x14858
  are 7f 0f (JG) after enforcement (from an applied 75 0f->7f 0f, or already
  patched). The existing fail-closed byte guard (guarded_action / STORE_PATCHES_
  GUARDED) is unchanged — this only observes the outcome.
- Emit exactly once per FIFA pid: on VERIFIED,
    [store-guard] verified capability fifa17.empty_mypacks_resolver=1 fifa_pid=<pid>
  otherwise a non-advertising
    [store-guard] guard status=<STATE> fifa_pid=<pid> (no capability advertised)
- Capability constants: EMPTY_MYPACKS_RESOLVER_VERSION=1, fully-qualified name
  "fifa17.empty_mypacks_resolver".
- Tests: 5 guard-state cases + capability-constant assertions (standalone-runnable).

The capability = "the guard was verified in THIS FIFA process", never merely
"the code is present". Design: docs/plans/FIFA17_PATCHED_CLIENT_CAPABILITY.md.
2026-08-13 04:03:37 +00:00
funman300 fc29c2eb9b docs(fifa17): record no-sentinel client resolver proof
Land the client-side empty-My-Packs resolver evidence and the session-stability
invariant established by the F3/R1 experiments.

- PART III (F3, CONFOUNDED CRASH): a mid-process sentinel -> no-sentinel flip
  left a stale POSITIVE My-Packs ordinal that still took the resolve branch and
  crashed at 0x180014882. Preserved verbatim (not a guard failure).
- PART IV (R1, SUCCESS): backend set no-sentinel first, then a FRESH FIFA
  process; genuine purchasegroup response ids [1,5,6,7] is byte-identical to the
  F3 capture, so client process lifetime is the only changed variable. Store
  opens on Browse Packs, no crash, no dialog. Guard PROVEN on the tested build.
- New INVARIANT: empty-My-Packs capability MUST be session-stable -- the server
  must not switch a running client between sentinel-present and sentinel-absent
  for the My Packs group within one FIFA process, because the client caches the
  group ordinal and a stale positive ordinal still crashes the resolver.
- Both no-sentinel captures kept: client_guard (F3) and freshretest (R1).

Backend P2 active-sentinel (65534) remains production default; no capability
handshake is implemented yet.
2026-08-13 03:13:40 +00:00
funman300 b0d5e04bb9 fix(fifa17): guard missing store category resolution
Port the PROVEN empty-"My Packs" resolver crash-guard into the canonical
autopatch.py /proc-mem patcher. When no `mypacks` purchase group exists, a
fresh FIFA 17 client resolves category id -1; CardsDLL FUN_1800147f0 at RVA
0x14858 (`JNZ 0x14869`, bytes 75 0f) treats every non-zero category as
resolvable, calls FUN_180014420, gets NULL, and dereferences [NULL+0x48] at
0x180014882 (0xC0000005). Rewriting JNZ->JG (7f 0f) preserves positive-category
resolution (EDI>0) while routing zero/negative categories to the existing
Browse/list-all path -> no NULL lookup, no crash, Store opens on Browse Packs.

- STORE_PATCHES_GUARDED table pins RVA 0x180014858 orig 75 0f -> patch 7f 0f.
- Applied every tick, fail-closed via guarded_action(): apply only when the
  live bytes are the known original; no-op when already patched; SKIP+log an
  unrecognised CardsDLL build (never blindly overwritten).
- Runtime watch loop moved under `if __name__ == "__main__"` so the module
  imports cleanly for unit testing; script behavior is unchanged. Existing
  ProtoSSL cert-gate and STORE_PATCHES enforcement are byte-identical (indent
  only).
- test_autopatch_guard.py: pure test covering PATCH/NOOP/SKIP and pinning the
  exact guarded RVA/bytes.

Proven on the tested build (CardsDLL 4706a881...) by a clean fresh-process
no-sentinel A/B (R1). Dormant while the backend active-sentinel is present.
See docs/plans/FIFA17_EMPTY_MYPACKS_CLIENT_FIX.md PART IV.
2026-08-13 03:13:39 +00:00
funman300 6746c75302 docs(fifa17): RE-backed native client-fix design for empty My Packs
Investigation + design only (no client/backend/binary changes, no live
Store experiment). Reconfirmed CardsDLL_Win64_retail.dll (4706a881..,
unpacked) against a freshly rebuilt Ghidra project on .105; FIFA17.exe
(29c31cef..) is Denuvo-packed so the Scaleform decision is unreadable.

PART II added to docs/plans/FIFA17_EMPTY_MYPACKS_CLIENT_FIX.md:
- Native category path traced: FUN_18007dab0 (store render, RVA 0x7dab0)
  reads screen+0x290; My Packs funnels through FUN_1800147f0 (0x147f0) ->
  FUN_180014420 (0x14420, NULL on ordinal miss) -> crash MOV [RDX+0x8] at
  0x14882 ([NULL+0x48]), matching the Exp-B minidump. Tab->ordinal map
  FUN_180014580 (0=mypacks..5=special); category 0 = list-all (Browse).
- Unopened-pack count is a data-manager singleton (vtbl[0x4d8] get /
  [0x4e0] set), reachable from the store resolver.
- Vehicle: existing openfut-hook -> version.dll proxy (already deployed);
  reuse ssl_patch signature-scan + connect_hook inline detour. No new loader.
- Preferred strategy A: entry-hook FUN_18007dab0; when the requested
  category is My Packs and unopened count==0, force screen+0x290=0 (Browse).
  Removes crash + fake 65534 tile + dialog + nav gate; count>0 untouched.
- Ranked B (resolver NULL fallback, higher risk) and C (null-guard, crash-only).
- Build guard: module gate + SHA/PE + signature scan; unknown build -> no
  patch, backend sentinel remains fallback.
- First experiment design (needs a later, separately-authorized backend
  empty-no-sentinel test mode) + client rollback (config flag / dll swap).
- Keep backend 65534 sentinel deployed until strategy A is verified.

Describes the FIFA 17 client/data model only; not OpenFUT Core assumptions.
2026-08-13 01:48:58 +00:00
funman300 b2697b13dc docs(fifa17): establish verified card taxonomy
Single source of truth for FIFA 17 FUT card families, reconciled against
the authoritative shipped fcc_*.json + staff tables (verified byte-identical
between .105 and this repo, 36/36 sha256).

- docs/CARD_TAXONOMY.md: family -> table/rowcount/subtype/carddbid/cardassetid,
  with OBSERVED/INFERRED/HYPOTHESIS/UNKNOWN labels. Corrects four superseded
  claims (chem styles are 250-273 not 91-136; 6300/6400xxx are kits not badges;
  5004xxx misc and 8010xxx league logos exist). Manager-league precision kept
  distinct: shipped table 300-340 (41 rows) vs client enum 300-341 (341 defined,
  unshipped). Club-item wire subtype->family mapping preserved as UNKNOWN.
- docs/evidence/fifa17-recon/table-hashes.sha256: 36-file provenance manifest
  (31 fcc_*.json + 5 staff tables), combined hash 10f239ad...

Describes the FIFA 17 data/client model only; not OpenFUT Core assumptions.
2026-08-13 01:31:22 +00:00
funman300 e8ee6c34e7 docs(fifa17): record empty My Packs client contract
Full investigation record for bug 6c: baseline + Experiments A/B/C', Candidate F (contradicted), the explicit active-placeholder selection test, the minidump-confirmed CardsDLL crash, and the P2 decision. Marks ROOT CAUSE ESTABLISHED and documents the known UX limitations and the client-side follow-up.

Files: docs/evidence/STORE_TILE_6C.md, docs/evidence/FIFA17_EMPTY_MYPACKS_CLIENT_CONTRACT.md, the four genuine /store/purchasegroup captures (baseline, mypacks70, empty_no_sentinel, active_placeholder), and docs/plans/FIFA17_EMPTY_MYPACKS_CLIENT_FIX.md (client-side design/research).
2026-08-13 01:08:47 +00:00
funman300 f42279f869 fix(fifa17): keep empty My Packs group client-safe
When the account owns zero unopened packs, store_catalog() emits a synthetic `mypacks` group placeholder (id 65534, absent from PACK_CATALOG). Change its state from "inactive" to "active".

Root cause (bug 6c): FIFA 17's Store/Scaleform path resolves the `mypacks` category even with zero unopened packs (category chosen client-side via the movie's CATEGORY_ID -> screen+0x290; no server field gates it). CardsDLL FUN_1800147f0 then dereferences the resolved group with no null guard, so an absent group crashes the client (CardsDLL+0x14882, [NULL+0x48], minidump-confirmed). An inactive placeholder avoids the crash but makes the Store report the pack unavailable on entry and bounce to the Hub; an active placeholder lets the Store open normally.

65534 stays economy-safe: pack_by_id() returns None, so store_buy()/purchased_items() cannot open it or grant items/coins, and grant_unopened_pack() rejects it. Explicit selection is rejected client-side ("This pack is no longer available") and sends no backend request. This is a FIFA-17 client-compatibility shim (P2), not an EA-authentic representation, confined to the FIFA-17 backend (not OpenFUT Core). A clean zero-pack UX needs a client-side fix (docs/plans/FIFA17_EMPTY_MYPACKS_CLIENT_FIX.md).

Adds regression tests (test_empty_mypacks.py): empty -> one active 65534 placeholder (absent from PACK_CATALOG); non-empty [70] -> no placeholder, genuine pack shown; economy safety; normal packs 1/5/6/7 untouched.
2026-08-13 01:08:37 +00:00
funman300 54ad9e8f79 docs(state): Slice 8 — real-data staged retail A/B PASS
Records the operator-assisted live A/B on the REAL imported club (1949/1962, 13
Legends deferred): real club render, clean pagination, Special filter (1665, 0
base leaked), squad edit persistence + cold relaunch, and rollback->Python->Rust
re-enable. Documents the three real-data fidelity fixes (versioned resourceId
e187cd4, rareflag 626c972, rare=SP filter 6f16a23) and the nation/league/team
model correction (44fcf24). Marks PRODUCTION NOT READY pending .105 Legends name
data for the 13 deferred assets. Aggregate counts only; no private identity.
2026-08-12 21:37:42 +00:00
funman300 6f16a231fc fix(fifa17): implement rare=SP 'Special' club filter via rareflag
The club search 'Quality = Special' sends rare=SP, which was a deliberate no-op
('semantics UNKNOWN'), so it returned every card — base golds included. The
rareflag work now grounds it: a special is rareflag > 1 (base rare = 1),
evidence-backed by the FIFA17 taxonomy + the observed profile (base Ronaldo/Messi
rareflag 1; their informs 11/24).

rareflag lives in the FIFA catalog, not Core, so Core cannot filter it:
- map_to_core: rare=SP now sets CoreOwnedQuery.special (host-applied), not
  'unsupported'; any OTHER rare value stays unsupported. special is NEVER a Core
  /collection param. is_special_rareflag(rf)=rf>1 lives in the adapter.
- handle_club special path: fetch all items matching the OTHER filters (offset/
  limit stripped), shape (resolves rareflag), then special_filter_page() keeps
  rareflag>1 and paginates the FILTERED set locally (start/count over specials,
  not Core's unfiltered page) — no base leakage, no post-pagination drops.

Verified live on the real staged club: rare=SP -> 1665 items (=1949-284 base),
rareflag distribution all >1, zero base leaked; pagination page0==full[0:50],
page1==full[50:100], no overlap. Tests: adapter map rare=SP->special, unknown
rare stays unsupported, is_special_rareflag predicate; host special_filter_page
filter+paginate. adapter 113 + host 25 + importer 25 green; clippy -D clean.
2026-08-12 21:25:18 +00:00
funman300 626c972232 fix(fifa17): carry observed rareflag so special cards render as specials
shape_item hardcoded rareflag=1, so all 1949 cards shaped as basic rare gold
regardless of type; informs/specials lost their card art. The dev fixture is
base-only, so this was invisible until the real profile (10 distinct rareflag
values) exposed it on .105.

rareflag is definition-level FIFA identity metadata OBSERVED from the profile
(the raw wire integer, never a guessed marketing label), so it lives in the
FIFA catalog like asset_id/version, not in generic Core:
- ObservedDefinition.rareflag + emitted into the production catalog entry.
- Fifa17CardCatalog RawCard/Fifa17CardIdentity gain rareflag (default 1 when a
  base-only catalog omits it, preserving prior wire behaviour).
- Fifa17Identity.rareflag; host resolver populates it from the catalog.
- shape_item emits id.rareflag instead of a hardcoded 1.

Verified on the real staged /club: wire rareflag distribution == source exactly
(0 per-item mismatches across 1949; e.g. rareflag 3 x591, 24 x302, 21 x256).
adapter 111 + host 24 + importer 25 tests green; clippy -D clean. rareflag lives
in the host catalog, not Core, so no re-import was needed.
2026-08-12 21:13:51 +00:00
funman300 44fcf24d92 fix(import-fifa17): nation/league/team are instance metadata, not definition identity
Evidence (resourceId 169193): its 4 owned copies are IDENTICAL in asset/rating/
position/all attributes and differ ONLY in nation/team/league (and those resolve
inconsistently, e.g. team 240 'Atletico Madrid' under league 16 'Ligue 1'). A
player's club affiliation is an instance-time snapshot, not part of the card
DEFINITION identity.

Correct the model (not a special-case): the definition-consistency gate now
compares a DefIdentity projection (asset_id/version/rating/position/attrs/
rareflag) and EXCLUDES nation/league/team. A club-only difference between copies
of one resourceId is no longer a conflict; a real identity disagreement
(rating/position/attrs/asset) still trips it. The definition's display
nation/league/club use the first-observed copy (deterministic; display-only,
never identity). No --defer-conflict allowlist entry is needed for 169193 now.

On the real profile: conflicts 1->0, 169193 reclassified conflict->NoName
(still deferred, unnameable), supported still 1681, deferred instances still 13,
BLOCKERS none without any --defer-conflict flag. 2 new tests (club-only diff is
not a conflict; rating diff still is). crate suite 25 green; clippy -D clean.
2026-08-12 20:58:33 +00:00
funman300 e187cd49a2 fix(fifa17): preserve versioned resourceId on the wire (no special->base collapse)
shape_item emitted resourceId/definitionId = asset_id (base), collapsing every
versioned (special) card onto its base definition on the /club and squad wire.
The dev 32-card fixture is base-only (version 0), so Slice 7 never exposed it;
the real profile (1531 versioned cards) did.

Fifa17Identity now carries resource_id (= (version<<24)|asset_id, == asset_id
for a base card). shape_item emits resourceId/definitionId from resource_id and
assetId/cardassetid from asset_id — versioned and base stay distinct. The host
resolver populates resource_id from the catalog's reconstructed resource_id
(the catalog already parsed version; it was dropped before shaping).

Regression test: versioned 117617092 (v7 of asset 176580) shapes resourceId/
definitionId=117617092, assetId/cardassetid=176580.

Verified on the real staged /club: 1949 items, wire-id set exact, 0
wire->resourceId mismatches, 0 duplicate-multiplicity mismatches vs the source
manifest. adapter 111 + host 24 tests green; clippy -D warnings clean.
2026-08-12 20:46:48 +00:00
funman300 1631d3b1a2 feat(import-fifa17): --apply — recoverable two-store real-profile import
FIFA17-specific orchestration that installs the real profile across BOTH durable
stores (openfut-identity + Core SQLite) recoverably and idempotently, handing
Core only a GENERIC request (all FIFA17 semantics stay in this adapter layer).

apply module:
- owned_item_id(persona, wire) = deterministic UUIDv5 from a private namespace;
  identical in BOTH stores (identity core_id AND Core owned_cards.id), so the
  running host's wire->owned reverse lookup resolves exactly what Core stored.
- plan_apply(report, raw_profile, fp): pure translation to a GenericImportRequest
  (card_id = fifa17_<resourceId>) + the preserved (owned_item_id <-> source wire)
  mappings + watermark. Canonical squad + Fifa17SquadExtensionV1 are built by the
  SAME adapter code (parse_squad_put + build_squad_write) the retail-validated
  live squad path uses. Refuses if the report has blockers.
- Two-store protocol (apply): staging gate -> local Core-preflight mirror ->
  identity dry-preflight -> idempotent seed (insert_existing_mapping per instance
  + set_watermark) -> ONE generic Core import transaction (spawned binary) ->
  cross-store post-validation -> completion record. A crash after identity
  seeding re-converges on re-run (idempotent mappings + Core already_imported):
  no cleanup, no reminting.
- gate_staging: deferred players are ABSENT from an import; allowed only for a
  staged run behind --allow-deferred-players-for-staging (never a silent default;
  prints an INCOMPLETE banner). Production requires zero deferred instances.

CLI: --apply (with --emit-content, --core-bin, --core-db, --core-data,
--identity-store, --allow-deferred-players-for-staging). Depends on
openfut-adapter-fifa17 + openfut-identity + uuid(v5).

Proven end-to-end on the real 33068179/CAGE profile (staged): first apply
imports 1949 supported instances (293 base + versioned), 11/11 f433 squad +
opaque extension, coins 28,112,944, fingerprint 8dc5582d2414af28; re-run is an
idempotent no-op (already_imported, DB unchanged); staging-not-default refuses
before any write; every OwnedItemId is an opaque UUID; identity wire-id set ==
source supported set exactly (0 minted, 0 dropped); 13 deferred instances leak 0.

10 new apply tests (determinism, request/mapping/squad translation, blocker
refusal, staging gate both ways, local preflight, identity seed/dry/postvalidate/
idempotency, conflict detection, graceful spawn failure). clippy -D warnings
clean; crate suite 23 tests green.
2026-08-12 20:36:34 +00:00
funman300 c71c2a8d33 feat(import): --emit-content (production pack + host catalog + private manifest)
Fold entity resolution (nation/league/club id->name via committed tables,
mirroring seed_fifa17_cards.py) and quality-tier rarity into the analysis, so
the supported set is honest about unresolved entities too. Add an explicit
--defer-conflict <rid> allowlist: a reviewed conflict (169193) defers, any NEW
conflict still hard-fails (defer never becomes a silent conflict suppressor).

--emit-content writes three files, PUBLIC content separated from PRIVATE account
state: fifa17-production-cards.json (Core CardDefinition[] keyed fifa17_<resourceId>,
base+versioned, tier rarity, profile-derived, no promo labels), a versioned host
identity catalog {card_id:{asset_id,version}}, and a private import manifest
(supported instances' wire ids + deferred set with reasons + preserved watermark
+ target profile + snapshot fingerprint). Emit refuses while blockers exist.

Real profile (33068179/CAGE): 1681 supported defs (150 base + 1531 versioned),
9 NoName deferred, 1 approved-deferred conflict (169193, 4 copies), 1949
importable instances, watermark 100004617 -> next 100004617, active squad f433
11/11 supported. fmt + clippy -D warnings clean; 13 tests.
2026-08-12 19:41:17 +00:00
funman300 a51947562c feat(import): identity import API + FIFA17 real-profile dry-run importer
openfut-identity:
- insert_existing_mapping(game,kind,core_id,external_id): preserve an existing
  external wire id instead of minting; idempotent for an identical mapping,
  rejects conflicting forward/reverse with IdError::Conflict, persists atomically.
- persisted per-scope allocator watermark (set_watermark/watermark_for) so a
  future mint continues past the source high-water even across burned-id gaps;
  next id = max(base_floor, live_max+1, watermark). Backward-compatible on-disk
  format (legacy bare [Row] still loads). +4 tests (10 total).

openfut-import-fifa17 (new): read-only dry-run analysis of a real FIFA17 Python
profile for a faithful Core import. Enforces disjoint item-class balance;
proposes profile-derived CardDefinitions keyed fifa17_<resourceId> (base vs
versioned never collapse) with a resourceId-group consistency gate (hard-fail on
disagreement, never pick a winner) and honest buildability (roster name +
version formula + metadata, never fabricated); plans owned-instance identity
(preserve Python wire ids, preserve nextItemId watermark); checks active-squad
coverage. --apply/--emit-content refuse to write in this phase. 11 tests.

Real profile (33068179/CAGE) dry-run: 1982 items balance (1962 players + 17
consumables + 3 staff); 1681 supported defs (155 base + 1535 versioned), 9
NoName unsupported, 1 hard conflict (resourceId 169193: one of 4 copies has a
divergent nation/team/league); 1949 importable player instances, watermark
100004617 -> first new alloc 100004617; active squad f433 fully supported.
fmt + clippy -D warnings clean.
2026-08-12 19:23:19 +00:00
funman300 63f02c4fb1 docs(state): Slice 7 — FUT squad read+write retail-validated on FIFA 17
Record the staged retail A/B: FIFA consumed the Rust squad path end-to-end
(userMassInfo overlay, in-game swap -> squad-replace {"id":0}, formation
f442->f433 persisted to Core, cold relaunch returned the persisted squad),
with Python rollback / Rust re-enable proven by host-log presence. Note the
OPENFUT_DEV_CONTENT_GAMES=fifa17 startup requirement (silent empty /collection
if omitted) as a needed deployment/preflight assertion.
2026-08-12 18:41:24 +00:00
funman300 4fd5ee2608 redirector: a port probe must not forge the signature of a TLS fault
"TLS HANDSHAKE FAILED: ... unexpected EOF" is exactly how the certificate
mismatch presented -- the defect that cost three live gate attempts and was
invisible everywhere else. It is the one line this project has learned to
treat as serious.

A reachability probe forges it for free: TcpStream::connect followed by a
drop opens the connection and closes without sending a byte, and the
acceptor reports that as "unexpected EOF". The launcher's preflight makes
two such probes per run. On 2026-08-12 they produced ten of these lines and
sent a whole session diagnosing a client-side fault that did not exist --
autopatch, ptrace_scope and client_arm.sh were all investigated before the
pairing of the timestamps gave it away.

Classify before the acceptor sees the connection: peek one byte, and treat
EOF-before-any-byte as a probe with its own quiet line. A timeout is
deliberately NOT a probe -- a slow or broken client must still reach the
acceptor and produce a real diagnostic, since misclassifying a fault as
benign would defeat the point.

The counter exists because the test needs it. A probe produces no response
either way, so a test written against client-visible behaviour passes with
the classification deleted; asserting on a count is what makes the mutation
detectable. Verified: all three mutations (drop the classification, treat
undetermined as a probe, treat a speaking client as a probe) are killed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-12 17:25:21 +00:00
funman300 c7d4b9f753 style(adapter): rustfmt catalog test assertions
Trailing rustfmt reflow of two catalog unit-test assertions (no logic change); clears the adapter dirty state so verify-build-identity.sh passes for the UTAS A/B.
2026-08-12 17:15:14 +00:00
funman300 37c2e5d7ee feat(utas-host): serve GET /squad/active from Core
Migrate the active-squad READ off the Python oracle to the existing Core-backed projector, completing the squad authority (read + write + /squad/list + userMassInfo overlay) on one projector.

- classify: GET /ut/game/<t>/squad/active -> Route::SquadActive. Numeric GET /squad/<n> stays on Python (no Core multi-squad model yet).
- handle_squad_active returns the projector object via user_mass_info_squad(v, persona) — byte-identical to userMassInfo.squad; degrades to an empty overlay on stale/missing/Core-error, never falls back to Python.
- persona: new REQUIRED OPENFUT_PERSONA_ID (non-zero) on HostConfig, injected not baked, must match LSX/Blaze/POW/UTAS identity.
- tests: squad_active parity test; classify updated; README config table + A/B command.

fmt + clippy -D warnings + tests (24 host + adapter) green.
2026-08-12 17:10:04 +00:00
funman300 7dbd878398 test: update mutation-battery anchors after rustfmt reflow
Formatting reflowed two mutation target lines onto multiple lines; update
the battery anchors (adapter #14 kit lookup, host #19 Content-Length push)
to the new unique substrings. Both batteries kill all mutants again
(adapter 14/14, host 20/20).
2026-08-12 04:01:37 +00:00
funman300 c2e2e0d8f2 style: rustfmt squad host + adapter files
Formatting-only. Runs the project formatter over the files authored/edited
this session (host lib+tests, adapter item/squad_ext/squad_projection/mod +
projection test). The intentionally-preserved dirty catalog.rs and
pre-existing /club-era host drift beyond these files are out of scope.
2026-08-12 03:59:15 +00:00
funman300 afc909fd3b fix(fixtures): sanitize lab subnet from committed UTAS captures
The capture sanitizer redacted tokens/device ids but left the lab Host
address (10.10.0.x) in three committed UTAS fixtures, tripping
scripts/check-no-lab-addresses.sh. Replace with an RFC 5737 TEST-NET
address (192.0.2.120) per the guard's own doctrine. Host header is
plaintext metadata only (tests decode body_b64), so no test is affected.
Pre-existing leak (fixtures committed at 0b66662/eb8311a); no lab address
was introduced this session.
2026-08-12 03:59:15 +00:00
funman300 b607ff28cb chore: bump openfut-core gitlink to rustfmt'd squad-ext routes (3084a46) 2026-08-12 03:58:51 +00:00
funman300 cf86d4e425 test(utas-host): squad host mutation battery (20 mutants, all killed)
mutation-battery.sh injects each of the 20 required wrong behaviours into
the committed host (or the adapter it composes) source, runs the one host
test that must catch it, and requires a non-zero exit (killed), reverting
via git after each. Adds a duplicate-definition host round-trip test.

Kills: authz-skipped, authz-loop-empty, failure-masked-as-success,
PUT-as-partial-diff, extension-dropped, stale-accepted, missing-fabricated,
overlay-clobbers-{userInfo,settings,pile}, list-separate-shaping,
captain-as-resourceId, kit-by-slot, client-eval-dropped, host-trusts-fp,
per-slot-N+1, squad/active-to-Rust, duplicate-collapse, stale-content-length,
python-squad-after-failure. 20/20 killed.
2026-08-12 03:11:25 +00:00
funman300 85761390a8 feat(utas-host): FIFA17 squad authority — PUT, /squad/list, userMassInfo overlay
Extend the UTAS migration host to own the squad slice, reusing the exact
production identity path (Fifa17CardCatalog + ExternalIdentityStore) that
/club uses, so /club, /squad/list, userMassInfo and PUT all agree on
wire<->owned identity.

Routing (classified ONCE, no try-Rust-then-Python):
  PUT  …/squad/<n>   -> Rust (numeric id; …/squad/active stays Python)
  GET  …/squad/list  -> Rust
  GET  …/userMassInfo-> Python proxy, ONLY .squad overlaid
  everything else    -> Python verbatim

CoreAccess gains read_squad_ext / replace_squad / all_owned (HTTP to the new
Core /squad/ext + /squad/replace routes).

PUT pipeline: parse -> build_squad_write (reverse-resolve every wire id;
refuse unresolved/duplicate) -> AUTHORIZE every resolved owned item against
the active club (identity resolution is NOT authorization; a valid wire id
owned by another profile is rejected before any mutation) -> Core atomic
replace+extension -> exactly {"id":0}. No Python fallback on failure; no
host-side second extension store; no fingerprint recomputation.

Read path assembles ONE projection input (one read_squad_ext + one batch
all_owned; no per-slot lookup) and runs the single adapter projector. Both
/squad/list and userMassInfo.squad derive from it. Fresh projects; Stale is
never applied; Missing is never fabricated — both are prominent integrity
failures, never served from Python (no split authority). The overlay
replaces only .squad and preserves userInfo/settings/userData/
pileSizeClientData, fixing Content-Length.

Tests: routing, full-replacement + exact ack, unknown/foreign/duplicate item
rejection with Core unchanged, idempotent repeat PUT, coupled read-after-
write (list + userMassInfo agree, real resourceIds + stable wire ids),
overlay field preservation, bounded no-N+1 reads, Stale/Missing integrity.
2026-08-12 03:04:24 +00:00
funman300 4d30d8b3e8 chore: bump openfut-core gitlink to squad-ext HTTP routes (9b2c6b8)
Exposes GET /squad/ext and PUT /squad/replace so the UTAS host can read
and atomically persist the FIFA17 squad canonical+extension state over
HTTP. Core commit sits atop the frozen contract 615c5fd (branch
rust-migration/squad-ext-routes); no domain change. The preserved dirty
openfut-core worktree (eab522a) is intentionally left untouched, so root
status still shows 'M openfut-core' as before.
2026-08-12 02:47:36 +00:00
funman300 0e30980632 style(adapter): elide redundant lifetime in squad projection test helper 2026-08-12 02:31:13 +00:00
funman300 46a81e7a07 test(adapter): squad mutation battery (14 mutants, all killed)
mutation-battery.sh injects each of the 14 required wrong behaviours into
the committed source, runs the one invariant test that must catch it, and
requires a non-zero exit (mutant killed), reverting via git after each.

Kills: kit-by-slot, captain-as-resourceId, chemistry-reconciled,
custom-regenerated, index-derived, stale-accepted, missing-fabricated,
faked-asset-id, duplicate-instance-collapse, PUT-as-slot-diff,
wire-id-in-canonical, projector-bypasses-shared-shaper, schema-version-
ignored, player-state-keyed-by-definition. 14/14 killed.
2026-08-12 02:30:38 +00:00
funman300 e09344490f feat(adapter): single FIFA17 squad projector + fixture round-trip tests
fut::squad_projection is the ONE projector for every squad read shape.
project_squad(canonical squad + Fresh extension + owned items) -> the FIFA
17 squad wire object; user_mass_info_squad and squad_list are envelope-only
wrappers over the same output (no per-endpoint domain model).

Design guarantees exercised by tests:
  - purity / no N+1: consumes a host-assembled input (read_squad_with_ext +
    one batch owned-cards fetch + in-memory card defs); no per-slot lookup
  - shared shaper: every occupied slot is shaped by fut::item::shape_item,
    so squad items and /club items cannot drift
  - Fresh -> full projection; Stale -> never applied (verdict surfaced);
    Missing -> explicit, never fabricated
  - captain projects as the resolved WIRE id (never resourceId); index and
    formation round-trip verbatim; kit follows the player; two owned copies
    of one definition stay distinct

Adds committed sanitized fixtures decoded from the squad session capture
(swap, f433, persisted userMassInfo.squad read, squad/list) and
tests/squad_projection.rs: baseline / swap / formation-change / persisted
read-after-write round-trips asserted by ownership class (canonical,
extension, shadow, derived identity), plus one-projector no-divergence.
2026-08-12 02:28:05 +00:00
funman300 80a8bc4520 feat(adapter): FIFA17 squad extension v1 + full-replacement PUT builder
Add fut::squad_ext::Fifa17SquadExtensionV1 — the versioned, adapter-owned
payload Core stores opaquely alongside the canonical squad. Carries the
FIFA-only wire state that is not Core-canonical:
  - custom[]        opaque 33-int string, round-tripped verbatim
  - squad_type      observed FIFA token
  - kit_numbers     keyed by owned_card_id (kit follows the PLAYER, proven
                    by the swap/formation captures), never by slot/definition
  - manager         opaque item ref (not a squad player; not shaped)
  - kicktakers      opaque role refs; relationship to captain UNKNOWN, so
                    preserved verbatim and never normalized to the captain
  - client_reported chemistry/rating/starRating shadow, never authoritative
from_payload enforces the payload schema version first (distinct from Core's
DB schema); an unknown version is rejected, never coerced.

build_squad_write turns a parsed PUT + host wire->owned resolver into a
canonical ProposedSquad + extension, refusing on unresolved ids or a
duplicate owned item. Identity resolution is explicitly NOT authorization.

Refactor the 550a59d parser scaffold: ProposedSquad is now pure canonical
(FIFA-only + shadow fields moved to the extension); the canonical formation
is the FIFA wire token verbatim (drop the lossy f442->"4-4-2" map that
could not even represent f433) so formation and index round-trip exactly
with no derivation. Bench split is the fixed 23-slot array convention.
2026-08-12 02:19:22 +00:00
funman300 b50e0359f7 feat(adapter): extract shared FIFA17 FUT item-shaping primitive
Move the per-item card shaper (CoreOwnedItem, Fifa17Identity,
ItemIdentityResolver, ShapeStats, shape_item) out of club_response into
fut::item so /club and the upcoming squad projection emit byte-identical
items from one source of truth. club_response keeps only the /club
{itemData:[...]} envelope and re-exports the moved types for API
stability. shape_item is now pub; no behavior change (all /club and
oracle-parity tests unchanged and green).

Adds item-shaper tests: full-field identity mapping and the duplicate
owned-copy invariant (two instances of one definition keep distinct wire
ids, share one asset id).
2026-08-12 02:14:41 +00:00
funman300 58a300c7f4 core: game-scoped opaque squad extension + atomic fingerprint write (submodule 615c5fd) 2026-08-12 01:40:13 +00:00
funman300 eb8311a5ee evidence: FIFA17 squad controlled retail capture (swap/formation/relaunch) sanitized fixtures 2026-08-12 01:16:46 +00:00
funman300 550a59d12c feat(adapter): FIFA17 squad full-replacement wire parser + reverse-map scaffolding (unrouted) 2026-08-12 00:53:46 +00:00
funman300 8c1d1ed958 docs(mirror): /club RUNTIME VALIDATED on retail FIFA 17 2026-08-12 00:36:26 +00:00
funman300 fc00b0c6f9 docs(mirror): /club composition proven live (slice 5) 2026-08-11 23:05:29 +00:00
funman300 5276dd2066 feat(utas-host): send X-OpenFUT-Game to Core + end-to-end /club composition test 2026-08-11 23:00:08 +00:00
funman300 88da16a11e feat(fifa17): curated dev content pack generator + Core dev seed (submodule 36abd4b) 2026-08-11 22:57:02 +00:00
funman300 3ef3bc32ec feat(utas-host): real Fifa17IdentityResolver (catalog + store + policy), drop placeholders 2026-08-11 22:33:40 +00:00
funman300 36fe1caa3f feat(fifa17): deterministic base-card seed generator + full identity catalog
scripts/seed_fifa17_cards.py: deterministic pipeline from committed FIFA17 data
(pool.json + roster.json + leagues/nations/teams tables) -> the card-definition
identity catalog. CardDefinitionId is opaque + deterministic (fifa17_<asset>),
version 0 (base cards only; resource_id == asset_id). --check mode diffs against
committed output (drift-detection mutation-proven). Provenance embedded.

Generated openfut-adapter-fifa17/data/fifa17-card-identities.json: all 17,563
base assets. Semantic definition coverage (to /tmp, not committed here): 17,547
resolvable; 16 skipped for missing roster name (reported, never fabricated).

Adapter loads the committed catalog (test: 17,563 entries, Ronaldo fifa17_20801
-> asset 20801 v0). Phase commit 3/5. NOT owned inventory: this is 'which cards
exist', not 'which the user owns'. Core content seeding + dev-owned set next.
2026-08-11 22:19:57 +00:00
funman300 f55c401b6c feat(fifa17): card-definition identity catalog + owned-item wire-id policy
fut::catalog — Fifa17CardCatalog maps a semantic CardDefinitionId to a FIFA 17
render identity (resource_id = (version<<24)|asset_id; version 0 => resource==
asset). Versioned JSON (schema_version=1, game=fifa17); validates schema/game,
rejects asset_id > 24 bits, and rejects two card ids claiming one resource_id.
Unknown definitions resolve to None (callers drop, never fabricate).
Fifa17WireItemIdPolicy carries the owned-item namespace (base 100_000_000,
first id 100_000_001, per the oracle) supplied to the generic store.

Adds serde derive to the adapter. 8 catalog tests; 3/3 mutations killed
(resourceId-drops-version, conflict-detection-off, asset-range-off).
Phase commit 2/5. No card->asset DATA shipped: the synthetic Core catalogue is
unmappable (see seed plan); the loader + format land now, population later.
2026-08-11 21:59:50 +00:00
funman300 b8037b9b22 feat(identity): generic game-scoped external-identity store
openfut-identity: durable, reversible (game_id, entity_kind, core_id) <->
external wire id mapping. Game-independent infrastructure (adapters supply the
numeric policy via base_floor; the store guarantees stable/unique/reversible/
game-scoped/persistent/atomic/explicit). JSON-file backed behind an
ExternalIdentityStore trait (SQLite can drop in later); parking_lot-guarded,
atomic temp+rename persist, rejects a torn reverse-duplicate on open.

Core never learns FIFA integers; only the host/adapter that owns a game
boundary uses this. 6 tests, 4/4 mutations killed (same-id-for-two-items,
lost-on-restart, broken-reverse, dropped-game-scope). Phase commit 1/5.
2026-08-11 21:57:15 +00:00
funman300 c0a3f68ded feat(utas): FIFA17 UTAS migration host + /club adapter mappings
openfut-utas-host: the first live UTAS host. Serves GET /ut/game/<title>/club
from OpenFUT Core via the FIFA17 adapter and reverse-proxies every other UTAS
route verbatim to the Python oracle. Plaintext HTTP/1.1 keep-alive (no TLS);
route classification before execution; a Core error on /club degrades to an
empty page and never falls back to Python. CoreAccess is a host-owned boundary
(the adapter stays transport-agnostic).

openfut-adapter-fifa17::fut: owned_query (wire parse + FIFA id->name mapping,
unknown id = hard error), entities (id<->name from committed tables), and
club_response (FIFA _item shaping; drops items lacking a real FIFA asset id,
never fabricates one).

openfut-core submodule advanced to the reconciled trunk (6acae54 = 8c8a4116
multi-game + eab522a replace_squad/SquadRules + the /club semantic query).
11 host tests + adapter fut tests; 10/10 host mutations killed. rare=SP UNKNOWN.
Retail rendering of Core inventory still blocked on the Core-card->asset-id
identity decision (next phase).
2026-08-11 21:40:15 +00:00
funman300 04c5043aba utas: My Squad filter corpus — every filter identified, root cause measured
Controlled retail capture, one criterion at a time, cleared between each.
47 transactions. Every filter the My Squad picker sends is now known from
the wire rather than guessed.

Route: GET /ut/game/fifa17/club -- the picker hits UTAS and reuses the
general club-inventory route.

  level=any|gold        quality      lowercase, ALWAYS present
  rare=SP               "Special"    uppercase, OMITTED when off
  position=ST           position     uppercase, omitted when off
  nation=52             entity id    numeric
  league=13             entity id    numeric
  team=5                entity id    numeric, NESTED under league
  sort=desc                          client constant; the UI has no sort control
  start=/count=11       pagination

Two encoding families: short string enums, and numeric FIFA ids. The ids
must never reach Core. Filters compose as plain ANDs in one query --
string and id filters alike -- so each maps independently.

THE ROOT CAUSE IS SELF-AMPLIFYING.

club_route honours type, team and league; it never reads start, count,
level, sort or year. Because start is ignored, every page returns the
same full set, so the client concludes the page was full and asks for the
next one. One scroll produced 22 requests and 6.2 MB, stopping at
start=200 only because the client gave up -- against a filtered set of 32
items that should have been three pages.

That also explains why the bug reads as erratic rather than broken:
league=13&position=ST returns every Premier League player instead of
Premier League strikers. Plausible, wrongly sized, hard to notice.

Measured filtered sets, from the real cluttered club -- these are the
acceptance test for the fix:

  unfiltered            1962
  league=13              350
  league=13&team=5        32

Two client behaviours worth carrying forward: the picker fires a query
per highlighted entry, not per selection (two requests for one club
pick), and parameter ORDER is not stable, so parsing must be key-value.

FIXTURE SIZE: bodies over 4 KB are truncated in the committed fixture,
with body_full_len and body_full_sha256 retained, because the same 1.1 MB
club response repeats ~25 times and its hash already proves identity.
13.3 MB -> 247 KB. The raw .ofcap keeps every byte, privately and
gitignored. Truncation is recorded per transaction so a trimmed fixture
is never mistaken for a whole response.

Audited across all three identifier surfaces -- headers, JSON bodies,
query strings -- before and after the size change: no leaks. 6/6
sanitiser mutations still killed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 19:32:57 +00:00
funman300 0b66662525 utas: first real corpus, and two sanitiser gaps the audit caught
24 transactions across 11 connections from a retail session: login,
hub, one pack open, two squad saves, a quick-sell, with before/after
state manifests. Raw .ofcap stays gitignored at 0600; the sanitized
corpus is committed as adapter fixtures.

TWO GAPS FOUND BY AUDITING THE OUTPUT, NOT BY TRUSTING THE SANITISER.

1. `POST /ut/auth` carries `macAddress` and `deviceId`. Session tokens
   were being redacted correctly and these were not. A committed fixture
   is a published fixture.

2. Then, with those fixed, the audit fired AGAIN on the file about to be
   committed: `GET .../phishing/trusteddevice?deviceId=...` puts the id in
   the QUERY STRING. Three input surfaces carry identifiers -- headers,
   JSON bodies, and query strings -- and the sanitiser knew about two.

Both fixed in the tool rather than by editing the file, with a
regression test and a mutation for the query path.

AND A THIRD ARTEFACT MIX-UP, in the mutation harness itself. It reported
the query-redaction mutation as SURVIVED while a hand-run of the same
mutation killed it. Cause: the harness pointed at a stale scratchpad copy
of the test that pre-dated the query assertion, so it was faithfully
testing the mutated tool against a test that could not detect the
mutation. That is the same class as the build guard checking the wrong
binary and cargo reusing a binary compiled from mutated source -- the
third instance today of measuring the wrong artifact. The harness now
resolves ROOT from its own location and runs the COMMITTED test; the
stale copy is deleted.

Harness committed as scripts/mutate-utas-observe.py so this is repeatable
rather than a thing that happened once in a scratch directory. 6/6 killed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 18:33:59 +00:00
funman300 cdea85e214 utas: standalone recording proxy that tees rather than rebuilds
UTAS needs a real request/response corpus before any Rust is written: it
is where protocol shape and FUT state start being coupled, so guessing is
worse here than it was for Blaze. The oracle truncates logged bodies at
~200 chars, and raising that cap would mean editing the behavioural
specification to make it easier to copy -- backwards. A proxy gets the
same evidence and leaves the oracle untouched.

THE DESIGN RULE: TEE, DO NOT REBUILD.

UTAS is plaintext HTTP/1.1 on ThreadingHTTPServer, so keep-alive,
pipelining and chunked transfer are all live. A proxy that parses a
request and re-emits it can corrupt the traffic it exists to observe --
and that corruption would present as a UTAS bug, pointing the
investigation in exactly the wrong direction. So bytes are copied
verbatim in both directions and a second copy goes to disk; transactions
are reconstructed later, offline, from that copy. A parser bug therefore
spoils the record and never the session.

Standalone, NOT in the container, so the same tool can later sit in front
of a Rust UTAS host and replay an identical captured request against both.

Two layers, as with the Blaze captures: raw/*.ofcap is exact bytes at mode
0600 and gitignored; sanitized/transactions.jsonl is the committed
artefact. Bodies are preserved EXACTLY and sanitised second -- only
known-secret headers and JSON keys are replaced, structure is never
reshaped, and every redaction is recorded in the transaction so a reader
knows what was touched.

Captured per transaction: connection id, sequence, relative and wall
time, elapsed ms, method, path, query, HTTP version, headers IN RECEIVED
ORDER as pairs (a dict would drop duplicates and ordering), raw body and
length for both directions, status, and observed keep-alive.

Verified as two independent properties, because they fail differently:
transparency (bytes through the proxy identical to bytes direct, Date
masked, with the mask asserted to have fired) and fidelity (parsed
transactions match what was sent, including a dechunked response and a
300-byte POST body). 5/5 mutations killed, including "record but do not
forward", "drop the last byte of every chunk" and "stop redacting".

scripts/test-utas-observe.py is committed alongside it: a capture tool
nobody can re-verify is not evidence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 18:13:06 +00:00
funman300 05f6147433 http: extract the shared body drain; fix a flaky test race it exposed
Queued cleanup, run only AFTER the roster gate closed in both directions,
so the live A/B changed exactly one thing.

The two `drain_body` implementations were character-for-character
identical, so the extraction is a move. What it guards is not cosmetic:
answering while the client is still sending leaves unread data in the
receive queue and Linux turns the close into an RST rather than a FIN --
invisible in any comparison of the response, and worth two live gate
attempts to find. Behaviour that must be identical across hosts gets one
implementation, the same reasoning that produced openfut-tls.

SCOPE IS DELIBERATELY NARROW. Only the byte-identical part moved. The two
head-reading loops are NOT identical and stay where they are:

              redirector   roster
  head cap    65536        16384
  read chunk  4096         1024
  on error    abort        proceed if any bytes arrived

Those differences are probably accidental, but each host is gate-proven
with the values it has. Unifying them would be a behaviour change wearing
a refactor's clothes -- exactly the mistake this project has already paid
for. They converge later as their own change with their own gate, or not
at all.

Purity shown, not asserted: every existing test in both hosts still
passes (426 workspace tests), and 7/7 mutations are killed, including
three in the SHARED crate that must break both hosts at once and one per
host that skips the drain call.

Three test cases neither host had now exist, because the extracted code
finally had somewhere to be tested directly: a malformed Content-Length,
an unterminated head, and a lookalike header. That last one matters --
`X-Original-Content-Length: 99` would drain 99 bytes that were never sent
if the match were `contains` rather than `starts_with`, and a mutation
confirms the test catches it.

Also fixes a race this run exposed in openfut-tls's own tests: keypair()
returned early if the certificate file existed, but wrote the certificate
BEFORE the key, so a parallel test could observe a cert whose key had not
landed. It failed one run and passed the next -- the kind of flake that
gets rerun instead of fixed. Now generated once per process via OnceLock,
key written first, and the suite was repeated five times to confirm.

Nothing deployed and nothing restarted: the running redirector and roster
are still the gate-proven binaries.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 18:04:08 +00:00
funman300 8f3b659c33 lifecycle: one host-lifecycle helper; roster.sh; ban pkill -f
redirector.sh and the coming roster.sh needed the same five rules, each
of which cost something to learn:

  * resolve /proc/PID/exe; never match a command line. `pkill -f` /
    `pgrep -f` match any shell whose ARGUMENTS mention the name, including
    the shell running the command. That has killed this session's own
    shell twice, and is now banned in migration tooling -- the helper
    contains no `-f` matching and the header says why.
  * `readlink`, not `readlink -f`. After a rebuild the link reads
    "<path> (deleted)" and -f resolves it to nothing, so the orphan check
    goes blind to exactly the long-lived processes it exists to find. Two
    orphans hid there, one serving the wrong certificate.
  * stop PROVES the process is gone and the port free.
  * an ambiguous binary is an error for start/verify but NOT for
    stop/status: rollback must never be blocked by a question about the
    build tree.
  * verify the RUNNING process's commit, not the artifact on disk, which
    a rebuild can silently advance past.

Copying those into a second script would have been the same mistake as
copying the TLS setup. Instead scripts/host-lifecycle.sh owns them and a
service supplies four facts: name, crate, executable, port variable.
redirector.sh goes from 178 lines to 26 and roster.sh is 24, with no
behaviour change -- the refactored redirector.sh still sees the live
armed process (pid 830736, port 42227) and still refuses correctly
because HEAD has moved past it.

Paths are unchanged (rundir, pidfile, portfile, commit stamp, log), so
the currently running redirector stays manageable across this refactor.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 17:45:15 +00:00
funman300 c9ae914910 roster-host: transport host for the FUT roster update, lifecycle-matched
Second consumer of openfut-tls, and the reason it was extracted first.
This host contains no roster content and no cipher choice: the adapter
owns the 67 bytes and the observed TLS profile, openfut-tls owns the
acceptor, and this crate owns accept/read/drain/write/close.

Lifecycle was MEASURED, not inherited. The obvious mistake here would
have been copying the redirector's 300ms dwell because the other host has
one. A probe against the oracle says otherwise:

    dwell after responding   0 ms      (redirector: 300 ms)
    request body             drained   POST answered only once it arrives
    close                    clean FIN, never RST
    keep-alive               none      one request per connection

The probe ran against a REPLICA of roster_server.py loaded from its own
source, not against :8081 -- http.server.HTTPServer is single-threaded
and FIFA was mid-session, so holding a connection open to measure the
close would have stalled the game's poll and could have surfaced as the
squad-update error. The replica was then confirmed byte-identical to the
live oracle under masking, the 1-byte delta being the container's Python
version in the Server header.

Differential against the live oracle, every field identical, with the
Server header compared UNMASKED:

    GET  230B   HEAD 163B   POST 163B
    drained=True  reset=False  answered_before_body=False
    keepalive: second request accepted by the socket, never answered

Testing follows the redirector's hard-won rule: where a property is
visible both to the client and inside the host, it is asserted inside the
host via ConnOutcome. A client-side check cannot tell "drained" from "not
drained" -- it reads the buffered response either way -- and that exact
mistake let a mutation survive once already.

9 parity tests, 6 unit tests, 5/5 mutations killed, including "answer
before draining", "hold the connection open like the redirector" and
"inherit the redirector's 300ms default".

drain_body is duplicated from the redirector deliberately. Unifying it
means editing the redirector, and the roster A/B must change exactly one
thing. Extraction is scheduled for after the roster gate closes.

Not deployed and not switched: Python still serves :8081.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 17:41:11 +00:00
funman300 84e81f2037 tls: extract a shared listener; move FIFA 17's profile into its adapter
The redirector was the only host that spoke TLS, so its TLS lived inside
it. The roster host needs the same listener, and that made the choice
explicit: share this code or copy it.

Copying it is what already went wrong. On 2026-08-11 the Rust redirector
served one certificate while the container served another. ProtoSSL
caches the server certificate per backend, so the redirector -- the first
TLS connection of a session -- decided what the client expected, and
every later service failed its handshake. Silently: Python's socketserver
swallows ssl.SSLError as OSError. Three gates went to it. One place to
configure TLS is the structural fix, so it exists before the second host
does rather than after.

Split along the line the architecture already draws:

  openfut-tls               how to build an acceptor. Game-independent.
                            Knows nothing about which suites any client
                            offers.
  adapter-fifa17::tls       what FIFA 17 was OBSERVED to offer: the six
                            enabled suites, the two refused, the TLS 1.2
                            window, the EA SNI. Plain strings, so the
                            adapter keeps its lean dependencies -- reading
                            a card table should not build OpenSSL.
  redirector-host           joins the two. Chooses no cipher of its own.

Behaviour is unchanged, and shown to be:

* tests/fifa17_tls_profile.rs carries over every case from the deleted
  module -- FIFA's eight suites negotiate AES256-GCM-SHA384, each enabled
  suite works alone, RC4-only is refused, ECDHE-only is refused. Deleting
  a module must not quietly delete its evidence.
* one test pins the composed values literally against the host as it was
  when gates 1-14 passed. A "pure refactor" that cannot fail is not a
  claim, it is an assumption.
* the rebuilt binary self-tests to the same TLSv1.2 / AES256-GCM-SHA384
  the retail client negotiated at 17:09 today.

Two improvements fall out of having one place to look:

* the startup banner now prints cert_sha256. The mismatch above raised no
  error at startup and broke the client much later with nothing logged;
  it is now the first line of the log.
* tls_min/tls_max print as TLSv1.2 rather than SslVersion(771). This line
  is gate evidence and gets read by people.

Nothing deployed and nothing restarted: FIFA is mid-session on the
running redirector, which is untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 17:30:01 +00:00
funman300 696386a9c1 client_arm: verify the hosts entry by resolution, not by presence
The old check was `grep easw /etc/hosts && echo ok`. It passed on ANY
matching line -- including a line that shadows ours. glibc returns the
first match, and the sed above only deletes lines this script wrote
(`# openfut`), so a foreign entry earlier in the file wins forever and
re-running the script never helps.

Observed today: a leftover `127.0.0.1 easw.easports.com` from the
single-machine era, before the backend moved to its own host. Every arm
reported "/etc/hosts ok" while the name resolved to loopback.

Now it resolves the name -- the same call the game makes -- and compares
address to address, so a server given as a hostname is handled too. On a
mismatch it prints the offending lines with line numbers and says how to
fix them.

It does NOT delete them. This script writes one tagged line and owns only
that line; silently removing entries a user put there by hand is a bigger
hazard than the shadowing it would cure.

Reported as a warning, not an error, because it is survivable: the
responders advertise the server address, so the game stops using this
hostname after the first redirected contact. FIFA reached the FUT hub
today with this exact misconfiguration in place. Claiming it is fatal
would be wrong, and a check that overstates its findings gets ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 17:19:52 +00:00
funman300 aa2679162d redirector.sh: never leave it ambiguous which binary is under test
Two defects, both found by the guards misfiring rather than by reading:

1. BIN preferred target/debug and fell back to release only when debug was
   absent. `cargo build --release` therefore produced a correct binary while
   the script kept inspecting a stale debug one, and the build guard refused
   with a message naming a commit nobody was trying to run. The guard was
   right that something was stale — it just pointed at the wrong artifact.
   Disagreement between the two is now an explicit refusal naming both, with
   OPENFUT_REDIRECTOR_BIN as the deliberate override.

   The refusal is recorded at load and raised only by `verify` and `start`.
   `stop` and `status` must work in any build-tree state: rollback can never
   be blocked by a question about which artifact would have been started.

2. `verify-running` read the stamp file without checking the process still
   existed. The stamp outlives the process, so after a stop it reported on a
   corpse — either "identity OK" or a REFUSAL naming a commit, both implying
   something was running when nothing was.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 16:20:16 +00:00
funman300 096d1c882f switch: fix the unquoted python string that broke status with no --name
`cmd_status` has two paths. The `--name` path filters on an exact tag and
works. The no-name path — the "show me every switch on this box" survey,
which is how an orphan switch under a different name would be found —
built its python with shell quote-juggling and never closed the string
literal, so it died with a SyntaxError every time.

It failed loudly (rc=1, a traceback) rather than reporting "no rules", so
it never lied about the state. But it also meant the survey path had
never once run, which is the more useful lesson: every branch of a safety
tool needs exercising, not just the branch the happy path takes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-11 16:16:10 +00:00
funman300 ca63095786 lifecycle: stop the orphan check going blind when the binary is rebuilt
`list_procs` matched on `readlink -f /proc/PID/exe`. Once the binary is
rebuilt -- which happens constantly here, `cargo test` alone is enough -- the
link reads "<path> (deleted)" and -f resolves it to something that matches
nothing. The scan then finds zero processes, so `start`'s orphan check passes
and a second instance can be launched alongside a stray.

Not theoretical. Two orphans were running undetected tonight:

  pid 592731  :42327  a stale-cert redirector left from testing check-tls-parity,
                      still serving F9:16:1A -- the exact certificate whose
                      mismatch cost three live gates
  pid 542693  :42230  a Blaze sidecar debug build from 03:12

Neither was in a client path, so neither was doing harm, but a stray listener
serving the known-bad certificate is precisely what should never sit around
unnoticed.

Fixed by using plain readlink and stripping the " (deleted)" suffix. Shown both
ways: with the bug `status` reports no processes at all for a live pid; with the
fix it reports 604454. The pidfile path was unaffected, which is why `stop` kept
working and hid this.
2026-08-11 05:25:33 +00:00
funman300 c65e9c54ce observe: correct a stale comment calling the catch-all 'other'
It is a TOTAL -- every packet reaching the chain counts there, including ones
already counted by a named-port rule. The old wording invited reading the number
as a remainder, which is how 15 unexplained attempts got misread earlier.
2026-08-11 05:20:24 +00:00
funman300 b1bc7a764e adapter: port the FUT roster-update response, held to the live oracle's bytes
Next component in the migration order (Roster -> LSX -> UTAS). Adapter layer
only: no host, no runtime replacement, nothing armed.

The response is shaped as much by http.server.BaseHTTPRequestHandler as by the
oracle's handler code, so it is captured over the wire rather than reasoned
about:

  * HTTP/1.0 status line -- protocol_version is left at its default, so the
    reply is 1.0 even though the client asks for 1.1
  * send_response injects Server: and Date: BEFORE the handler's own headers
  * POST answers with headers only: the handler writes the body `if method ==
    "GET"`, so a POST advertises Content-Length: 67 and then sends nothing

That last one is preserved, not corrected. It looks like a bug, but "obviously a
bug" has been the wrong call before in this port, and a test now asserts it so a
future cleanup has to argue with something.

Date and Server are volatile and are MASKED in the fixture rather than dropped,
so their presence and position are still asserted. Server is additionally
recorded verbatim: it carries the container's Python version, so a drift away
from roster::ORACLE_SERVER fails a test instead of silently changing every byte
we emit.

generate_roster.py --check FAILS when it cannot reach the oracle rather than
passing, and mutation-testing the mutation harness itself caught two "surviving"
mutations that were really sed no-ops. With application verified, all four
mutations (header order, Content-Length, XML body, Connection) are killed.
2026-08-11 05:19:29 +00:00
funman300 d7c0a5521d switch: refuse to arm at a dead target; watchdog: use a pidfile
Three times now the same sequence has broken the client path: a build guard
correctly refuses to start the Rust replacement, and the `switch on` that
follows in the same script arms anyway, because it never checked whether
anything was listening. The redirect then lands on a closed socket and the
working Python service is bypassed for no benefit.

`on` now refuses unless the target port is listening. ALLOW_DEAD_TARGET=1
overrides it for arming ahead of a service that is about to start, but that has
to be deliberate. Verified both ways: rc=2 and nothing installed against a dead
port, rc=0 and two rules with the override.

The watchdog now writes a pidfile. Stopping it by command-line match is unsafe
-- any shell whose arguments merely mention the script name matches too, which
has now killed the wrong process twice here (once via `pkill -f`, once via a
/proc/*/cmdline substring loop).
2026-08-11 05:13:40 +00:00
funman300 2ae90b1ea9 tooling: watchdog that rolls an armed switch back when the service stops answering
`openfut-switch.sh on` prints "the service MUST stay up" -- true, and useless
when nobody is at the terminal. An armed switch pointing at a dead port means
the client hits a closed socket with no fallback.

This turns the documented rollback into an automatic one, failing toward the
Python oracle. The worst case of a spurious trip is a gate needing re-arming;
it can never leave the client broken.

It only ever REMOVES a switch. It does not install one, restart the Rust
service, or touch Python, and it does not re-arm after tripping -- an
unexplained rollback should be a finding to read, not something hidden by
flapping the switch back on.

The probe goes through the switch and speaks TLS, because a bare TCP connect
would succeed against a process wedged mid-handshake.

Tested both directions, not just the happy path: quiet for 45s against a
healthy service, and against a stopped one it failed 3/3 in 9s, rolled back,
and left Python serving -- verified by re-reading all four tables and by which
implementation's log grew.
2026-08-11 05:11:41 +00:00
funman300 cfb0435d96 redirector.sh: verify the RUNNING process's commit, not just the binary on disk
`verify` inspects `$BIN --identity`, which is the file on disk. That is not
necessarily what is serving. Caught during gate 14 setup: the live process had
been started from 5bc39e9, then `cargo test` re-ran build.rs (the branch ref
moved when an unrelated script was committed) and restamped the on-disk binary
to fc411bb. `verify` then reported "build identity OK" about an artifact that
was not the running service.

`start` now records the stamped commit to $RUNDIR/redirector.commit, and
`verify-running` compares THAT against HEAD, refusing when they differ. The
existing on-disk check stays -- it is the right gate for "may I start this" --
but only the recorded stamp answers "is the thing currently serving the thing I
think it is", which is the question a live gate's evidence depends on.
2026-08-11 05:03:47 +00:00
funman300 fc411bb6f1 scripts: require one certificate across the whole FIFA-facing TLS stack
Two live gates were lost to a second variable I had been asked to eliminate.
The Rust redirector was pointed at the repo's fifa17-recon/tools/redir_cert.pem
(fingerprint F9:16:1A...), while the running container serves a different cert
baked into its image (E7:F9:46...) which the Python redirector, roster and the
rest of the stack all share. So the A/B compared TLS implementation AND
certificate identity at once.

FIFA 17's ProtoSSL caches the server certificate for a backend. The redirector
is the first TLS connection of a session, so its cert becomes the one the client
expects; the next service presenting a different cert fails its handshake. That
is why the redirect itself always succeeded and the failure surfaced later, on
the roster fetch -- "An error occurred downloading the FUT Squad Update".

It stayed invisible because Python's socketserver swallows it: a handshake
failure at accept() raises ssl.SSLError, which subclasses OSError and is
discarded by _handle_request_noblock. No request log, no stderr. Every server
looked healthy while the client could not talk to any of them.

Confirmed on the wire: tls-observe in front of the roster server captured four
ClientHellos from the client, correct SNI and the same 8 static-RSA suites it
offers the redirector, none of which produced a request.

The check is mutation-tested against the real bug: with a redirector started on
the stale repo cert it exits 1 and names the mismatch.
2026-08-11 04:38:23 +00:00
funman300 5bc39e902d tooling: observe client connection ATTEMPTS; make the build guard reject bad args
openfut-observe.sh answers the one question no server log can: when a gate
fails and a service logged nothing, did the client try and fail, or never try?
Both look like silence. Two redirector gates were lost to that ambiguity --
"roster server logged nothing" was equally consistent with a broken roster
service, a wrong roster URL, and a client that never asked.

Built on iptables packet counters because this box has no tcpdump, no
conntrack, and no readable kernel log. That last one is verified rather than
assumed: an initial LOG-based version installed correctly and its rules matched
(counters proved it), but the output went nowhere -- journalctl -k has no
entries and dmesg is empty. Counters are also lower volume and record only SYNs,
so no payload can be captured even in principle.

Validated against the live client, not a loopback stand-in: an initial
self-test using this host's own address counted almost nothing, because
locally-generated packets never traverse PREROUTING. Against the real remote
client it counts 8081 at ~4/min, matching the roster server's own log.

Known gap, recorded rather than hidden: the catch-all TOTAL runs well above the
sum of the named ports, so the client makes steady background attempts to ports
not tracked here. It is present during a working session, so it is not the
failure signature, and it is not chased further here.

verify-build-identity.sh now rejects an argument that is not a commit hash.
Passing the binary path instead of its stamp previously produced a plausible
"REFUSING: binary was built from ./target/release/... but HEAD is <sha>", which
reads as a real stale-build finding rather than a caller mistake -- and a
safeguard that cries wolf is one people learn to route around. Usage error is
now exit 2, distinct from a genuine stale build (1) and success (0).
2026-08-11 04:22:40 +00:00
funman300 e2c4ca6d56 redirector-host: reproduce the oracle's connection lifecycle, not just its bytes
Two live gate attempts failed with "An error occurred downloading the FUT
Squad Update" while the redirect response was verified byte-identical to the
Python oracle. Rolling back to the Python redirector fixed it, so the response
bytes were never the whole contract.

Log archaeology found the discriminator: the client polls
/fifa17/fut/rosterupdate.xml ~4x/min in every successful FUT session, and the
only gap in 300 recorded fetches is 03:47-03:58 -- exactly the two
Rust-redirector sessions. The Blaze RPC sequence over those sessions is
identical (msgNum 0-53), so the divergence is entirely outside Blaze.

A differential lifecycle probe against both redirectors found the two
behaviours this host never reproduced:

  * the oracle drains the request body per Content-Length; this host stopped
    at the header terminator, leaving unread data in the receive queue, which
    makes Linux close with RST rather than FIN
  * the oracle holds the connection open ~300ms before closing
    (time.sleep(0.3)); this host closed at 0ms

Both are now reproduced. The dwell is a named constant, ORACLE_CLOSE_DWELL,
overridable only so the causal experiment -- set it to 0, confirm the failure
returns -- can be run without a rebuild.

The suite could not have caught either: it sent Content-Length: 0, so there
was never a body to drain. It now POSTs a body, and asserts a split-write body
is fully consumed.

Testing the drain via client-visible symptoms does NOT work -- verified by
mutation: with the drain removed the client still reads the buffered response
and sees close_notify before any reset. So the host records a per-connection
ConnOutcome and the test asserts on that. Both mutations (no-dwell, no-drain)
are now each caught by exactly one test.

This does not yet prove causation for the FUT Squad Update failure; it removes
the only two measured divergences. Gate 6 is the test.
2026-08-11 04:12:32 +00:00
funman300 288d990821 empty commit to advance HEAD for the stale-binary mutation test 2026-08-11 03:46:08 +00:00
funman300 c03702707b redirector: commit stamp + shared build-identity verifier that REFUSES
The binary records only the commit it was built from -- no dirty-tree flag.
Cargo will not re-run a build script because another crate's source changed, so
a compiled-in 'clean' claim can be stale and is not a safeguard; that was
verified on the Blaze host.

scripts/verify-build-identity.sh establishes both facts at LAUNCH, where they
cannot go stale: the stamped commit equals HEAD, and the migration crates are
clean. It REFUSES rather than warns, because for a migration gate a warning on
stderr is something to scroll past.

--identity prints the stamp without valid configuration. The launcher must be
able to establish which commit a binary came from BEFORE deciding whether to
run it; requiring a correct environment first would invert the check.

redirector.sh mirrors sidecar.sh: refuses to start with an orphan present or
the port busy, matches the resolved executable rather than the command line
(pgrep -f matches any shell mentioning the name), and stop PROVES the process
is gone and the port free.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 03:46:07 +00:00
funman300 89f77470f3 redirector: Rust host on vendored OpenSSL; shared typed config extracted
TLS DEPENDENCY, as directed: the openssl crate directly with the `vendored`
feature. NOT native-tls. native-tls abstracts over whatever the platform
provides; here the requirement is the opposite -- precise, evidenced behaviour
for one legacy client -- which needs explicit control of the cipher list,
protocol floor/ceiling and security level. Vendored so a distro libssl update
cannot silently change whether FIFA 17 can connect.

Scoped to this crate alone. Neither OpenFUT Core nor the generic protocol
crates gain an OpenSSL dependency.

CIPHERS driven by the captured retail ClientHello, not by generic legacy
assumptions. The six RSA+AES suites it offers are enabled; RC4 and MD5 are
deliberately NOT, even though the client offers them -- it already negotiates
AES256-GCM-SHA384, so resurrecting RC4 for completeness would weaken the
service for nothing. TLS 1.2 floor and ceiling, matching the observed client;
the floor is not dropped to 1.0 pre-emptively because "the oracle permits it"
is not "the client requires it".

SECURITY LEVEL IS NOT LOWERED. Tried the default policy first, as directed,
and OpenSSL 3.6.3 accepts static-RSA/AES without weakening. No SECLEVEL change
was needed and none is applied; it remains overridable per-listener with
evidence.

CERTIFICATE: the proven Python redirector's material is reused, so the TLS
implementation stays the only variable in an A/B. Verified RSA-2048, CN
winter15.gosredirector.ea.com, cert/key modulus match; the key stays
gitignored.

SHARED CONFIG. New openfut-host-config is now the only crate that reads the
environment, and both hosts resolve endpoints through it. Two hosts each
parsing OPENFUT_ADVERTISE would be exactly the "separate helpers constructing
endpoints from different sources of truth" the address audit forbids.

VERIFICATION BY REAL HANDSHAKE, not by enumeration. The crate exposes no
accessor for a context's configured suites at this version, which turned out
better: the host now rehearses the retail handshake at startup with a client
restricted to exactly FIFA's eight suites and REFUSES TO SERVE if it fails, so
a cipher/version misconfiguration surfaces at boot rather than as an
unexplained failure during a live gate.

Gates 1-5 pass: TLS config unit tests; a FIFA-suite-only client negotiates
TLSv1.2/AES256-GCM-SHA384; each enabled RSA+AES suite negotiable alone; an
RC4-only client is refused; an ECDHE-only client is refused (proving no modern
policy was silently inherited); a full HTTPS round-trip returns bytes
IDENTICAL to the Python oracle's recorded response.

Cargo.lock committed for reproducibility: openssl 0.10.81, openssl-sys 0.9.117,
openssl-src 300.6.1+3.6.3 (OpenSSL 3.6.3). Updating openssl-src is NOT a
routine bump -- it requires re-running the FIFA compatibility gates.

Gates 6-14 need the retail client and are next.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 03:28:04 +00:00
funman300 0d576a14b7 switch: one generic NAT implementation; blaze-switch becomes a wrapper
The Blaze switch was hardwired to 42130 and could not intercept the redirector.
Rather than clone it, the iptables logic now lives in one place:

  openfut-switch.sh   generic: --server-ip --intercept-port --target-port
                      --name [--client-ip] [--legacy-tag]
  blaze-switch.sh     thin wrapper, CLI and output UNCHANGED so the validated
                      gate runbook and sidecar.sh's cross-check keep working

No deployment IP or port literal in the generic tool; 42130 is supplied by the
wrapper, 42127 by the redirector experiment.

VERIFICATION IS INDEPENDENT OF REMOVAL. Rules are created and deleted by their
comment tag; they are verified by parsing the kernel's own FIELDS (chain,
destination, dport, to-ports) with no reference to the comment. Status detects
duplicates, incomplete pairs, conflicting targets under one name, and foreign
redirects on the same port -- which it reports but never deletes. `off` removes
only rules bearing this switch's exact tag, then re-reads the table to confirm.

THREE BUGS FOUND WHILE BUILDING IT, all in the same family as the original
lying rollback:

1. Renaming the tag ORPHANED live rules. Gate 10 deliberately ended with the
   switch on, so rules carrying the old tag were still installed and the
   renamed tool could not see them -- `off` would have reported success while
   traffic stayed redirected. Hence --legacy-tag: a rename must not strand
   rules it owns.
2. Deleting by re-feeding the raw `iptables-save` line through the shell fails
   on this iptables, which prints `--comment "tag"` WITH quotes; word-splitting
   leaves the quotes inside the value so nothing matches. Bare-comment rules
   deleted fine, which is exactly what made it look like it worked. Deletes are
   now rebuilt from parsed fields and passed as argv elements.
3. `IFS=$'\t' read` collapsed consecutive tabs because tab is IFS *whitespace*,
   so an absent `-s` shifted every later field left and produced
   `-s <dport> --dport <to_ports> --to-ports ''`. Harmless here, but a shifted
   spec that matched a real rule would delete the wrong one. Now uses \x1f.

Mutation-tested against all seven required cases: wrong intercept port, wrong
target port, missing rule, duplicate rule, changed comment representation
(bare vs quoted), and a rollback that leaves a foreign redirect installed --
which exits non-zero rather than claiming success.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 03:12:09 +00:00
funman300 c5807c07a9 blaze-host: passive ClientHello observer for the redirector TLS decision
The redirector TLS question cannot be answered from the cipher OpenSSL
selected: its server follows client preference by default, so FIFA preferring
static RSA does not prove ECDHE was unavailable. Choosing a TLS stack on that
inference would be a guess. This reads the actual ClientHello.

PASSIVE BY CONSTRUCTION. Bytes relay verbatim both ways, nothing is injected
or rewritten, and the handshake is still terminated by the untouched Python
redirector. A parse failure logs and relays anyway -- observation must never be
able to break the path it observes.

Reports record/client version, supported_versions, SNI, every offered suite by
name, extensions, and a verdict on whether ANY forward-secret suite is offered,
which is exactly the rustls question. Unknown suites print as hex rather than
being dropped.

Verified end to end against the live Python redirector with openssl s_client:
31 offered suites parsed, 18 classified forward-secret, and Python logged the
relayed request and served its 406B serverinstanceinfo -- proving observation
AND pass-through in one run.

Unit-tested on truncated and non-TLS input; the verdict is asserted in both
directions so a static-RSA-only hello reports RULED OUT rather than defaulting
to the permissive answer.

NOTE: that 18-suite result is from openssl s_client, NOT from FIFA. It proves
the instrument works. The actual question is still open until a retail FIFA
ClientHello is captured.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 03:04:13 +00:00
funman300 8f5f54833f ci: tripwire against lab addresses creeping back into tracked source
Cheap insurance, explicitly not the real check -- the semantic tests in
deployment_config.rs are what prove propagation, using two TEST-NET addresses
and bind != advertise. This grep only stops the lab subnet reappearing months
from now when the reasoning has been forgotten.

Deployment config legitimately contains real addresses and lives in gitignored
files, so it is never scanned. The frozen baseline doc is allowlisted BY PATH:
it records what a past deployment actually was, and rewriting it would falsify
the record.

Also swapped the lab IP for a TEST-NET placeholder in the usage examples and
error messages of compose/entrypoint/client_arm. Those were already correct
architecture -- every one requires the address via ${VAR:?} -- but using the
real lab IP as the example is the same 'happens to match our lab' smell, and
placeholders keep the tripwire allowlist near-empty.

Mutation-tested: adding a lab address to a source file makes it exit 1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:59:41 +00:00
funman300 f451406058 audit: eliminate deployment-address hardcoding; single typed endpoint config
Mandatory OpenFUT architecture audit. Two real defects found and fixed, plus
the config surface tightened so neither class can recur.

DEFECT 1 -- hidden localhost fallback. The Rust host defaulted POW hosts to
127.0.0.1 while every other URL followed OPENFUT_ADVERTISE, so a remote
deployment would emit loopback POW URLs and fail far from the cause. It also
diverged from the deployed Python entrypoint, which derives them
(POW_HOST="${POW_HOST:-$ADV:8094}"). POW endpoints now derive from the
advertised address; explicit overrides still win.

DEFECT 2 -- Default gave loopback silently. `Endpoints::default()` and
`AdapterConfig::default()` supplied 127.0.0.1, so anything constructing a
config by omission got loopback with no signal. Both `Default` impls are
REMOVED. Loopback is now `Endpoints::loopback()` / `AdapterConfig::loopback()`:
an explicit, greppable decision. Production uses `advertising(host)`.

CONFIGURABILITY. `blaze_port` and `utas_port` are now config, not literals.
The advertised Blaze port is our choice -- the client goes wherever
<serverinstanceinfo> sends it -- and 8099 is the client's own built-in default
but still deployment config. A bad port value is an error, not a silent
fallback to the previous one.

TEST-NET EVERYWHERE. Committed fixtures and tests used the lab's real LAN
address; a test that passes because its constant matches the current lab
proves nothing about relocatability. Redirector fixtures regenerated on
RFC 5737 TEST-NET-1/2/3 plus loopback. Harness scripts no longer default the
client IP to the lab address -- client-state.sh now requires it.

SEVEN REQUIRED TESTS in tests/deployment_config.rs plus host-side coverage:
remote config never silently becomes localhost; missing advertise fails
clearly; bind may differ from advertise; changing the Blaze port changes the
redirect; changing the host updates all 200+ generated URLs with no
stragglers; no helper bypasses central config; mutations are detectable.

MUTATION TESTED, and it found a hole in the audit tests themselves. Hardcoding
utas_base, reverting the POW derivation and re-hardcoding the Blaze port were
all caught. Making the redirector read `bind` instead of `advertise` was NOT:
`advertising()` sets bind == advertise, so the two sources were
indistinguishable. That is the single most likely bypass -- the oracle really
does read bind for nucleusConnect -- so the test now forces bind != advertise
and asserts the bind address never reaches the wire. Re-mutated: caught.

Wire behaviour unchanged: oracle fixtures still current, 153 tests green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:55:50 +00:00
funman300 8aab2c0d41 adapter: FIFA 17 redirector response; Nucleus deliberately not ported
REDIRECTOR. The first hop's <serverinstanceinfo> XML, byte-for-byte against
the oracle across three advertised addresses. Owns the response only; TLS and
HTTP transport belong to a host, exactly as the Blaze adapter owns dispatch
while the sidecar owns the socket.

The <secure>0</secure> field is the client being told the second hop is
plaintext -- independent corroboration of the plaintext Blaze finding, now
expressed in code.

NUCLEUS IS NOT PORTED, and that is a finding rather than an omission.
Instrumented across every live session:

  listener bound            YES  0.0.0.0:42131 since 00:21:32
  handler logs on connect   YES  unconditional, before any parsing
  client received the URL   YES  OSDK_NUCLEUS fetched 10+ times
  client connected          NO   zero requests, including 4 full FUT flows

So the long-standing nucleusConnect=0.0.0.0 anomaly is explained: FIFA never
follows that URL on this path. The invalid address has never mattered because
nothing dials it. Porting the stub would add an untested component for no
parity gain.

TLS CONSTRAINT RECORDED, NOT RESOLVED. All 9 observed handshakes negotiated
AES256-GCM-SHA384 = TLS 1.2 with STATIC RSA key exchange. rustls supports only
forward-secret (EC)DHE suites and cannot serve that. Whether the client also
OFFERS ECDHE is unknown -- OpenSSL follows client preference by default, so
preferring static RSA does not prove it is the only option. This must be
instrumented from a real ClientHello before a TLS stack is chosen; the module
docs say so rather than guessing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:48:12 +00:00
funman300 ed0ccb8c2b blaze-host: check client sessions in BOTH network namespaces
Host-side ss cannot see the Python backend's connections: the responders run in
a container, so a client session terminates at 172.20.0.2:42130 inside its
namespace and the host only sees the NAT'd flow. 'ss | grep <client>' on the
host therefore reports nothing while a session is very much alive.

That produced a wrong precondition: 'no .105 Blaze session -- closed' was
reported while FIFA was mid-session on Python, and gate 9 was armed against a
client that had never exited. Python's own log had the answer -- it logs closes
reliably and there was no close for that session.

client-state.sh looks in both namespaces, reports Rust and Python separately,
and exits non-zero while any session is live. An unreachable container counts
as 'cannot confirm', not as 'clear'.

Fourth measurement bug in this tooling, and the most consequential: the other
three mis-COUNTED, this one mis-STATED a precondition and caused an action.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:34:46 +00:00
funman300 b40adac3fc gate-evidence: window FUT-action counts to the gate, not the whole log
'pack opens recorded: 45' appeared in the gate 8 report. The UTAS log is
cumulative across the entire deployment, so a bare count reads as if 45 packs
were opened during that gate; the real number was 1.

Now reports both, labelled, windowed from the sidecar's start time (it is
restarted per gate, so that is the gate boundary). A bare count in a gate
report will be read as belonging to that gate, so it has to be the one that
does.

Third counting bug in this tooling: the trace frame counter matched OPEN/CLOSE
markers, the capture and trace were read seconds apart during a live session,
and now this. Evidence tooling gets the same scrutiny as the code under test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:31:55 +00:00
funman300 bfb7876ed4 gate-evidence: count trace frames correctly, archive the raw capture, observe FUT actions
Three fixes, all found while closing out gate 7.

1. Frame count was wrong. It counted lines matching '^conn-', which also
   matches the OPEN/CLOSE lifecycle markers, inflating the figure by one or
   two. Compared against the capture's record count that looked like a
   capture/trace divergence (89 vs 88) when there was none: read at the same
   instant, both report 99. Evidence tooling that miscounts is exactly what
   this project cannot afford.

2. The raw capture is now copied into the evidence bundle (0600), so a gate's
   forensic bytes travel with its report.

3. FUT actions are now observed on the UTAS side. 'Known FUT action succeeded'
   is a client-side fact, but FUT actions go over UTAS -- which is never
   switched -- so the UTAS log confirms them independently of anyone's
   recollection. Gate 7's pack open shows up as:
     STORE: opened pack Special Players Pack -> 11 items

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:28:27 +00:00
funman300 55b4e54d5f gate-evidence: add the Python-side positive/negative observation
'Rust did not receive it' is weaker than 'Python did'. The redirector always
runs on Python and is never switched, so it advertises the Blaze endpoint on
every run; whether Python then receives the Blaze CONNECT it just advertised
says where the hop actually went.

This is already visible in the existing logs and settles gate 5-6 more firmly
than the sidecar record alone:

  02:02:13  Python REDIR SENT -> 10.10.0.120:42130  (to .105)
  02:02:13  Rust  conn-0005 CONNECT from 10.10.0.105
            Python received NO Blaze CONNECT

Same second, both sides: Python advertised the endpoint and did not get the
connection; Rust did. It is also the mechanism gate 8 needs in reverse.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:21:21 +00:00
funman300 fafa2f1858 blaze-host: document capture, sanitization, and what the tests do not cover 2026-08-11 02:16:11 +00:00
funman300 c84fd14cac blaze-host: make the build stamp trustworthy for evidence attribution
Committing updates refs/heads/<branch>, not the HEAD file, so watching HEAD
alone left the stamp one commit behind -- observed live, the banner read
a84a72e immediately after 2337431 was committed. build.rs now also watches the
resolved branch ref.

Belt and braces, since cargo still cannot see every source change: sidecar.sh
compares the binary's stamped commit against the tree's real HEAD at launch and
says so loudly on a mismatch. An evidence artefact that names the WRONG commit
is worse than one that names none.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:15:11 +00:00
funman300 23374312bc blaze-host: opt-in raw frame capture + auditable sanitizer
Evidence infrastructure, not protocol functionality. Built before gates 7-10
because those sessions cannot be reproduced -- a later run is a different
session, and the migration-validation runs happen once. Gates 5-6 already went
past without their bytes being recorded.

TWO LAYERS

  live FIFA traffic
    ├── raw capture      exact RX/TX bytes, mode 0600, gitignored
    └── blaze-sanitize   → repository-safe, replayable fixtures

CAPTURE. Off unless OPENFUT_BLAZE_CAPTURE names a file. Deterministic
big-endian container: 20-byte file header, then per-frame records carrying
connection id, a global monotonic sequence, timestamp, direction and the EXACT
frame bytes. RX is recorded as received; TX only AFTER a successful write, so a
record means the bytes were sent rather than intended.

Component/command/msgNum/msgType/payload length are deliberately NOT stored
beside the frame: they are already in its 16-byte header, and a redundant copy
can disagree with the bytes, leaving a reader unable to tell which is true.
Record::header() derives them, so every field the requirements name is
available without duplicating it.

SANITIZER. Redacts only the named tags in SENSITIVE_TAGS (KEY, AUTH, SESS,
MAIL, PML) and reports every substitution with path, kind and length.
Replacement is LENGTH-PRESERVING, so the TDF varint, payload length and Fire2
header are unchanged and the sanitized frame is exactly the size of the
captured one -- asserted per frame, failing rather than emitting a subtly
different conversation. Frames with nothing sensitive keep their exact wire
bytes. Payloads that will not decode are passed through and REPORTED, so a
reader knows they were never inspected rather than assuming they were checked.

TESTS. 39 in this crate. All nine required cases: capture disabled produces no
artefact; RX and TX captured exactly; ordering preserved; fragmented input
(one byte at a time) reconstructs the same frames as a single write; coalesced
input is captured as separate frames, not per-read; capture does not alter wire
output; sanitization removes a real session key from a real captured login;
malformed/truncated/wrong-version captures fail clearly; every listed sensitive
tag is provably reachable.

MUTATION TESTED. Dropping TX capture, truncating captured frames to their
header, and removing KEY from the sensitive list were each verified to turn the
suite red. One mutation was NOT caught: moving the TX capture above the write.
It is indistinguishable while writes succeed and only diverges when one fails.
That invariant is held by code placement and a comment saying so, not by a
test, and the code says as much rather than implying coverage it does not have.

Python oracle unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:14:25 +00:00
funman300 a84a72e0c0 blaze-host: A/B the RPC routes a real FIFA session actually used
The gate 5-6 live run exercised 14 RPCs the recorded fixtures never covered --
Stats, Clubs, OSDKSettings, SponsoredEvents, Messaging::fetchMessages,
Util::getTelemetryServer, Util::userSettingsLoadAll, UserSessions cmd 0x0008,
and the transport PING -- every one taking the empty-reply fallback.

That Python does the same was an inference from reading its dispatch table.
This sends those exact routes to both backends and diffs the replies:
14/14 byte-identical.

Worth keeping: the fixtures were built from what the responder implements, so
they could never have covered what the client asks for and the responder does
not. Only a live session reveals that surface, and this makes it checkable
afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:05:18 +00:00
funman300 6c102f00c0 gitignore: gate-evidence bundles are run artefacts, not source
They contain live traces and logs from a specific run; they belong with the
run, not in the tree.
2026-08-11 02:01:18 +00:00
funman300 48aa955212 blaze-host: per-gate evidence capture, separating asserted from observed
For the live FIFA gates. Records switch rules, sidecar status, log, trace and
the Python contract result into a timestamped bundle, and reports CONFIGURED
and OBSERVED state as two distinct sections.

The separation is the whole point. 'blaze-switch.sh status = ON' is an
assertion produced by the same tooling that performs the switch, and that
tooling reported a successful rollback once when none had happened. The
observed half comes from an unrelated source: the sidecar's own record of
which peers connected to it. A non-loopback peer in that log proves the
client's Blaze traffic landed on Rust without depending on reading an iptables
rule correctly.

Verified both ways: loopback-only traffic reports 'a FIFA session did NOT land
here'; a non-loopback peer reports that it observably did.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 02:00:31 +00:00
funman300 cf3ddde3a6 blaze-host: move the dirty-tree safeguard to launch and evidence time
The compiled-in dirty flag cannot be trusted for this job. Cargo does not
re-run a build script when another crate's source changes, so editing the
adapter and rebuilding the host leaves it reading 'clean' -- verified by
appending a line to the adapter and watching the flag not move.

So the stamp now only names the commit, and the real safeguards run at the
moment they matter and cannot go stale:

  * sidecar.sh checks the working tree at LAUNCH and warns.
  * check-live-parity.sh REFUSES on a dirty tree, since it produces the
    artefact a migration decision is made from. ALLOW_DIRTY=1 overrides for a
    throwaway check.

Both scope to the three migration crates, so unrelated submodule dirt does not
trigger them -- a warning that is always on is a warning nobody reads.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 01:56:43 +00:00
funman300 468b006008 blaze-host: scope the dirty-tree check to the crates the binary is built from
A whole-repo check read DIRTY permanently, because unrelated submodules carry
pre-existing modifications. A warning that is always on is a warning nobody
reads, which defeats the point: the flag exists so a mutated build announces
itself before it can be mistaken for parity evidence.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 01:55:20 +00:00
funman300 e091921b18 blaze-host: safe sidecar lifecycle, Blaze switch, build identity
Prerequisites for the live FIFA A/B. Two safeguards here exist because the
corresponding failure actually happened, not because it was imagined.

BUILD IDENTITY. build.rs stamps commit + working-tree cleanliness; the host
prints commit, tree state, profile and a fingerprint of the bundled config
table at startup, into both the log and the trace. A dirty tree prints an
explicit "do NOT treat results from this binary as parity evidence" warning.
The previous step left four sidecars running, two serving mutated builds, and
nothing in their output said so.

SIDECAR LIFECYCLE (sidecar.sh). start/stop/status/check-orphans/with. Start
refuses when any sidecar is already running or the port is busy. Stop kills,
waits, then PROVES it: PID gone AND port free AND no stray processes, failing
if any check does not hold. `with -- CMD` traps EXIT/INT/TERM so cleanup runs
however the command exits.

  Bug found and fixed while testing it: orphan detection used `pgrep -f`,
  which matched any process whose command line merely mentioned the name --
  including the shell running the test script. It now matches the resolved
  executable via /proc/PID/exe. `pgrep -x` is unusable because Linux truncates
  the process name to "openfut-blaze-h".

BLAZE SWITCH (blaze-switch.sh). Redirects Blaze to the sidecar with a scoped
NAT rule instead of editing the frozen Python oracle, whose redirector
advertises a hardcoded BLAZE_PORT = 42130. Rules match only <LAN_IP>:42130;
127.0.0.1:42130 is deliberately left alone so Python stays reachable on
loopback and the A/B compares real Python against real Rust. Verified both
directions live: LAN->Rust with the switch on, LAN->Python with it off.

  Bug found and fixed: `off` reported success while two rules remained active
  and rollback had NOT happened. It matched `--comment "tag"` with quotes this
  iptables does not emit -- and the verification used the SAME broken matcher,
  so it confirmed its own failure. A rollback that lies is worse than one that
  fails. Now matched on the bare tag, verified with iptables-save plus a
  tag-independent check that nothing still redirects the port.

  Second flaw fixed: `sidecar.sh stop` originally warned about a live switch
  and then stopped anyway, creating the exact broken state it warned about. It
  now REFUSES, with --force as the deliberate override.

The general rule this all converges on, now stated in the README: a
verification must not share the failure mode of the thing it verifies.

116 tests still passing; clippy clean; Python backend untouched and contract
suite 446/446. NAT table left clean, no orphan processes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 01:54:40 +00:00
funman300 a9eb54ae9c openfut-blaze-host: thin Blaze sidecar, live-parity with Python
Third migration step, and the one that turns fixture parity into transport
parity. A TCP host that frames a Fire2 stream, keeps one Session per
connection, calls openfut-adapter-fifa17::dispatch(), and writes the returned
frames in order. It owns a socket, a buffer, a session and diagnostics --
that is the complete list. No coins, club, packs, profiles or UTAS logic:
those belong to Core, reached through the adapter later.

NO TLS, and that is evidence-based rather than an omission. The Blaze main
port is plaintext: sending a raw Fire2 Util::ping to the running backend
returns a plaintext PingResponse, blaze_handle uses the raw socket, and only
redir_handle wraps ssl. TLS belongs to the redirector phase.

LIVE A/B AGAINST THE RUNNING PYTHON BACKEND: 101 frames across three
conversations, identical normalized traces. This is the first result in the
migration that is not purely offline. check-live-parity.sh replays the
recorded conversations against both endpoints over real sockets and diffs
volatile-masked traces; session keys and clocks are masked, so anything that
differs is behavioural.

Transport tests cover what fixtures cannot: byte-for-byte replay over a
socket, requests dribbled one byte at a time, several requests in one write,
the four-frame login burst ordered on the wire, session state persisting
across frames and NOT leaking between connections, an absurd payload length
closing the connection instead of allocating, and an undecodable body still
getting a reply. 18 tests here, 116 across the three migration crates.

MUTATION TESTED, including the comparison itself. Dropping a post-login
notification is caught by the probe (frame count) AND the diff; a same-length
content change deep inside a notification body (CTY "US"->"GB", payload 116
both sides) is caught ONLY by the trace digest. So the probe's exit code is
not the test -- the diff is, and the README says so. check-live-parity.sh was
itself verified to exit 1 under mutation.

The listen port is required configuration with no default, so the sidecar
cannot silently collide with the working container. OPENFUT_BIND stays the
advertised-config bind (the adapter derives nucleusConnect from it,
reproducing the oracle) and the listener gets its own setting, so the two are
not conflated.

Gates 1-4 pass and are re-runnable. Gates 5-10 need a FIFA client and are
listed in the README, including the Python -> Rust -> Python -> Rust
back-and-forth that proves the rollback path rather than asserting it.

Python backend untouched and still the live runtime; contract suite 446/446
after this work.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 01:42:23 +00:00
funman300 cf961603fe openfut-adapter-fifa17: FIFA 17 Blaze adapter, oracle-tested
The second migration step: the layer above the codec, deciding WHAT to say
rather than how to encode it. Sits on openfut-protocol-blaze and supplies
what that crate deliberately refuses to know.

  blaze/ids.rs           component/command/notification tables
  blaze/config.rs        injectable identity + endpoints, nothing hardcoded
  blaze/session.rs       per-connection state
  blaze/client_config.rs the fetchClientConfig tables
  blaze/responses.rs     16 Blaze::* response bodies
  blaze/dispatch.rs      (component, command) -> Vec<Frame>

Parity is tested, not asserted. fixtures/generate.py drives the real
blaze_responder_v3b.dispatch() and records 49 request->response(s)
transactions, replayed in order against a shared session per connection so
ordering-dependent behaviour is exercised: preAuth captures the locale later
ALOC fields echo, login sets the auth code getAuthToken returns. Comparison
is byte-for-byte including frame count and order.

98 tests green across both crates; clippy clean.

MUTATION TESTED, and it found a real defect in this commit's own design.
Swapping two post-login notifications and flipping one enum inside
AccountInfo both turned the suite red as intended. Hardcoding an address in
utas_base() did NOT -- the config templating substituted raw hosts directly,
making those helpers dead code that merely looked load-bearing. The table now
templates on URL-level tokens ({utas_base}, {nucleus_base},
{pow_content_url}) so they are the single place a URL shape is defined, and
the mutation is caught.

The client config table (227-243 rows per CFID) is generated from the oracle
rather than transcribed: it is reverse-engineered data, not logic, and 400
hand-copied string literals would add a typo class no reviewer can catch. The
generator substitutes real addresses back in and diffs against the oracle for
every section before writing, so the templating is verified rather than
assumed.

Reproduces one known defect deliberately: nucleusConnect is built from BIND,
not advertise, so the live split deployment tells a client on another machine
to reach Nucleus at http://0.0.0.0:42131. Confirmed against the running
container. Reproduced because it is what the only proven-working config does;
fixing it needs live validation and is a separate change. It also implies the
Nucleus stub is not reached in the current remote flow.

Blaze carries no FUT domain state -- no coins, packs, clubs or squads on this
wire -- so Session stays a session key, locale, service name, auth code and a
flag. That boundary will need defending when UTAS is migrated.

Not wired into anything. The crate answers frames; it opens no socket and
owns no runtime. The Python backend remains the live service and the oracle,
and is unmodified (contract suite still green).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 01:18:29 +00:00
funman300 cc3ecddc06 openfut-protocol-blaze: pin advertise/bind so fixtures do not depend on the shell
The responder reads OPENFUT_ADVERTISE/OPENFUT_BIND at import time and several
live payloads embed the advertised address (Blaze redirect target, RS4/POW/
roster URLs). Without pinning, regenerating on a machine that exports
OPENFUT_ADVERTISE produces different bytes and --check goes red for a reason
that has nothing to do with the codec.

Pinned to 127.0.0.1 as a placeholder so no real LAN address is baked into a
committed fixture. Not a claim about deployment: remote mode still requires an
explicit advertised address and has no loopback fallback.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 00:59:36 +00:00
funman300 a9a816e0ed openfut-protocol-blaze: generic Blaze protocol layer, oracle-tested
First Rust component of the Python -> Rust migration. Chosen first because
it is the lowest genuinely game-independent layer, it has an executable
oracle, and both existing Rust implementations of it are wrong.

Contents:
  * fire2   -- the proven 16-byte frame header, frame/stream splitting
  * heat2   -- tag packing, varints, all 11 TDF value types
  * message -- frame + decoded body, routed by NUMERIC component/command
  * diagnostics -- dumps for capture review

No FIFA 17 command tables, response schemas or notification IDs: this layer
knows 0x0009/0x0007 is component 9, command 7, not that it means
Util::preAuth. That mapping belongs to a game adapter, which is what lets a
future FIFA 18/23 adapter reuse this.

Parity is tested, not asserted. fixtures/generate.py drives the proven
Python responders (heat2.py, blaze_responder_v3b.py) and freezes 56 vectors
-- 31 of them real payloads from the responder's own builders, including
the 11.8 KB preAuth reply. tests/oracle_parity.rs replays every one
byte-for-byte. 54 tests green; clippy clean.

Supersedes two wrong framings, neither of which is removed yet:
  * fifa-blaze/crates/blaze-proto/frame.rs -- a 12-byte header with a u16
    length, nibble-packed type/options, an error field and a JUMBO flag.
    A documented guess at FIFA 23 predating the FIFA 17 recon.
  * heat2.py::build_fire2_frame -- packs >IHHHHB3s, msgId at [10:12] and
    msgType at [12]. Dead code, but its docstring still states that layout.

Confidence is carried in the types: TypeId::is_verified() reports which
layouts are capture-backed (int/string/blob/struct) and which the oracle
marks UNVERIFIED (list/map/union/varlist/objtype/objid/float), with a test
asserting the unverified ones stay flagged.

Cargo.lock is deliberately NOT included: it re-resolves ~240 lines against
the current registry even without this crate, so that churn is pre-existing
and does not belong in a foundation commit.

The Python backend remains the live runtime and is untouched. Nothing
consumes this crate yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 00:53:59 +00:00
funman300 3153a93edf fifa17-recon: drop superseded docker-side tools/data copies
fifa17-recon/tools (authoritative) and fifa17-recon/data now feed the Docker
build directly via the curated runtime-tools.list manifest. The duplicated
fifa17-python/tools+data are removed so the repo has a single source of truth;
the rebuilt openfut-fut-backend:dev image is byte-identical to the previous
deployment (verified: manifest diff empty, 446/446 contract checks pass).
2026-08-10 17:21:58 -07:00
funman300 f64106ed8b fifa17-recon: fix compose dockerfile path for relocated build context 2026-08-10 17:20:27 -07:00
funman300 9faaf12dd7 fifa17-recon: Docker build consumes authoritative tools via curated manifest
Build context moves from docker/fifa17-python/ up to fifa17-recon/ so the
Dockerfile reads the single-source tools/ and data/ trees. Only the 77 runtime
files listed in runtime-tools.list are installed into /app/tools (baseline image
minus the two git-ignored certs, regenerated in-image). memdump and recon
artifacts are excluded via fifa17-recon/.dockerignore.
2026-08-10 17:19:07 -07:00
funman300 83539e33ec fifa17-recon: take running-backend versions of 8 runtime files (direction fix)
The earlier reconcile committed the local working-tree versions of these
files, which are OLDER than the deployed backend. The running container (C)
is byte-identical to docker/fifa17-python/tools (B) and is a strict superset:
it adds profile_path_for/select_account/ensure_security_question (fut_store),
safe_header_for_log/safe_request_path/security_question_route (utas_server),
account_sync_route/_match_call/match_ready_body, plus POW balance fields and
match lifecycle support, with zero unique local functions lost.

Reconciled tree is now a strict superset of B with every shared file
byte-identical; verified via md5 map (0 missing, 0 differing).
2026-08-10 17:12:27 -07:00
funman300 695421cfd4 Merge remote-tracking branch 'origin/main' into fifa17-fut-squad-and-userinfo 2026-08-10 17:08:08 -07:00
funman300 8cba70dc90 fifa17-recon: reconcile authoritative tools with running backend (B)
- Add 8 files present in docker/fifa17-python/tools but missing from the
  top-level tree: fut_accounts.py + 7 test_*.py contracts (all committed in
  the server's docker tree; byte-identical to the running image).
- Preserve newer responder work already matching the running container:
  utas_server.py (offlineSeason), lsx_responder_v2.py (OPENFUT_BIND),
  blaze_responder_v3b.py, autopatch.py, pow_server.py, fut_store.py,
  test_fut_contract.py, fifa17-hook-m1.sh.
- Add 30 newer ghidra_queries (draft purchase/state, SBC 9-26, runtime
  registries). Local tree is now a strict superset of B with all shared
  files byte-identical.
2026-08-10 17:08:06 -07:00
root 28773e7cf1 fifa17-python: sync tools to running container state
The frozen baseline image predates two hot-patches made in the running
container after build:
* utas_server.py: FUT_MODES-gated offlineSeason block in GetHubData's club
  response (keeps the offline-season summary valid)
* test_hub_offline_season_contract.py added to /app/tools

Sync fifa17-python/tools to the running container (verified byte-identical,
237 files incl. the redir cert pair) and snapshot the live FS as
openfut-fut-backend:python-running-2026-08-10 (docker commit). A fresh build
from the committed sources now reproduces the running backend exactly
(baked SHA256SUMS.txt diffed against the container manifest: identical).
2026-08-10 23:56:58 +00:00
root 3ae5587a38 docs: baseline manifest equivalence note (pycache + cert deltas expected) 2026-08-10 23:54:59 +00:00
root 70a64e3709 fifa17-python: commit working FUT backend deployment (client/server split)
Freeze the running offline FUT backend into version control as
fifa17-recon/docker/fifa17-python/ - declarative and rebuildable from a
fresh checkout:

* OPENFUT_BIND / OPENFUT_ADVERTISE client/server split in the responders
  (lsx, blaze, roster, utas, pow) + entrypoint.sh; OPENFUT_ADVERTISE is
  required for remote mode (compose and entrypoint fail without it)
* docker-compose.yml reproducing the frozen baseline container exactly
  (env, ports incl. the 8085->8080 POW-content remap, /state bind, restart)
* .env.example / .env for site config - the LAN IP is never hardcoded in source
* tools/ + data/ staged from openfut-fut-backend:python-baseline-2026-08-10,
  verified byte-identical to the running container at freeze time
* client_arm.sh (the 105 client-side arming counterpart)
* Dockerfile bakes /app/SHA256SUMS.txt so any image is self-identifying
* docs/BASELINE-python-2026-08-10.md: frozen image/container/hash record,
  restore instructions and rebuild-equivalence procedure

Secrets (redir key/cert, .env) and runtime state (docker/state) stay gitignored.
The live container is untouched pending the .105 launcher audit.
2026-08-10 23:54:04 +00:00
268 changed files with 139574 additions and 1281 deletions
+9
View File
@@ -27,3 +27,12 @@ __pycache__/
# OS
.DS_Store
Thumbs.db
# Frozen baseline archives / inspects / manifests
/docker-backups/
gate-evidence/
# Raw Fire2 frame captures — forensic evidence, may contain session material.
# Sanitize with `blaze-sanitize` before anything leaves this machine.
*.ofcap
captures/
Generated
+254 -95
View File
@@ -457,6 +457,29 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "aws-lc-rs"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e"
dependencies = [
"aws-lc-sys",
"zeroize",
]
[[package]]
name = "aws-lc-sys"
version = "0.44.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483"
dependencies = [
"cc",
"cmake",
"dunce",
"fs_extra",
"pkg-config",
]
[[package]]
name = "axum"
version = "0.7.9"
@@ -613,19 +636,6 @@ dependencies = [
"tokio-util",
]
[[package]]
name = "blaze-ssl-async"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fec08f35919613bda0b3eb3bc772c2f793b3634133923b931874b18e1ac55de"
dependencies = [
"bytes",
"num_enum",
"rsa",
"tokio",
"x509-cert",
]
[[package]]
name = "block"
version = "0.1.6"
@@ -830,6 +840,15 @@ dependencies = [
"error-code",
]
[[package]]
name = "cmake"
version = "0.1.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
dependencies = [
"cc",
]
[[package]]
name = "codespan-reporting"
version = "0.11.1"
@@ -1062,23 +1081,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der_derive"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1187,6 +1193,12 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
[[package]]
name = "dunce"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "ecolor"
version = "0.29.1"
@@ -1457,12 +1469,6 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "flate2"
version = "1.1.9"
@@ -1547,6 +1553,12 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "futures-channel"
version = "0.3.33"
@@ -2113,9 +2125,9 @@ dependencies = [
"futures-util",
"http 0.2.12",
"hyper 0.14.32",
"rustls",
"rustls 0.21.12",
"tokio",
"tokio-rustls",
"tokio-rustls 0.24.1",
]
[[package]]
@@ -3126,11 +3138,34 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "openfut-adapter-fifa17"
version = "0.1.0"
dependencies = [
"openfut-protocol-blaze",
"rand",
"serde",
"serde_json",
]
[[package]]
name = "openfut-autopatch"
version = "0.1.0"
[[package]]
name = "openfut-blaze-host"
version = "0.1.0"
dependencies = [
"openfut-adapter-fifa17",
"openfut-protocol-blaze",
"rand",
"serde_json",
]
[[package]]
name = "openfut-bridge"
version = "0.1.0"
dependencies = [
"aes",
"anyhow",
"axum",
"bytes",
@@ -3141,13 +3176,13 @@ dependencies = [
"hyper-util",
"rcgen",
"reqwest",
"rustls",
"rustls-pemfile",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
"serde",
"serde_json",
"thiserror 1.0.69",
"tokio",
"tokio-rustls",
"tokio-rustls 0.24.1",
"tokio-stream",
"tower 0.4.13",
"tower-http",
@@ -3156,6 +3191,10 @@ dependencies = [
"uuid",
]
[[package]]
name = "openfut-common"
version = "0.1.0"
[[package]]
name = "openfut-core"
version = "0.1.0"
@@ -3181,10 +3220,40 @@ dependencies = [
]
[[package]]
name = "openfut-hook"
name = "openfut-host-config"
version = "0.1.0"
dependencies = [
"windows-sys 0.59.0",
"openfut-adapter-fifa17",
]
[[package]]
name = "openfut-http"
version = "0.1.0"
[[package]]
name = "openfut-identity"
version = "0.1.0"
dependencies = [
"parking_lot",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "openfut-import-fifa17"
version = "0.1.0"
dependencies = [
"anyhow",
"openfut-adapter-fifa17",
"openfut-core",
"openfut-identity",
"serde",
"serde_json",
"sqlx",
"tempfile",
"tokio",
"uuid",
]
[[package]]
@@ -3196,11 +3265,73 @@ dependencies = [
"dirs",
"eframe",
"egui",
"openfut-common",
"parking_lot",
"serde",
"serde_json",
"tokio",
]
[[package]]
name = "openfut-lsx"
version = "0.1.0"
dependencies = [
"aes",
"parking_lot",
]
[[package]]
name = "openfut-protocol-blaze"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "openfut-redirector-host"
version = "0.1.0"
dependencies = [
"openfut-adapter-fifa17",
"openfut-host-config",
"openfut-http",
"openfut-tls",
"openssl",
]
[[package]]
name = "openfut-roster-host"
version = "0.1.0"
dependencies = [
"openfut-adapter-fifa17",
"openfut-host-config",
"openfut-http",
"openfut-tls",
]
[[package]]
name = "openfut-tls"
version = "0.1.0"
dependencies = [
"openssl",
]
[[package]]
name = "openfut-utas-host"
version = "0.1.0"
dependencies = [
"axum",
"openfut-adapter-fifa17",
"openfut-core",
"openfut-http",
"openfut-identity",
"parking_lot",
"rand",
"reqwest",
"serde_json",
"sqlx",
"tokio",
]
[[package]]
name = "openssl"
version = "0.10.81"
@@ -3232,6 +3363,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-src"
version = "300.6.1+3.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
dependencies = [
"cc",
]
[[package]]
name = "openssl-sys"
version = "0.9.117"
@@ -3240,6 +3380,7 @@ checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
dependencies = [
"cc",
"libc",
"openssl-src",
"pkg-config",
"vcpkg",
]
@@ -3680,8 +3821,8 @@ dependencies = [
"once_cell",
"percent-encoding",
"pin-project-lite",
"rustls",
"rustls-pemfile",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
"serde",
"serde_json",
"serde_urlencoded",
@@ -3689,7 +3830,7 @@ dependencies = [
"system-configuration",
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-rustls 0.24.1",
"tower-service",
"url",
"wasm-bindgen",
@@ -3828,10 +3969,26 @@ checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e"
dependencies = [
"log",
"ring 0.17.14",
"rustls-webpki",
"rustls-webpki 0.101.7",
"sct",
]
[[package]]
name = "rustls"
version = "0.23.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06"
dependencies = [
"aws-lc-rs",
"log",
"once_cell",
"ring 0.17.14",
"rustls-pki-types",
"rustls-webpki 0.103.13",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pemfile"
version = "1.0.4"
@@ -3841,6 +3998,24 @@ dependencies = [
"base64 0.21.7",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.101.7"
@@ -3851,6 +4026,18 @@ dependencies = [
"untrusted 0.9.0",
]
[[package]]
name = "rustls-webpki"
version = "0.103.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
dependencies = [
"aws-lc-rs",
"ring 0.17.14",
"rustls-pki-types",
"untrusted 0.9.0",
]
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -4037,15 +4224,17 @@ version = "0.1.0"
dependencies = [
"anyhow",
"blaze-proto",
"blaze-ssl-async",
"bytes",
"chrono",
"futures-util",
"hex",
"rustls 0.23.43",
"rustls-pemfile 2.2.0",
"serde",
"serde_json",
"tdf",
"tokio",
"tokio-rustls 0.26.4",
"tokio-util",
"toml",
"tracing",
@@ -4063,6 +4252,12 @@ dependencies = [
"digest",
]
[[package]]
name = "sha1_smol"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
[[package]]
name = "sha2"
version = "0.10.9"
@@ -4329,8 +4524,8 @@ dependencies = [
"once_cell",
"paste",
"percent-encoding",
"rustls",
"rustls-pemfile",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
"serde",
"serde_json",
"sha2",
@@ -4784,27 +4979,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tls_codec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
dependencies = [
"tls_codec_derive",
"zeroize",
]
[[package]]
name = "tls_codec_derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tokio"
version = "1.53.1"
@@ -4849,7 +5023,17 @@ version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
dependencies = [
"rustls",
"rustls 0.21.12",
"tokio",
]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
dependencies = [
"rustls 0.23.43",
"tokio",
]
@@ -5214,6 +5398,7 @@ dependencies = [
"getrandom 0.4.3",
"js-sys",
"serde_core",
"sha1_smol",
"wasm-bindgen",
]
@@ -6152,18 +6337,6 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "x509-cert"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
dependencies = [
"const-oid",
"der",
"spki",
"tls_codec",
]
[[package]]
name = "xcursor"
version = "0.3.11"
@@ -6388,20 +6561,6 @@ name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zerotrie"
+22 -1
View File
@@ -2,9 +2,30 @@
resolver = "2"
members = [
"openfut-core",
"openfut-protocol-blaze",
"openfut-adapter-fifa17",
"openfut-blaze-host",
"openfut-host-config",
"openfut-http",
"openfut-tls",
"openfut-redirector-host",
"openfut-roster-host",
"openfut-utas-host",
"openfut-identity",
"openfut-import-fifa17",
"openfut-bridge",
"openfut-launcher",
"openfut-launcher/openfut-hook",
# The two companion services the launcher used to shell out to Python for.
"openfut-lsx",
"openfut-autopatch",
"fifa-blaze/crates/blaze-proto",
"fifa-blaze/crates/server",
]
# openfut-hook is a Windows-only version.dll proxy injected into the FIFA client.
# It MUST build with its own [profile.release] (panic="abort" — unwinding across
# the DllMain/FFI boundary into the game process is UB — plus strip + opt-level="s").
# Cargo ignores a non-root member's profile and forbids per-package `panic` overrides,
# so the hook is deliberately EXCLUDED from this workspace to build as its own root
# (this also lands its artifact in openfut-hook/target/, matching the launcher's
# config.rs default hook_dll_path). Build: cargo build --release --target x86_64-pc-windows-gnu.
exclude = ["openfut-launcher/openfut-hook"]
-250
View File
@@ -1,250 +0,0 @@
# OpenFUT — Direction Document
*The pivot: FUT lives in the app; FIFA 23 is the match renderer.*
*Supersedes the Blaze-backend approach as the primary plan. Last updated 2026-06-30.*
---
## 1. Goal (revised)
Deliver an **intuitive way to play a FUT-style experience with FIFA 23**, where:
- The entire **FUT experience** — cards, squads, packs, SBCs, coins, chemistry,
progression — lives in a **custom app** (web UI or desktop) built on the
already-complete OpenFUT Core economy backend.
- **FIFA 23 is demoted to a match renderer.** Its only job is to play a
single-player match using the squad the app built. No FUT mode, no online, no
Blaze, no EA servers.
This deliberately drops in-game FUT cards/UI (they live in the app) in exchange
for a project that **converges** instead of being gated behind months of
backend reverse-engineering.
### Why this replaces the backend plan
The status review confirmed the backend route (faking EA's online stack) is
blocked at an upstream in-process EbisuSDK gate, with Blaze/Fire2 unconfirmed
beyond it — realistically 3–6 months of expert RE that may not converge. The
app-centric route sidesteps **every** wall in that review by never making FIFA's
own FUT mode run.
---
## 2. Base mode: Career, not Kick-Off
**Career mode is the base.** Reasons:
- FLE's live-editing API (`EditDBTableField`, Freeze Lineup) is **confirmed to
work in career mode** and explicitly does NOT work in FUT/online modes.
- Career already provides the FUT-shaped scaffolding we'd otherwise fake:
persistent club, a fixture schedule, recorded results, progression across a
season.
- **Match results are written into the career DB**, making result capture a DB
read rather than a fragile live-memory grab.
**Kick-Off is the prototype sandbox.** Use it first to prove squad injection
works with nothing to corrupt (no save to break), then move the real loop onto
career. Run the foundational injection test in BOTH.
---
## 3. Core architecture: the bidirectional FLE bridge
The backbone is a **bidirectional channel between the app and a resident FLE Lua
script running inside the game.** Everything else is messages over this channel.
```
Custom App (FUT experience)
│ squad push ──────────────► ┌─────────────────────────────┐
│ │ Resident FLE Lua script │
│ ◄────────── game state │ (inside FIFA 23, career) │
│ ◄────────── match result │ - reads game state │
└────────────────────────────► │ - applies squad live │
(file-watch or local socket) │ - reads results from DB │
└─────────────────────────────┘
│
FIFA 23 plays the match
```
Three message types over the bridge:
1. **App → Game: squad push.** The app's chosen XI + stats applied LIVE via
`EditDBTableField`, replicating whatever DB write FLE's "Freeze Lineup"
feature performs (see `docs/foundational-xi-injection-test.md` — the exact
field(s) are found by diffing, not assumed). No restart, no
file-copy-reload. (File-load remains a fallback.)
2. **Game → App: game state.** The resident script polls the game's current
screen/menu state and reports "safe to apply" vs "not safe", driving a smart
Apply button in the app (see §5).
3. **Game → App: match result.** After full-time, the script reads the result
from the career DB and pushes score/scorers to the app, which awards
coins/progression. (Manual entry is the baseline fallback.)
The bridge transport can be a watched file the in-game Lua polls, or a local
socket — decided in build (see §7). Either way the *game keeps running*; a file,
if used, is just the message channel, not a reload.
---
## 4. Tiered mod scope
Build in tiers matched to risk. The core tier is all the SAME kind of DB write,
so it lands together once squad injection works.
### Tier 1 — Core writes (ride the same live DB-edit mechanism)
- **Squad / custom XI** — the load-bearing primitive (Freeze Lineup's
underlying write, replicated via script — see §6).
- **Player stats as "cards"** — card tiers, in-form versions, SBC upgrades all
expressed as written attribute values.
- **Chemistry as stat adjustment** — app computes FUT chemistry, applies it as
small stat bumps when writing players in (no in-game chem UI; that's in the app).
- **Appearance / identity** — kits, names, team assignment, so the club looks
like your club on the pitch.
- **Formation / tactics** — squad structure carries the app's build onto the pitch.
### Tier 2 — Confirm-then-add
- **Match difficulty per game** — to drive a Squad-Battles-style "this opponent is
World Class". Settable in-game trivially; programmatic drive needs confirming.
- **Match rules / modifiers** (half length, etc.) — for app-defined challenges.
### Tier 3 — Result capture (manual baseline + automated stretch)
- **Manual:** user enters the score in the app after the match. Zero RE, ships
first.
- **Automated:** resident script reads the career-DB result (or, for Kick-Off,
reads the in-match score from memory at full-time — precedent exists: the
CM cheat table's `export_season_stats.lua` already reads goals/cards from
memory via known offsets). Push to app → auto-award progression.
### Out of scope (stays in the app, by design)
- In-game FUT cards, FUT menus, pack-opening animation, chemistry board, FUT
presentation. The app is where it looks/feels like FUT.
---
## 5. The smart Apply button (state-aware)
Live DB edits only "stick" in safe menu states (the in-game "Edit Player" screen,
for example, overwrites edits). So the bridge reads game state and gates applying:
- Resident Lua script polls the game's current-screen value (a few Hz),
classifies **safe / not safe**, reports to the app.
- App's **Apply button is enabled only when the script confirms a safe state**
(squad hub, main menu); greyed otherwise.
- **Safe-by-default-OFF:** unknown state → button greyed → never a risky write.
Expand the known-safe list incrementally as states are confirmed.
- **v2 (more seamless):** instead of greying, the app always lets you click and
the script **queues** the apply, executing the moment a safe state is entered,
then confirms back. Greying is v1; queue-and-apply is v2.
`IsInCM()` is a confirmed state-read; the specific screen-state address + the
value→screen mapping is one-time reconnaissance (same technique as result reading).
---
## 6. What's confirmed vs what needs validating
**Confirmed (from FLE's own Lua API docs/wiki, checked 2026-06-30):**
- FLE live-edits the running career DB without restart, via `EditDBTableField`
(real signature: `EditDBTableField(cell)` where `cell = row["fieldname"]`
with `.value` mutated first — not the table/index/field/value form an
earlier draft of this doc assumed).
- FLE reads game state via `IsInCM()`.
- A `MEMORY` Lua class exists (`ReadInt`/`WriteInt`/`ReadMultilevelPointer`/
etc.) for arbitrary process memory — confirms the result-reading fallback
in §4 Tier 3 is a real, documented capability, not just cheat-table analogy.
- `GetPlayersStats()` is a documented function returning per-player
goals/assists/cards/etc. — a better confirmed path for match-result capture
than raw memory offsets.
- **Freeze Lineup** (Formation Editor → arrange XI → tick "Freeze Lineup" →
`Data → Save`) is FLE's actual documented mechanism for forcing a starting
XI in career mode. This **replaces** "selection bias" below.
- OpenFUT Core (economy) is complete and tested.
**Walked back — not actually confirmed:**
- "Selection bias forces specific players into the starting XI" — no such
field appears anywhere in FLE's documented Lua API or its own example
scripts. This was an unverified assumption carried over from general FIFA
modding precedent (other titles), not anything checked against FLE/FIFA 23.
See `docs/foundational-xi-injection-test.md` for the corrected plan, which
uses Freeze Lineup instead.
**Needs validating (the foundational tests — see §7):**
- Whether Freeze Lineup actually holds into a played match (FLE's wiki
documents the feature but not a live-match test of it).
- What DB table/field Freeze Lineup's `Data → Save` actually writes — it's
GUI-only and undocumented at that level; finding it is part of the
foundational test.
- Whether that write can be replicated by a script (`EditDBTableField`) well
enough to drive it from an EXTERNAL trigger, not just the Formation Editor
UI — required for the app↔game bridge.
- The app↔game bridge transport (file-watch vs socket) works cleanly under the
run setup.
- The screen-state address + safe/not-safe classification (FLE's `Events`
API page exists in the wiki index but its content is currently empty/
undocumented — this is more open than previously assumed).
- Result read-back from the career DB after a match.
**Standing caveat:** the whole stack rides on **EAAC staying neutralized**
(FLE's fake-launcher bypass). If a game update re-enables it, hooks fail. Keep
game updates off; confirm neutralized state each session.
---
## 7. Build order / next steps
Each is a bounded, verifiable step. Do them in order; later ones depend on
earlier answers.
1. **FOUNDATIONAL TEST — live custom XI in career.** Confirm Freeze Lineup
holds into a played match, reverse-engineer the DB write it makes, then
replicate that write from a script so it can be triggered externally
instead of through the Formation Editor UI. See
`docs/foundational-xi-injection-test.md` for the full procedure. *Done =
a script-driven write produces a match that fields the squad you
specified.* Everything rests on this.
2. **Pick the bridge transport.** Decide file-watch vs local socket for app↔game
messaging; implement the minimal app→game squad push. *Done = app sends a
squad, the resident script receives and applies it.*
3. **Game-state reader + smart Apply.** Find the screen-state address, classify
safe/not-safe, expose to the app, gate the Apply button. *Done = button greys
when you enter a match/edit screen, enables in the squad hub.*
4. **Result read-back.** Read the career-DB match result post-game, push to app,
award progression. Manual entry ships alongside as the fallback. *Done = app
updates coins from a played match.*
5. **Tier 1 breadth.** Extend the squad push to carry stats, appearance,
formation (same write mechanism). *Done = the club looks and plays like the
app's build.*
6. **Tier 2 + economy loop polish.** Difficulty drive, challenges, and the full
pack → SBC → squad → match → reward loop closed end-to-end.
### Decision still open
- **App form factor:** web UI vs desktop app. This affects the bridge transport
(a desktop app can hold a local socket more naturally; a web UI leans toward a
small local helper/file-watch). Decide before step 2.
---
## 8. Provenance
Clean-room throughout. This route relies on FLE's documented public API and the
game's own supported career mode — no EA backend, no Blaze, and nothing derived
from leaked EA source. The earlier backend RE remains clean-room and is preserved
as a spec artifact; it is simply no longer the primary path.
---
## 9. One-paragraph summary
OpenFUT becomes a **FUT companion app that uses FIFA 23 as a match engine.** The
app owns the entire FUT experience; a resident FLE Lua script in career mode
applies the app's squad live (no restart), reports game state to drive a safe
Apply button, and reads match results back to feed progression. This sidesteps
every backend wall, runs on confirmed FLE capabilities, builds on the finished
economy core, and delivers the intuitive, offline, FUT-flavored loop that is the
actual goal.
-108
View File
@@ -1,108 +0,0 @@
# FIFA 23 PC Startup Flow (Offline / Proton)
Observed via FLE log, hook log, and file inspection on 2026-06-26.
## Launch chain
```
umu-run / Steam → FIFA23.exe (via Proton/Wine)
│
├─ DLL load order (before entry point)
│ ntdll.dll, kernel32.dll, ws2_32.dll …
│ version.dll ← our hook DLL slot (loads here)
│ FIFALiveEditor.DLL ← injected by FLE launcher after ~100 ms
│
├─ anadius / LSX emulator (anadius64.dll)
│ Fakes EA App / Origin session
│ Reads HKLM\SOFTWARE\Wow6432Node\Origin\ClientPath
│ Writes AppData\Local\anadius\LSX emu\achievement-*.xml
│ Provides fake PersonaId=1144668899 / UserId=1000200030000
│
├─ EA Anti-Cheat (EAAntiCheat.GameServiceLauncher.exe)
│ Spawns as child; checks EAAntiCheat.cfg
│ Not active in offline/cracked builds (FakeEAACLauncher present)
│
└─ FIFA23.exe entry point
Frostbite engine init (BuildDate 2023-07-05, changelist 5417699)
Reads Data\initfs_Win32 ← Frostbite package manifest
Reads Data\layout.toc ← file-system layout
Reads Patch\initfs_Win32 ← patches on top of base
Reads Documents\FIFA 23\fifasetup.ini ← display settings
Reads Data\locale.ini ← language table
Reads Data\db_meta.xml (via FLE) ← DB schema for all tables
```
## Phase timing (observed, single machine)
| Phase | Time after launch | Trigger |
|------------------------------|-------------------|----------------------------------|
| DLL load + FLE injection | 0 – 0.3 s | OS loader |
| Engine + DirectX init | 0.3 – 5 s | FIFA23 entry point |
| "Press any key" splash | ~5 s | First rendered frame |
| Main menu | ~25 s | After key press |
| FUT mode entry (attempted) | user-driven | User selects FUT tile |
| Network calls to EA services | at FUT entry | DirtySDK / EAWebKit |
## Files read at startup (observed)
| File | Format | Purpose |
|------|--------|---------|
| `Data/initfs_Win32` | Frostbite pkg | Base asset manifest |
| `Data/layout.toc` | Frostbite TOC | File layout index |
| `Patch/initfs_Win32` | Frostbite pkg | Patch layer |
| `Data/locale.ini` | INI | String localisation |
| `Data/db_meta.xml` | XML | DB schema (loaded by FLE) |
| `Data/id_map.json` | JSON | Player/team ID→name map |
| `Data/char_conv.json` | JSON | Character conversion table |
| `Documents/FIFA 23/fifasetup.ini` | INI | Display/audio settings |
| `AppData/Local/Temp/FIFA 23/_replay0.bin` | binary | Replay buffer |
| `anadius.cfg` | VDF | Fake EA persona config |
| `AppData/Local/anadius/LSX emu/achievement-*.xml` | XML | Achievement state |
## Files written during a session (observed)
| File | When written | Content |
|------|-------------|---------|
| `Documents/FIFA 23/settings/Settings*` | Main menu reached | FBCHUNKS — controller/display prefs |
| `Documents/FIFA 23/settings/ProfileOptions` | Profile load | FBCHUNKS — 1.5 MB profile blob |
| `Documents/FIFA 23/filesystemcache/survey.state` | Startup | Empty state file |
| `Documents/FIFA 23/filesystemcache/atlPlayTimeJson/playtime_*.json` | Ongoing | Playtime tracking |
| `FIFA 23 Live Editor/config.json` | FLE ready | FLE settings (rewritten each session) |
| `Logs/log_DD-MM-YYYY.txt` | Throughout | FLE debug log |
## Save file formats
### FBCHUNKS (Frostbite chunk container)
- Magic: `46 42 43 48 55 4E 4B 53` (`FBCHUNKS`)
- Byte 8: version (01 seen)
- Offset 0x12: null-terminated label string (e.g. "Personal Settings 1", "Career - Player Progress 1")
- Remainder: compressed/binary chunk data — no public spec; requires Frostbite tooling to fully parse
- Tools: [Frosty Tool Suite](https://github.com/CadeEvs/FrostyToolSuite) can read/write these
### fifasetup.ini
- Plain `KEY = VALUE` ini, fully human-readable
- Safe to edit (display resolution, locale, vsync)
## Network calls at FUT entry (observed with iptables redirect)
Traffic pattern captured before changing strategy:
- Multiple TLS connections to port 443 (destination: EA servers, resolved as various EA IPs)
- TLS 1.3, AES-256-GCM (DirtySDK's copy of ProtoSSL, inline in FIFA23.exe)
- No SNI sent (DirtySDK does not set `server_name` extension)
- Connections originate from Wine/Proton network stack via Linux kernel TCP
Specific EA hostnames used (from openfut-bridge captures, not decoded from TLS):
- `fut.ea.com` (FUT API)
- `accounts.ea.com` (auth)
- `gateway.ea.com` (entitlements)
- `pin-river.data.ea.com` (telemetry)
## Key FLE Lua API hooks
FLE injects `FIFALiveEditor.DLL` and exposes a Lua engine that can:
- Read any in-memory DB table via `GetDBTableRows(tableName)`
- Write any cell via `EditDBTableField`
- Query career mode state via `IsInCM()`
- Get player/team names via `GetPlayerName`, `GetTeamName`
This is the primary safe integration path (see `fut-integration-options.md`).
-191
View File
@@ -1,191 +0,0 @@
# Foundational test — live custom XI via Freeze Lineup
**Status: PENDING — test has not yet been run.**
This is build-order step 1 from `docs/direction.md`: the test everything else
in the direction pivot depends on.
## What changed since the first draft of this doc
The first version of this test guessed at a "selection bias" DB field and a
candidate squad/lineup table name, based on general FIFA-modding precedent
that turned out not to hold for FLE's documented API — no such field appears
anywhere in FLE's actual Lua API docs or its own example scripts. While
researching an unrelated hotkey issue, a **confirmed, FLE-documented**
mechanism for forcing a starting XI turned up instead: the **Formation
Editor's "Freeze Lineup" feature** (FLE wiki, `Formation-Editor.md`):
> This feature can be used in player career mode if you want to manage the
> starting lineup of your team. Can be also used in manager career mode to
> manually manage your next opponent's starting lineup.
Steps (GUI, no scripting): open Formation Editor for a team → arrange players
on the pitch → tick **Freeze Lineup** → `Data → Save`.
This is real and documented, but it's GUI-only — there is no Lua function for
it, and what DB write it actually performs under the hood is undocumented.
This test is now two phases: confirm the GUI feature works at all, then
reverse the DB write it makes so it can be replicated programmatically
(required for the app→game bridge in build-order step 2, which needs this
driven from outside the game, not from a person clicking checkboxes).
Also fixed in this pass: `EditDBTableField`'s real signature, confirmed from
FLE's own docs and `lua/scripts/99ovr_99pot.lua`, is
`EditDBTableField(cell)` where `cell` is `row["fieldname"]` with `.value`
mutated in place — **not** `EditDBTableField(table, row_index, field, value)`
as originally (incorrectly) written into the first draft of the injector
script.
## What this test settles
Whether a *specific, externally-chosen* 11 players can be forced into a
career (or Kick-Off) match's starting lineup, live, with no restart — and
whether the mechanism that does it (Freeze Lineup's underlying DB write) can
be driven by a script instead of a person clicking through the Formation
Editor UI.
If Freeze Lineup itself doesn't actually hold under match start (the wiki
doesn't show it being tested against a live match, only "you should be able
to see... when you play against them"), the whole bridge architecture in
`docs/direction.md` §3 needs rethinking — there is no other documented
mechanism for forcing a lineup.
## Prerequisites
- FIFA 23 launched normally (FLE injected, EAAC neutralized — same baseline
as `track-c-fut-table-test.md`)
- A career save loaded (Freeze Lineup is documented for career mode
specifically — confirm separately whether it does anything in Kick-Off,
don't assume it does)
- Note 11 player IDs from your club (`tools/squad-exporter/export_squad.lua`
output, `playerid` field) that are NOT currently your starting XI
## Phase 1 — confirm Freeze Lineup actually holds into a match
This has zero scripting and should be done first since everything else is
wasted effort if it fails.
1. Open the Live Editor overlay (F9, or `Windows → Settings` from the
overlay's own menu bar if the hotkey isn't registering — see the umu/Wine
hotkey note below).
2. `Features → Teams` → find your team → `Edit`.
3. `Team → Formation` to open the Formation Editor.
4. Swap players around on the pitch so the XI differs from your current
actual starting XI in some checkable way (e.g. swap two outfield players'
positions, or bench/start a specific player).
5. Tick **Freeze Lineup**.
6. `Data → Save`.
7. Hide Live Editor (F9), save your career **on a new slot** (don't overwrite
your main save in case this corrupts something), exit to main menu, reload
that save, and check the team's lineup screen / play a match and watch who
starts.
**Record in the Results table below whether the frozen lineup actually took
the pitch.** If not, stop here — Phase 2 is moot.
## Phase 2 — find the underlying DB write
Only proceed if Phase 1 confirmed Freeze Lineup works.
1. In FLE's Lua Engine, run `tools/squad-injector/snapshot_lineup_tables.lua`.
This dumps every DB table whose name contains `squad`, `lineup`,
`formation`, `tactic`, `teamsheet`, `selection`, `players`, or `teams` to
`C:\FIFA 23 Live Editor\openfut_snapshot_<timestamp>.json`. Note this
filename — this is your **before** snapshot.
2. Without restarting or reloading, repeat the Formation Editor steps from
Phase 1 (steps 2–6 only — open Formation Editor, change the lineup, tick
Freeze Lineup, `Data → Save`). Don't save/reload the career between
snapshot and this step — keep it to a single live session so the diff
isn't polluted by other state changes.
3. Run `snapshot_lineup_tables.lua` again. This is your **after** snapshot.
4. Copy both JSON files out of the Wine prefix (same path pattern as
`track-c-fut-table-test.md`: `~/Games/umu/.../drive_c/FIFA 23 Live
Editor/`) and run:
```bash
python3 tools/squad-injector/diff_snapshots.py before.json after.json
```
5. The output shows exactly which table(s) and field(s) changed. This is the
real, confirmed write Freeze Lineup performs — record it in the Results
table below.
## Phase 3 — replicate the write via script
1. Open `tools/squad-injector/apply_lineup_write.lua` and fill in
`TARGET_TABLE` and `TARGET_FIELDS` using Phase 2's diff output.
2. Edit `C:\FIFA 23 Live Editor\openfut_test_xi.json`:
```json
{
"team_id": 12345,
"xi": [
{ "player_id": 111111, "position": 0 },
{ "player_id": 222222, "position": 5 }
]
}
```
Use 11 entries. Position codes are **confirmed numeric 0–27**
(`GK=0, SW=1, RWB=2, RB=3, RCB=4, CB=5, LCB=6, LB=7, LWB=8, RDM=9, CDM=10,
LDM=11, RM=12, RCM=13, CM=14, LCM=15, LM=16, RAM=17, CAM=18, LAM=19,
RF=20, CF=21, LF=22, RW=23, RS=24, ST=25, LS=26, LW=27`) — from
`lua/scripts/export_season_stats.lua`'s `get_pos_name` table in FLE's own
repo, not a guess.
3. Run `apply_lineup_write.lua` from FLE's Lua Engine.
4. Repeat the save-to-new-slot / reload / check-lineup verification from
Phase 1, but this time without ever opening the Formation Editor — the
write was made entirely from the script.
## Classification criteria
### "Confirmed — full mechanism works"
Phase 1 holds, Phase 2 finds a clean diff, Phase 3's scripted write produces
the same in-match result as the manual GUI path.
**Verdict:** Build-order step 1 done. Proceed to step 2 (bridge transport) in
`docs/direction.md`.
### "GUI works, script doesn't"
Phase 1 holds but Phase 3's replicated write doesn't stick, even though the
diffed fields matched what changed in Phase 2.
**Verdict:** Freeze Lineup likely does more than a single DB field write
(e.g. an internal engine call beyond `EditDBTableField`'s reach, or a second
write the diff missed because it happened in a table outside the `KEYWORDS`
filter in `snapshot_lineup_tables.lua` — widen the filter and redo Phase 2).
### "Freeze Lineup doesn't hold at all"
Phase 1 fails — the lineup reverts to the game's own AI-picked XI regardless.
**Verdict:** No confirmed mechanism exists for forcing a lineup. This kills
the bridge architecture as designed in `direction.md` §3 and needs a return
to first principles — there is no fallback documented anywhere in FLE's wiki
for this specific case.
## A note on the umu/Wine F9/F11 hotkey issue
If FLE's F9 (hide/show) hotkey isn't registering under umu, this is plausibly
a Wine keyboard-hook limitation (FLE's global hotkey detection likely uses a
low-level hook that doesn't translate cleanly through Wine's input layer) —
not something documented anywhere in FLE's own troubleshooting docs, which
don't mention Linux/Wine at all. F11 specifically has **no documented FLE
function** — F9 is the only documented toggle. Workaround: click directly
into the FLE overlay window (it should still be visible/clickable even if the
hotkey doesn't fire) and use its own menu bar instead of relying on the
hotkey.
## Results
*(To be filled in after the test is run.)*
| Field | Value |
|---|---|
| Date run | — |
| Phase 1: Freeze Lineup holds into a match? | — |
| Phase 2: table(s)/field(s) changed | — |
| Phase 3: scripted write reproduces Phase 1 result? | — |
| **Classification** | **PENDING** |
-136
View File
@@ -1,136 +0,0 @@
# FUT Integration Options
How to connect FIFA 23 to the OpenFUT local simulator, ranked by safety and feasibility.
## Option A — FLE Lua scripting (RECOMMENDED)
**What it does:** Use FIFA Live Editor's in-memory Lua API to read and write the game's
database tables at runtime. FLE is already injected; no additional hooking needed.
**Why it's the right path:**
- Fully offline, no EA servers touched
- FLE is already trusted by the user (it's the launch mechanism)
- `GetDBTableRows` / `EditDBTableField` expose the full Frostbite DB in memory
- Scripts run inside the game process; no IPC complexity
- Same mechanism used by modders for career mode edits today
**Integration design:**
```
openfut-core (SQLite)
│
│ HTTP REST (localhost)
▼
openfut-bridge (port 8080, plain HTTP, no TLS)
│ pulls club/squad/player data as JSON
▼
FLE Lua bridge script
│ calls GetDBTableRows, EditDBTableField
▼
FIFA 23 in-memory DB (Frostbite)
```
The Lua script polls openfut-core's REST API at intervals (or on FUT menu entry)
and writes simulator data (coins, items, squad) into the appropriate DB tables.
**Tables likely involved (to verify with export_squad.lua):**
| Table | Expected FUT content |
|-------|---------------------|
| `players` | Player attributes (OVR, potential, stats) |
| `teams` | Club identity, stadium, colors |
| `fut_clubs` | FUT club record (if in memory when FUT loads) |
| `fut_items` | Card inventory (if in memory) |
| `fut_squads` | Active squad (if in memory) |
**Steps to implement:**
1. Run `tools/squad-exporter/export_squad.lua` from FLE Lua Engine while in FUT to discover which tables are live
2. Map openfut-core's data model to the discovered table fields
3. Write a Lua polling script that fetches `/api/v1/club`, `/api/v1/squad`, etc. from openfut-core and calls `EditDBTableField` to populate them
4. Optionally add a small HTTP client to the Lua script using LuaSocket (FLE ships with Lua 5.4)
**Limitations:**
- Changes are in-memory only; they reset on game restart (acceptable for a simulator)
- Only works while FLE is running (always true in our setup)
- FUT tables may only be populated when the FUT hub is loaded; test with the exporter
---
## Option B — Local save file injection (career mode proxy)
**What it does:** Generate or modify offline career mode save files that contain FUT-like
squad/player data, using Frostbite's FBCHUNKS format.
**Feasibility:** Medium
- FBCHUNKS format is not publicly documented but has been partially reverse-engineered by the Frosty Tool Suite project
- Career saves are 16 MB — large and complex
- Changes take effect only after a game restart
**Best use:** Pre-populating a career club with the same players as the FUT simulator squad, so offline Squad Battles use "your" players.
**Steps:**
1. Use Frosty Tool Suite to open a career save and map the schema
2. Build a Python exporter that writes a valid FBCHUNKS save with simulator squad data
3. Test: replace the career save, launch FIFA, verify squad is correct
---
## Option C — Local companion web UI
**What it does:** The user manages their FUT simulator entirely in a web browser (openfut-core already has this). A button exports the current squad/club state to a format that a Lua script or file injector can consume.
**This is already implemented** — openfut-core serves the FUT simulator REST API. The missing piece is the Lua bridge script (Option A) that reads from it.
---
## Option D — Local proxy for non-secured local calls only
**What it does:** Intercept FIFA 23's calls to `localhost:*` or a known local endpoint (not EA servers) and respond with simulator data.
**Feasibility:** Low value in isolation
- FIFA 23 does not make calls to localhost in normal operation (except EA App on port 10853)
- All FUT API calls go to EA's servers over TLS
- Intercepting those would require the approach we explicitly ruled out
**Not recommended as a primary path.** Could be combined with Option A if the Lua script exposes a local socket that a coordinator process writes to.
---
## Option E — Memory bridge (Cheat Engine / FLE offsets)
**What it does:** Use known memory offsets (FLE's `offset_cache.json`) to read/write FUT state directly in FIFA23.exe's heap.
**Feasibility:** Medium — FLE already does this for career mode
- FLE's `offset_cache.json` contains addresses for many game structures
- FUT in-memory structs are separate from career structs and may not be mapped yet
- This is fragile (offsets change with game updates)
**Not recommended** unless Options A and B both fail — too brittle.
---
## Recommendation
**Start with Option A (FLE Lua scripting).**
1. Run `tools/squad-exporter/export_squad.lua` in-game to discover which DB tables exist in FUT mode
2. Use `tools/file-watch-diff/watch.sh` to snapshot file state entering FUT and identify any new local files
3. Use `tools/network-metadata-logger/netlog.sh` to log which EA hosts FIFA contacts at FUT entry (metadata only, no decryption)
4. Map findings back to openfut-core's data model
5. Implement the Lua bridge script that calls openfut-core's REST API and writes to discovered tables
If FUT tables are not exposed by FLE's DB API (they may not be — FUT data lives server-side in online mode), fall back to **Option B** (career save injection) to provide a squad that mirrors the simulator's club.
---
## Safety boundary
The following are out of scope and must not be implemented:
- Decrypting or inspecting EA's TLS traffic
- Spoofing EA domain names or impersonating EA servers
- Sending modified clients to EA's production services
- Bypassing EA App login or account verification
- Anything that could constitute online cheating or violate EA's ToS for online play
All integration must remain local/offline/single-player.
-208
View File
@@ -1,208 +0,0 @@
# OpenFUT Status Review
*Generated 2026-06-30 — read-only stocktake, no code changed.*
---
## Executive Summary
OpenFUT has a mature offline FUT economy backend (Core, 25 phases, fully functional in
isolation) and a sophisticated hook DLL that loads into FIFA 23, redirects EA hostnames
to loopback, and bypasses TLS certificate verification. The Blaze/ProtoSSL layer is
structurally ready: framing code exists, a TLS listener runs, cert-verify is patched.
However the project is currently blocked before any Blaze traffic is ever seen.
The fundamental problem is that FIFA 23 submits `GoOnline` to EbisuSDK and then
**waits for an asynchronous ONLINE_STATUS_EVENT push** from the EA-app LSX server —
a push that current code never sends. Every approach tried so far (flipping poll
return values, forcing the state flags, read-only probes) confirms the gate is
event-driven, not poll-driven. The Blaze captures directory contains six empty files.
No Fire2 frame from FIFA 23 has ever been decoded. Until the ONLINE_STATUS_EVENT push
is synthesized and delivered correctly, Milestones 2–7 are all waiting on the same
single wall.
---
## 1. Proven vs Assumed
| Claim | Status | Evidence |
|---|---|---|
| FIFA 23 uses DirtySDK / ProtoSSL | **Proven** | String scan hit `ProtoSSLSend`, `ProtoSSLRecv`, `gosredirector` in FIFA23.exe memory (Task 1) |
| `version.dll` loads and runs hook code | **Proven** | `hook.log` written at DLL_PROCESS_ATTACH |
| `getaddrinfo` IAT hook redirects EA domains to loopback | **Proven** | Hook log records every EA `getaddrinfo` call; connect_hook log confirms port redirects |
| ProtoSSL cert-verify prologue found and patched (FIFA23.exe) | **Proven** | ssl_patch.rs prologue confirmed at file offset 0xf0c850; hook log "ssl: main exe cert-verify patched" |
| ProtoSSL cert-verify patched in EAWebKit.dll | **Proven** (if loaded) | Lazy patch fires on first EA getaddrinfo call; hook log message confirms |
| Gate is upstream of DirtySDK — no DNS/connect fires on FUT entry | **Proven** | getaddrinfo, connect, WSASend/Recv hooks all show zero external traffic during "connecting to EA Servers" |
| `GoOnline` is called by the game | **Proven** | Read-only detour on `anadius64.dll+0x2BB90` confirmed hit |
| anadius returns GoOnline success | **Proven** | Handler observed returning successfully; game still retries every ~7 s |
| Gate is downstream of GoOnline | **Proven** | GoOnline called + returns success; no Blaze connect follows |
| Connection-state function: `GetInternetConnectedState @ anadius64.dll+0x27790` | **Proven** | Located via anadius LSX command-registration table; two-flag branch decoded (`+0xCAB1A`, `+0xCAB1B`) |
| Gate is event-driven (game waits for async push, not a poll return) | **Proven** | Forced both state flags AND GoOnline return to "1"; game kept retrying; worker-thread stack scan confirms handler runs on anadius IOCP thread, not FIFA's thread |
| GoOnline runs on anadius worker thread, not FIFA's call thread | **Proven** | Stack scan from inside detour found zero FIFA23.exe frames, sp ~2.4 KB from thread stack top |
| `protossl-scan` live toolkit is exhausted for finding GoOnline in FIFA23.exe | **Proven** | No `"GoOnline"` string in image; worker-thread call stack has no FIFA frames; jmpscan yields ~3875 hits (overwhelmingly data false positives) |
| FIFA 23 redirector config references `Authorization:` header (Nucleus token) | **Proven** | Found in FIFA23.exe .rdata pointer table @ `+0x83FC858` |
| openfut-core REST API complete and tested | **Proven** | 25 phases, 15 migrations, passing integration tests |
| Bridge LSX server starts and handles request-response | **Proven** (code) | `openfut-bridge/src/lsx.rs` + `main.rs` — server starts on 127.0.0.1:3216 |
| Bridge LSX server ACTUALLY receives FIFA's LSX connections | **UNCONFIRMED** | anadius may intercept the same calls in-process before the TCP connection reaches the bridge |
| Bridge LSX server `GetInternetConnectedState → connected="1"` unblocks the gate | **UNCONFIRMED (known to fail in-process)** | Flipping the value via anadius in-process failed; bridge path not yet confirmed working |
| ONLINE_STATUS_EVENT push XML format | **UNKNOWN** | No capture; format not derived |
| Fire2 framing is correct for FIFA 23 | **UNCONFIRMED** | Implemented based on post-2012 EA convention; all blaze captures are empty (0 bytes) |
| Blaze component / command IDs for FIFA 23 | **UNKNOWN** | Zero captures; dispatch table entirely empty placeholders |
| ProtoSSL recv-injection convention (non-blocking return values etc.) | **UNCONFIRMED** | Never reached M4; recv_hook module removed from active install path |
| FUT REST endpoint paths in mapper.rs | **SPECULATIVE** | Based on community knowledge of older FIFA titles; the one actual capture in `captures/` is an early GET from before the Blaze strategy |
| FLE Lua API exposes FUT DB tables in memory | **UNKNOWN** | `export_squad.lua` has never been run; FUT data may only exist server-side in online mode |
---
## 2. Milestone Status
| Milestone | Status | Blocker | Depends on unconfirmed assumption? |
|---|---|---|---|
| **M1** — Locate connection-state decision point | ✅ Done | — | No |
| **M2** — Flip gate, force "connected" | ⛔ Blocked | Game waits for async ONLINE_STATUS_EVENT push; no current code sends it | Yes — unknown event XML format |
| **M3** — First ProtoSSL plaintext on Blaze connection | 🔲 Not started | Depends on M2 | Yes — Fire2 framing unconfirmed |
| **M4** — Answer redirector + decode first Fire2 frame | 🔲 Not started | Hard wall: Fire2 framing, recv-injection convention, component/command IDs all unconfirmed | Yes — all three unknown |
| **M5** — Blaze preauth / login / postauth | 🔲 Not started | Depends on M4 | Yes — Blaze auth TDF body layout unknown |
| **M6** — FUT entry + hub load | 🔲 Not started | Depends on M5; also requires FUT REST response shapes confirmed | Yes — endpoint paths speculative |
| **M7** — Squad Battles (AI FUT) | 🔲 Not started | Depends on M6 | Yes |
**Note on roadmap.md wording:** Under M2–M4, roadmap.md uses `**Done (observable):**` bullets. These describe the *success criterion* for each milestone, not an achieved state. The authoritative status is in `connection-gate-findings.md` (M2 attempts failed; M3/M4 never started). The roadmap has not been updated to reflect M2 failure.
### M4 is the first hard wall in detail
Even assuming M2 is solved, M4 requires three unconfirmed things simultaneously:
1. **Fire2 framing** — the 12-byte header layout is assumed; if FIFA 23 uses an older Fire variant or a custom delta, the codec will misparse every packet.
2. **ProtoSSL recv-injection** — delivering responses to the game via recv hook requires knowing what return values and buffer conventions ProtoSSL expects; recv_hook.rs exists but is not installed.
3. **Blaze component/command IDs** — the dispatch table is entirely empty; we cannot answer any request until IDs are known from captures.
All three are resolved by getting one real captured frame. M4 is primarily a capture problem, not a decoding problem — once bytes exist, the framing and IDs are immediately readable.
---
## 3. Blockers, Risks, Unknowns
### Blockers (stop progress now)
1. **ONLINE_STATUS_EVENT push not synthesized** *(M2 wall)*
The game calls GoOnline, gets success, then waits indefinitely for a push event on the LSX socket that never arrives. This is the single gate blocking all Blaze work. Options: (a) trace the event format via Ghidra on FIFA23.exe (xref `ONLINE_STATUS_EVENT` string + the game's EbisuSDK listener), (b) RE anadius's LSX event-send path (find what it would push in an "online" scenario), (c) brute-force push candidate event XMLs and observe whether the game advances.
2. **Bridge LSX server delivery unconfirmed** *(architectural risk converted to blocker)*
The hook passes port 3216 connections through, assuming the bridge LSX server on the Linux host receives them. If anadius's in-process hooks intercept the winsock calls before they reach the TCP stack, the bridge server is never reached. This must be confirmed by checking `openfut_hook.log` for a getaddrinfo on the LSX host, or by observing the bridge server's accept logs.
### Risks (could derail later)
3. **Fire2 framing wrong** *(M4 risk)*
If FIFA 23 uses Fire (pre-2012) or a modified frame layout, the codec misparses. Mitigation: the server has a `Raw` fallback mode for capturing raw bytes when framing fails.
4. **Secondary auth-token gate** *(M5 risk)*
`connection-gate-findings.md` noted the redirector request carries an `Authorization:` header. M1's final conclusion said `GetAuthCode` returns a fake token that appears accepted — but this was inferred, not confirmed by seeing the redirector request actually constructed with that token.
5. **EAAC not fully neutralized** *(persistent risk)*
`FakeEAACLauncher` bypasses the anticheat launcher. The hook DLL is unsigned. If EAAC is ever active (e.g., after a game update re-enables it), all hooks fail silently. Marked as "not active in offline/cracked builds" — assumed, not confirmed on every launch.
6. **FUT REST response shapes wrong** *(M6 risk)*
The 61 endpoint mappings in mapper.rs and the shaper stubs in shaper.rs are based on community guesses about older FIFA FUT APIs, not FIFA 23 captures. Response JSON shapes may differ enough to cause the client to fail silently or crash.
### Unknowns (open questions)
7. **ONLINE_STATUS_EVENT XML format** — exact tag names, field order, sender attribute, and any nonces/tokens required.
8. **GoOnline event sequence** — whether ONLINE_STATUS_EVENT alone is sufficient or a sequence of events (e.g., PROFILE_EVENT, LOGIN_EVENT, COMMERCE_EVENT) is expected.
9. **Whether FLE exposes FUT DB tables** — FUT card inventory and squad data likely live server-side in online mode; FLE may not surface them for in-process editing.
10. **Blaze component/command IDs for FIFA 23** — entirely unknown; no captures.
11. **openfut_hook.log current content** — we have the code but no log output in any document. Whether the current hook (with connect, ssl_patch, tls_bypass, WSAIoctl, origin_spy all installed) fires correctly and what it observes is unverified in this review.
---
## 4. Track Comparison
### Track A — Full EA-backend fake (M1–M7, playable FUT vs AI)
**What it delivers:** The FIFA 23 FUT hub loads from OpenFUT Core; Squad Battles matches play and reward economy items.
**Effort:** Research-grade. Minimum path: synthesize ONLINE_STATUS_EVENT (unknown format, 1–2 weeks of RE), then capture Fire2 frames (days once M2 is solved), then implement Blaze auth handlers (weeks), then implement FUT entry (weeks), then Squad Battles (weeks). Realistic minimum: 3–6 months of expert RE work.
**Proven support:** Hook loads and redirects correctly. TLS bypass patched. Core economy backend complete. Blaze framing code and TLS listener exist.
**Assumed:** Fire2 framing correct; component/command IDs discoverable from captures; FUT REST shapes close enough to community guesses; no additional undiscovered gates.
**Evidence for:** Architecture is coherent. The M1 finding (gate precisely named and decoded) was achieved cleanly. The in-process hook approach is validated.
**Evidence against:** M2 was attempted and failed with the in-process approach. The event-driven architecture adds a full EbisuSDK emulation layer before even one Blaze byte is seen. The live toolkit is exhausted (Path A verdict); Ghidra-level work on a 505 MB binary is required. Six capture files with zero bytes.
---
### Track B — Clean-room spec deliverable (M1–M5 documented)
**What it delivers:** A documented map of the connection gate, LSX event sequence, Blaze auth surface (transport, framing, gate conditions, component IDs, TDF schemas). Valuable as an archival/community artifact even if Track A stalls.
**Effort:** Medium. M1 is done. M2–M5 documentation emerges as a by-product of engineering work. The spec itself (writing) is lightweight; the engineering to produce the captures is the cost.
**Proven support:** M1 complete and documented. connection-gate-findings.md is already a high-quality spec artifact.
**Assumed:** Same as Track A for the unconfirmed values, but the spec can mark them `TODO/CONFIRM` rather than needing to implement them.
**Evidence for:** The clean-room constraint means a spec is the only artifact that can be safely published. connection-gate-findings.md shows this approach produces real value. B finishes even if A is never fully playable.
**Evidence against:** Track B alone doesn't produce a playable FUT; it is a foundation, not an end-user product.
---
### Track C — FLE Lua bridge (local-match path, skip the backend gate)
**What it delivers:** FIFA 23 career mode or Kick-Off with an OpenFUT club's players and squad loaded via FLE's in-memory DB API. No online gate, no Blaze, no TLS. Fully offline from day one.
**Effort:** Low-to-medium. FLE is already loaded in the normal launch path. Tools exist (`tools/squad-exporter/`, `tools/profile-exporter/`). Primary unknown is whether FUT-relevant DB tables are accessible.
**Proven support:** FLE Lua API exposes `GetDBTableRows` / `EditDBTableField` for career mode. `fifa23-startup-flow.md` confirms FLE injects at load. `fut-integration-options.md` documents the integration path in detail and rates this as the recommended option.
**Assumed:** FUT card/club/squad data has in-memory DB table representations that FLE can write. If FUT data is purely server-side (loaded from EA servers, not from the Frostbite DB layer), Track C produces no FUT simulation at all — only career mode player stats.
**Evidence for:** Career mode already works with FLE edits (community precedent). Tools are present and designed for this path. No infrastructure work needed.
**Evidence against:** FUT in FIFA 23 uses server-side data. The cards in a player's FUT club, the coins, the squad — these are fetched from `fut.ea.com` REST APIs, not from the Frostbite embedded DB. FLE's `GetDBTableRows` likely exposes base player stats tables but not FUT item tables. The crucial test (run `export_squad.lua` while in FUT mode) has never been done.
---
### Recommendation
**Start Track C immediately as a parallel, low-cost validation.**
Run `export_squad.lua` in FLE while inside the FUT hub (or attempting to enter it). If FUT tables appear in the export, Track C is viable and is the fastest path to something a user can interact with. This test takes one session and costs nothing.
Simultaneously, **continue Track A/B with the next concrete RE step:** synthesize the ONLINE_STATUS_EVENT push. The most actionable option is to run `origin_spy` logs from the current hook to see what LSX events fire during a session, then attempt to push candidate event XMLs via the bridge LSX server and watch whether the game advances. This is bounded, testable work that either unblocks M2 or produces the spec value for Track B.
**Do not abandon Track A/B for Track C** — they are complementary. Core is already built; the bridge is mostly built. The gap is purely the RE wall at M2.
---
## 5. Architecture and Provenance Sanity-Check
### Hook + Brain coherence
The CLAUDE.md bridge architecture diagram (hook intercepts ProtoSSL → plain localhost TCP → blaze_brain → Core) remains coherent. The M1/M2 findings revealed one additional layer (EbisuSDK LSX event) that must precede the Blaze connection. The bridge has been updated to handle LSX directly. The overall design is sound; the M2 blocker is an implementation gap (event synthesis), not an architectural flaw.
**One inconsistency to flag:** The hook's `lsx.rs` contains a complete in-process LSX emulator (AES-128-ECB, CRandom, all response builders), but the recv/send hooks that activate it are explicitly removed (`lib.rs`: "recv/send hooks removed — LSX is now handled by the native openfut-bridge LSX server"). This is dead code. The bridge's LSX server is the current path. The in-process lsx.rs should either be deleted or documented as a fallback; its presence is confusing.
### Clean-room status
No evidence of EA leaked source anywhere in the tree. All RE work is derived from:
- Running the shipping binary and observing behavior (function return values, network traffic patterns)
- Memory scanning of the live process (string search, xref, disasm of observed addresses)
- Reading anadius's own compiled output (its exported symbols, its LSX XML format — which is anadius's own implementation, not EA's)
- Community FUT API knowledge (mapper.rs endpoint paths — plausible but speculative)
The Blaze framing in `fifa-blaze/crates/blaze-proto/src/frame.rs` cites "Fire2 used by ME3, BF3, and most post-2012 titles" — this is sourced from public community documentation of those older titles, not from any leaked EA source. **Clean-room intact.**
The `AES_KEY` in the hook's lsx.rs (`[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]`) is a placeholder key used for the LSX session encryption. The real session key is derived from the challenge seed via CRandom — this algorithm was RE'd from anadius's own binary. No EA source required.
---
## 6. If You Read Only This
- **The project is blocked at M2.** FIFA 23 submits `GoOnline`, gets success, then waits for an async `ONLINE_STATUS_EVENT` push on the LSX socket that no current code ever sends. All six Blaze capture files are empty (0 bytes). No Fire2 frame has ever been decoded.
- **M1 is the only completed milestone.** The gate function (`GetInternetConnectedState @ anadius64.dll+0x27790`) is precisely named and its two-flag branch decoded. Everything after M1 is either blocked or not started.
- **The next concrete action** is synthesizing the ONLINE_STATUS_EVENT push XML and testing whether the bridge's LSX server can deliver it to the game. This is the single thing that unblocks all Blaze work.
- **Track C (FLE Lua) is untested but cheap to validate.** Run `export_squad.lua` while in FUT to find out if FUT DB tables are accessible. If yes, it is the fastest path to user-visible results. If no, it is ruled out with one session.
- **openfut-core is complete and ready** — 25 phases, 15 migrations, full economy REST API, passing tests. It is not blocking anything; it is waiting for the bridge to connect to it.
-93
View File
@@ -1,93 +0,0 @@
# Track C — FUT DB table viability test
**Status: PENDING — test has not yet been run.**
## What this test settles
Track C ("FLE Lua bridge") would inject OpenFUT club data directly into FIFA 23's
in-memory Frostbite DB tables at runtime, bypassing the entire backend/Blaze stack.
It is only viable for FUT (not just career mode) if FUT-specific tables — card
inventory, squad composition with FUT fields, coins — are accessible in memory when
the game is in the FUT area.
FUT data in online mode is fetched server-side from `fut.ea.com`. It is not known
whether FIFA 23 mirrors any of this into the Frostbite in-memory DB that FLE
can read/write. This test settles that question directly.
## Test procedure
**Prerequisites:**
- FIFA 23 launched normally via umu-run/Steam
- FLE (FIFA Live Editor) injected and active (normal launch path)
- EAAC in offline/neutralized state
- Game navigated as deep into FUT as possible (FUT hub if reachable; otherwise the
furthest FUT screen before the gate blocks it)
**Run the exporter:**
1. In FLE's Lua Engine, open and run `tools/squad-exporter/export_squad.lua`
(full path on the Windows side: `C:\<game>\openfut_squad_export.json`)
2. Wait for the MessageBox "Done! N players, M teams." or "ERROR writing..."
3. Retrieve the output file from the Wine prefix:
`~/Games/umu/fifa23-tools/drive_c/FIFA 23 Live Editor/openfut_squad_export.json`
(or wherever `C:\FIFA 23 Live Editor\` maps in the active prefix)
**What to inspect in the output:**
- `all_db_tables` array — the complete list of table names visible to FLE right now
- `fut_tables` object — any table whose name contains `fut`, `club`, `pack`, `item`, or
`market` (the script auto-extracts these)
- `is_career_mode` — confirms whether FUT or career mode was active
## Classification criteria
### "FUT tables present"
`fut_tables` is non-empty AND contains FUT-specific fields beyond base player stats:
- e.g., `fut_items` with card-type / rating / chemistry fields
- e.g., a squad table with FUT formation / chemistry / loan-flag fields
- e.g., a coins or points balance field
**Verdict:** Track C is viable for FUT. Fastest path to user-visible results.
### "only base player tables"
`fut_tables` is empty (no `fut_*` / `club_*` / `item_*` / `market_*` table names found
in `all_db_tables`), OR those tables exist but contain only base player attributes
(OVR, potential, position, pace, …) — the same fields visible in career mode.
**Verdict:** Track C cannot produce FUT. It could at most provide a custom Kick-Off or
career-mode match with players sourced from OpenFUT Core. FUT items and coins exist
only on EA's servers (not in the in-memory DB in offline mode).
### "FUT area unreachable to test"
The connection gate blocked entering FUT deeply enough for FUT tables to be populated.
Record which tables were visible and at what screen the test was run.
**Verdict:** Retest after M2 is unblocked, OR test with `TLS_ENABLED=false` bridge
handling the entry check stub.
## Results
*(To be filled in after the test is run.)*
| Field | Value |
|---|---|
| Date run | — |
| FIFA screen at test time | — |
| `is_career_mode` | — |
| Total tables in `all_db_tables` | — |
| FUT-specific table names found | — |
| Key FUT fields present | — |
| **Classification** | **PENDING** |
## Honest prior
`fut-integration-options.md` rates this as the recommended path and lists `fut_clubs`,
`fut_items`, `fut_squads` as "expected" tables. However those expectations are based on
analogy with career mode (which does store club/squad in the DB). FUT's data model is
architecturally different — it is account-bound server-side. The expectation may be
wrong. This test is the oracle.
The `export_squad.lua` script checks `GetDBTablesNames()` exhaustively (not just
assumed names), so it will surface any FUT tables that actually exist, regardless of
what name they use.
+16
View File
@@ -0,0 +1,16 @@
# Keep the authoritative-tree build context lean: only tools/ and data/ runtime
# files (plus the Dockerfile's own entrypoint/manifest) are needed in-image.
.git
.gitignore
artifacts
captures
futmem
staging
docs
FUT-RUNBOOK.md
README.md
data/memdump
**/__pycache__
*.pyc
*.pem
*.key
+1
View File
@@ -0,0 +1 @@
state/
@@ -0,0 +1,11 @@
# Copy to .env in this directory. Required for remote deployment.
#
# OPENFUT_ADVERTISE — the address of THIS host as seen from the game machine
# (105). The responders advertise it to the client for every next hop (Blaze,
# roster, UTAS, POW). Compose refuses to start without it.
OPENFUT_ADVERTISE=203.0.113.10 # <- REPLACE with this host's LAN IP
# OPENFUT_BIND — address the listeners bind inside the container.
# Defaults to 0.0.0.0 (container-facing); the original all-on-localhost flow
# uses the loopback default baked into the responders when unset.
OPENFUT_BIND=0.0.0.0
@@ -0,0 +1,70 @@
# OpenFUT FIFA-17 FUT backend — Python migration deployment.
#
# Runs the 5 network responders (LSX / Blaze / roster / UTAS / POW) that FIFA 17
# dials to reach the FUT hub. Pure-Python; the only third-party dep is
# pycryptodome (LSX AES handshake). autopatch.py is intentionally NOT run here —
# it patches the game process memory and belongs on the client (105).
#
# Build context is fifa17-recon/ (the repo tree). tools/ is the AUTHORITATIVE
# recon tree (fifa17-recon/tools/). Only the runtime file set listed in
# docker/fifa17-python/runtime-tools.list is installed into /app/tools, so the
# deployed manifest stays byte-identical to the frozen baseline image
# openfut-fut-backend:python-baseline-2026-08-10 (see docs/BASELINE-*.md) while
# recon scripts, ghidra_queries and docs stay out of the image. data/ comes
# from the authoritative fifa17-recon/data. A SHA256SUMS.txt is baked into the
# image so any running backend can be matched to the exact dataset it was built
# from.
FROM python:3.12-slim
RUN pip install --no-cache-dir pycryptodome==3.20.0
WORKDIR /app
# Stage the authoritative tools tree in full...
COPY tools/ /app/tools-full/
# ...then install ONLY the runtime manifest (baseline image minus the two
# git-ignored certs, which are regenerated below).
COPY docker/fifa17-python/runtime-tools.list /app/runtime-tools.list
RUN set -eu; \
mkdir -p /app/tools; \
while IFS= read -r f; do \
[ -n "$f" ] || continue; \
mkdir -p "/app/tools/$(dirname "$f")"; \
cp "/app/tools-full/$f" "/app/tools/$f"; \
done < /app/runtime-tools.list; \
rm -rf /app/tools-full
COPY data/ /app/data/
# Redirector/roster TLS cert (CN/SAN = winter15.gosredirector.ea.com). ProtoSSL
# cert-verify is patched client-side, so a self-signed cert is fine — but the
# client dials the roster and redirector BY IP, and that path still checks the
# SAN against the dialed address (it is NOT covered by the two patched gates), so
# a cert without a matching IP SAN is rejected with fatal certificate_unknown
# (docs/FIFA17_FUT_SQUAD_UPDATE_TLS.md). The advertised LAN IP is a RUNTIME value,
# unknown here, so this bakes only a loopback-IP baseline and the entrypoint
# reissues with IP:$OPENFUT_ADVERTISE at start.
#
# openssl therefore has to remain in the image for the entrypoint, not be dropped
# with the apt lists. The pair is git-ignored (*.pem/*.key); regenerate if absent
# so a fresh checkout builds without extra steps.
RUN apt-get update && apt-get install -y --no-install-recommends openssl && \
rm -rf /var/lib/apt/lists/*
RUN if [ ! -s tools/redir_cert.pem ] || [ ! -s tools/redir_key.pem ]; then \
openssl req -x509 -newkey rsa:2048 -nodes \
-keyout tools/redir_key.pem -out tools/redir_cert.pem \
-days 3650 -subj "/CN=winter15.gosredirector.ea.com" \
-addext "subjectAltName=DNS:winter15.gosredirector.ea.com,DNS:*.gosredirector.ea.com,DNS:*.ea.com,IP:127.0.0.1"; \
fi
# Bake a dataset manifest so every image is self-identifying.
RUN find /app/tools /app/data -type f | LC_ALL=C sort | xargs sha256sum > /app/SHA256SUMS.txt
COPY docker/fifa17-python/entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# LSX 4216 | Blaze redir/main/nucleus 42127/42130/42131 | roster 8081 | UTAS 8099 | POW 8094/8080
EXPOSE 4216 42127 42130 42131 8081 8099 8094 8080
ENTRYPOINT ["/app/entrypoint.sh"]
@@ -0,0 +1,102 @@
#!/usr/bin/env bash
# ============================================================================
# OpenFUT FIFA-17 — CLIENT-side arming (runs on the GAME machine, e.g. 105).
#
# Companion to the dev container on the SERVER (120). The server runs the heavy
# responders (Blaze / UTAS / roster / POW). Two pieces are inherently local to
# the game and therefore stay here:
#
# * autopatch.py — patches FIFA17.exe process memory (ProtoSSL cert-verify).
# Must run where the game runs; cannot be containerised.
# * lsx_responder — the Origin/EADesktop emulator the game dials on the
# hardcoded loopback 127.0.0.1:4216. Loopback IPC can't be
# cleanly redirected to a remote host, so it lives here.
#
# Everything the game reaches by a routable address is redirected to the server:
# * winter15.gosredirector.ea.com (hardcoded EA IP 159.153.51.20) -> SERVER:42127
# * easw.easports.com (dead hardcoded UTAS host) -> SERVER (:8099)
#
# The server's responders were started with OPENFUT_ADVERTISE=<SERVER_IP>, so
# after these first redirected contacts the game is handed <SERVER_IP> for every
# later hop (Blaze main, roster, UTAS, telemetry) and dials the server directly.
#
# Usage: sudo OPENFUT_SERVER=203.0.113.10 ./client_arm.sh
# (re-run after every reboot; the sysctl/iptables state is volatile)
# ============================================================================
set -euo pipefail
SERVER="${OPENFUT_SERVER:?set OPENFUT_SERVER to the backend host IP, e.g. 203.0.113.10}"
GOS_EA_IP="159.153.51.20" # winter15.gosredirector.ea.com (hardcoded in FIFA17)
UTAS_HOST="easw.easports.com" # dead UTAS host baked into CardsDLL
UTAS_RE="${UTAS_HOST//./\\.}" # same, safe to embed in a regex
if [ "$(id -u)" -ne 0 ]; then
echo "!! must run as root (sudo). Re-run: sudo OPENFUT_SERVER=$SERVER $0" >&2
exit 1
fi
echo "[client_arm] backend server = $SERVER"
# 1) allow /proc/PID/mem writes (autopatch's ProtoSSL cert-verify patch)
sysctl -q kernel.yama.ptrace_scope=0
# 2) Redirect the hardcoded Blaze redirector IP to the server's redirector.
# (Replace any stale rule first so re-runs and IP changes are clean.)
while iptables -t nat -D OUTPUT -p tcp -d "$GOS_EA_IP" -j DNAT \
--to-destination "$SERVER:42127" 2>/dev/null; do :; done
iptables -t nat -A OUTPUT -p tcp -d "$GOS_EA_IP" -j DNAT --to-destination "$SERVER:42127"
# 2b) DNAT from OUTPUT to a REMOTE host needs a matching source-NAT on the way
# out, or the server's replies (from its own IP) won't match the game's
# conntrack entry. MASQUERADE the redirected flow so it is SNAT'd to this
# host's outbound IP. (Harmless duplicate-guarded like the DNAT above.)
while iptables -t nat -D POSTROUTING -p tcp -d "$SERVER" --dport 42127 \
-j MASQUERADE 2>/dev/null; do :; done
iptables -t nat -A POSTROUTING -p tcp -d "$SERVER" --dport 42127 -j MASQUERADE
# 3) Point the dead hardcoded UTAS host at the server. The port (8099) is carried
# in the game's own URL, so only the name needs redirecting. Remove any prior
# OpenFUT-managed line (loopback or other server) and write the current one.
sed -i "/[[:space:]]${UTAS_RE}\b.*# openfut\$/d" /etc/hosts
printf '%s\t%s\t# openfut\n' "$SERVER" "$UTAS_HOST" >> /etc/hosts
echo "[client_arm] --- armed ---"
sysctl kernel.yama.ptrace_scope
iptables -t nat -L OUTPUT -n | grep -i "$GOS_EA_IP" || echo " (DNAT missing!)"
# Verify the hosts entry by EFFECT, not by presence.
#
# glibc returns the FIRST match in /etc/hosts, so our line can be written
# correctly and still lose to an earlier one -- and the sed above only removes
# lines this script wrote (`# openfut`), so re-running never clears a foreign
# one. The old check here was `grep easw /etc/hosts && echo ok`, which passed on
# the shadowing line itself and reported success while resolution was wrong.
#
# Observed on 2026-08-11: a leftover `127.0.0.1 easw.easports.com` from the
# single-machine era shadowed the OpenFUT line, and every re-run said "ok".
resolved="$(getent ahosts "$UTAS_HOST" 2>/dev/null | awk '{print $1}' | sort -u | tr '\n' ' ')"
# SERVER may be a hostname, so compare address-to-address rather than comparing
# the literal string against resolved IPs (which would warn spuriously).
server_ips="$(getent ahosts "$SERVER" 2>/dev/null | awk '{print $1}' | sort -u)"
[ -n "$server_ips" ] || server_ips="$SERVER"
match=0
for ip in $server_ips; do
printf '%s' "$resolved" | grep -qw -- "$ip" && match=1
done
if [ "$match" -eq 1 ]; then
echo " /etc/hosts ok ($UTAS_HOST -> $resolved)"
else
echo
echo " !! WARNING: $UTAS_HOST resolves to [$resolved], not $SERVER."
echo " An earlier /etc/hosts line is shadowing the OpenFUT one:"
grep -nE "^[[:space:]]*[^#].*[[:space:]]${UTAS_RE}([[:space:]]|\$)" /etc/hosts \
| grep -v '# openfut$' | sed 's/^/ /' || true
echo
echo " Not fatal: the responders advertise $SERVER, so the game stops using"
echo " this name after the first hop. Worth removing the line above anyway."
echo " Lines are listed rather than deleted -- this script will not remove"
echo " /etc/hosts entries it did not write."
fi
echo
echo "[client_arm] Next: start the LOCAL pieces (LSX + autopatch) with client_local.sh,"
echo " ensure the container is up on $SERVER, then launch FIFA 17."
@@ -0,0 +1,49 @@
# OpenFUT FIFA-17 FUT backend — declarative deployment (server side, runs on 120).
#
# cp .env.example .env # set OPENFUT_ADVERTISE to THIS host's LAN IP
# docker compose up -d --build
#
# Brings up the 5 responders the game dials. OPENFUT_ADVERTISE is the address
# the servers hand the client (105) for every next hop (Blaze, roster, UTAS,
# POW) and is required — there is no silent loopback fallback in remote mode.
#
# The client (105) still needs its first-hop redirect (hook or DNAT) plus
# autopatch.py running locally; see client_arm.sh and the FIFARUNBOOK.
name: openfut-fut-backend
services:
fut-backend:
build:
context: ../..
dockerfile: docker/fifa17-python/Dockerfile
image: openfut-fut-backend:dev
container_name: openfut-fut-backend
restart: unless-stopped
environment:
# Bind all interfaces inside the container.
OPENFUT_BIND: "${OPENFUT_BIND:-0.0.0.0}"
# Address advertised to the client for the next hop. MUST be this host's
# LAN IP as seen from the game machine (105). Required (see .env.example).
OPENFUT_ADVERTISE: "${OPENFUT_ADVERTISE:?set OPENFUT_ADVERTISE in .env to this host's LAN IP, e.g. 203.0.113.10}"
# POW content advertises port 8080 by default, which collides with the
# openfut-core publish on this host. Remap it to 8085 on the host and
# advertise the remapped endpoint.
POW_CONTENT_ADDR: "0.0.0.0:8080"
POW_CONTENT_HOST: "${OPENFUT_ADVERTISE}:8085"
# Launcher-selected EA/Origin identity shared by LSX, Blaze, POW and UTAS.
# FUT saves are isolated by persona beneath /state/accounts.
FUT_ACCOUNT_PATH: "/state/active_account.json"
FUT_PROFILE_ROOT: "/state/accounts"
FUT_SETTINGS: "off"
FUT_MODES: "1"
volumes:
- "../state:/state"
ports:
- "4216:4216" # LSX (Origin bootstrap)
- "42127:42127" # Blaze redirector (TLS)
- "42130:42130" # Blaze main
- "42131:42131" # Nucleus OAuth stub
- "8081:8081" # FUT roster XML (HTTPS)
- "8099:8099" # UTAS / RS4 FUT REST API
- "8094:8094" # POW / EASFC API
- "8085:8080" # POW content (host 8085 -> container 8080; avoids core:8080)
@@ -0,0 +1,91 @@
#!/usr/bin/env bash
# ============================================================================
# OpenFUT FIFA-17 FUT backend — in-CONTAINER orchestrator.
#
# Runs the 5 network responders that the game dials. Unlike the host-based
# openfut-fut.sh, this does NO host arming (no pkexec / iptables / /etc/hosts /
# ptrace) — those are client-side concerns handled on the game machine (105).
# autopatch.py is NOT run here: it patches the FIFA17.exe process memory and must
# run on the box the game runs on.
#
# Address behaviour is driven by two env vars (see each responder):
# OPENFUT_BIND bind address for every listener (container: 0.0.0.0)
# OPENFUT_ADVERTISE address handed to the client for the next hop
# (the server's LAN IP, e.g. 203.0.113.10)
# ============================================================================
set -uo pipefail
cd "$(dirname "$(readlink -f "$0")")/tools"
BIND="${OPENFUT_BIND:-0.0.0.0}"
ADV="${OPENFUT_ADVERTISE:?OPENFUT_ADVERTISE must be set to the server LAN IP (e.g. 203.0.113.10)}"
export OPENFUT_BIND="$BIND"
export OPENFUT_ADVERTISE="$ADV"
# POW keys advertised by blaze must also point at the server, not loopback.
export POW_HOST="${POW_HOST:-$ADV:8094}"
export POW_CONTENT_HOST="${POW_CONTENT_HOST:-$ADV:8080}"
export POW_ADDR="${POW_ADDR:-$BIND:8094}"
export POW_CONTENT_ADDR="${POW_CONTENT_ADDR:-$BIND:8080}"
echo "[openfut] bind=$BIND advertise=$ADV"
# The TLS cert every responder serves must carry the ADVERTISED IP in its SAN.
# The client dials the roster (:8081) and redirector by that IP, and that path
# validates the cert's SAN against the dialed address — it is NOT covered by the
# two client-side ProtoSSL gates autopatch patches, so a cert lacking IP:$ADV is
# rejected with fatal certificate_unknown and the FUT hub fails with "An error
# occurred downloading the FUT Squad Update" (docs/FIFA17_FUT_SQUAD_UPDATE_TLS.md).
# The advertised IP is unknown at image-build time, so reconcile it here: reissue
# only when the current cert does not already carry it, so a restart reuses the
# same cert (no per-start fingerprint churn) and this self-heals if $ADV changes.
CERT=redir_cert.pem KEY=redir_key.pem
if ! openssl x509 -in "$CERT" -noout -ext subjectAltName 2>/dev/null | grep -qF "IP Address:$ADV"; then
echo "[openfut] reissuing TLS cert with SAN IP:$ADV (was missing it)"
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$KEY" -out "$CERT" -days 3650 \
-subj "/CN=winter15.gosredirector.ea.com" \
-addext "subjectAltName=DNS:winter15.gosredirector.ea.com,DNS:*.gosredirector.ea.com,DNS:*.ea.com,IP:$ADV,IP:127.0.0.1" \
>/dev/null 2>&1 \
&& echo "[openfut] cert SAN now: $(openssl x509 -in "$CERT" -noout -ext subjectAltName 2>/dev/null | tail -1 | tr -s ' ')" \
|| { echo "[openfut] FATAL: could not reissue TLS cert" >&2; exit 1; }
fi
# name script extra-env
declare -a SERVERS=(
"lsx|lsx_responder_v2.py|OPENFUT_LSX_EVENT_COUNT=100000"
"blaze|blaze_responder_v3b.py|-"
"roster|roster_server.py|-"
"utas|utas_server.py|FUT_TRADING=1 FUT_PILESIZES=1 FUT_TRADEABLE=1 FUT_DISCARD_TABLE=1 FUT_DISCARD_SEND=1"
"pow|pow_server.py|-"
)
pids=()
names=()
for entry in "${SERVERS[@]}"; do
IFS='|' read -r name script env <<<"$entry"
envprefix=""; [ "$env" != "-" ] && envprefix="env $env"
echo "[openfut] starting $name ($script)"
# shellcheck disable=SC2086
$envprefix python3 -u "$script" &
pids+=($!)
names+=("$name")
done
# Propagate SIGTERM/SIGINT to children so `docker stop` is clean.
term() {
echo "[openfut] shutting down…"
for p in "${pids[@]}"; do kill "$p" 2>/dev/null || true; done
wait
exit 0
}
trap term TERM INT
# If ANY responder dies, take the whole container down so the failure is visible
# (they all bind ports the game needs — a partial stack is a broken stack).
while true; do
for i in "${!pids[@]}"; do
if ! kill -0 "${pids[$i]}" 2>/dev/null; then
echo "[openfut] responder ${names[$i]} (pid ${pids[$i]}) exited - bringing container down"
term
fi
done
sleep 2
done
@@ -0,0 +1,77 @@
origin_login_probe.py
card_proof.py
force_login_flag.py
card_record_poke.py
test_tournament_contract.py
dmp_stack.py
fut_clubitems.py
test_autopatch_logging.py
capture_lsx.py
roster_server.py
autopatch.py
dbschema_probe.py
test_account_profiles.py
coach_window.py
watch_club_model.py
db_dump.py
coach_probe.py
uidiff.py
probe_club_stats.py
blaze_responder_v3.py
dbdata_extract.py
decode_fire2.py
check_club_stat_vocab.py
fut_accounts.py
strip_dead_cards.py
test_hub_offline_season_contract.py
repair_club.py
forge_node.py
verify_preauth.py
fut_coaches.py
heat2.py
test_security_question.py
test_utas_log_redaction.py
sbc_populate_poke.py
atomdump.py
lsx_responder.py
fut_staff.py
fut_cards.py
blaze_responder.py
blaze_responder_v2.py
fut_store.py
blaze_responder_v3b.py
test_fut_contract.py
utas_server.py
lsx_force_online.py
grab_crash_code.py
gate_byte_probe.py
fut_admin.py
test_match_rewards.py
lsx_responder_v2.py
card_identity_probe.py
extract_player_ids.py
watch_online_mode.py
store_enable_poke.py
pow_server.py
fut_account.py
blaze_responder_v3_patched.py
check_settings_flags.py
test_match_lifecycle.py
sbc_hook_poke.py
futlog.py
fut_seed.py
hub_counter_probe.py
fut_consumables.py
db_catalog_walk.py
memtool.py
build_player_facts.py
sweep_collect.py
test_card_families.py
fut_club_stats.py
dmp.py
build_consumables.py
test_market_buy.py
dump_login_code.py
auth_watch.py
vgamepad.py
ghidra_env.py
@@ -0,0 +1,121 @@
# Python backend baseline — 2026-08-10
Frozen rollback target for the working offline FUT backend (Python migration) as
it ran on 10.10.0.120. Everything here was recorded from the live system before
any cleanup/restructure; the image and state are archived in
`/home/alex/OpenFUT/docker-backups/`.
## Frozen image
| field | value |
|------------|-------|
| tag | `openfut-fut-backend:python-baseline-2026-08-10` |
| image id | `e1f93ad647ab` |
| digest | `sha256:e1f93ad647abbec32e2751f3e88fed75d3e574d4500395b21c31d0f0b96abac6` |
| created | 2026-08-10T02:14:56Z (built as `openfut-fut-backend:dev`) |
| size | 278 MB |
| archive | `docker-backups/openfut-fut-backend-python-baseline-2026-08-10.tar.gz` (53 MB, `docker save \| gzip -1`) |
## Frozen container
| field | value |
|------------|-------|
| id | `f16d3204cbf48151be232ff8f4194b429e311042f8f6f95644760d4b8eba2938` |
| created | 2026-08-10T02:14:56.194470252Z |
| image | `openfut-fut-backend:dev` (= baseline image id) |
| restart | `unless-stopped` |
| network | `docker_default`, IP `172.19.0.2`, aliases `openfut-fut-backend`, `fut-backend` |
| log | json-file |
| inspect | `docker-backups/openfut-fut-backend-container-inspect-2026-08-10.json` |
### Environment (Config.Env)
```
FUT_SETTINGS=off
FUT_MODES=1
OPENFUT_BIND=0.0.0.0
OPENFUT_ADVERTISE=10.10.0.120
POW_CONTENT_ADDR=0.0.0.0:8080
POW_CONTENT_HOST=10.10.0.120:8085
FUT_ACCOUNT_PATH=/state/active_account.json
FUT_PROFILE_ROOT=/state/accounts
PYTHON_VERSION=3.12.13 (python:3.12-slim base)
```
### Volumes / mounts
Bind mount `docker/state` (host) -> `/state` (container, rw). Runtime state:
`active_account.json` (active persona) + `accounts/` (FUT saves by persona).
Snapshot: `docker-backups/state-2026-08-10/`.
### Ports (host -> container)
| host | container | service |
|------|-----------|---------|
| 4216 | 4216 | LSX (Origin bootstrap) |
| 42127 | 42127 | Blaze redirector (TLS) |
| 42130 | 42130 | Blaze main |
| 42131 | 42131 | Nucleus OAuth stub |
| 8081 | 8081 | FUT roster XML (HTTPS) |
| 8099 | 8099 | UTAS / RS4 FUT REST API |
| 8094 | 8094 | POW / EASFC API |
| 8085 | 8080 | POW content (remapped to avoid openfut-core:8080) |
All listeners verified bound on `0.0.0.0` in the container (LSX/Blaze/nucleus,
roster, UTAS, POW, POW content).
## Dataset manifest
`docker-backups/SHA256SUMS-container-baseline-2026-08-10.txt` — sha256 of all
323 files under `/app/tools` + `/app/data` inside the running container.
`fifa17-python/tools/` and `fifa17-python/data/` are the staged sources that
built this image (verified byte-identical to the container copies at freeze
time). Images rebuilt from git now bake their own `/app/SHA256SUMS.txt`; the
rebuild-equivalence check is `diff` between that and this manifest; the only expected deltas are pycache files (not committed) and the redir cert pair (regenerated per build).
## Restore
```sh
# From the archived image (works offline, exact layers):
docker load -i /home/alex/OpenFUT/docker-backups/openfut-fut-backend-python-baseline-2026-08-10.tar.gz
docker tag openfut-fut-backend:python-baseline-2026-08-10 openfut-fut-backend:dev
# Or rebuild from git:
cd /home/alex/OpenFUT/fifa17-recon/docker/fifa17-python
cp .env.example .env # set OPENFUT_ADVERTISE
docker compose up -d --build
```
## Status at freeze time
- The 2026-08-10 `openfut-fut-backend` container was **left running untouched**
(the .105 launcher audit uses it). No rebuild/replacement happens until that
audit finishes; the frozen image is the rollback target if cleanup breaks it.
- `docker/state` was **not** moved during restructure (bind path must not change
while the container is live); the new compose mounts `../state` from the same
location.
- TURN/relay re-addressing (multiplayer) and long-tail endpoints (weather,
matchday, kit assets) are deferred feature gaps — tracked separately.
## Running state vs image — what the frozen image does NOT contain
The baseline image (`python-baseline-2026-08-10` / `dev`) was built at 02:14Z,
but the container's `/app` was hot-patched afterwards:
* `tools/utas_server.py` — gained the `FUT_MODES`-gated `offlineSeason` block in
GetHubData's club response (keeps the hub's offline-season summary valid).
* `tools/test_hub_offline_season_contract.py` — added to `/app/tools`.
`docker save` captures the image, not the container's writable layer, so the
baseline tar.gz lacks those two changes. Two paths cover the exact runtime:
* `openfut-fut-backend:python-running-2026-08-10` — `docker commit` of the
running container (sha256:093a98fa0496...), the exact runtime FS.
* The committed `fifa17-python/tools` + `data` — synced to match the running
container byte-for-byte (237 files verified, incl. the redir cert pair), so a
fresh build reproduces the actual running backend. Proven by rebuilding from
the committed sources and diffing the baked `/app/SHA256SUMS.txt` against the
container manifest: identical.
Archive: `docker-backups/openfut-fut-backend-python-running-2026-08-10.tar.gz`.
Regular → Executable
+115 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Watch for a (re)launched FIFA17.exe and auto-apply both ProtoSSL cert patches
the moment its unpacked code is mapped. Idempotent; keeps watching across relaunches."""
import glob, time, struct
import glob, time, struct, sys
# Watch for a (re)launched FIFA17.exe and auto-apply ProtoSSL cert + FUT store patches
import glob, time, os
@@ -24,7 +24,46 @@ STORE_PATCHES = {
0x1800175aa: NOP2,
}
LOG="/tmp/autopatch.log"
# Store resolver crash-guard for the empty "My Packs" case (bug 6c; PROVEN R1 on the
# tested FIFA 17 build -- see docs/plans/FIFA17_EMPTY_MYPACKS_CLIENT_FIX.md PART IV and
# docs/evidence/FIFA17_EMPTY_MYPACKS_CLIENT_CONTRACT.md).
#
# When no `mypacks` group exists, FIFA's Store resolver receives category id -1. CardsDLL
# FUN_1800147f0 @ 0x180014858 is `JNZ 0x14869` (75 0f): the original treats every non-zero
# category (including -1) as resolvable, calls FUN_180014420, gets NULL, and crashes at the
# [NULL+0x48] deref in FUN_1800147f0 (0x180014882). Changing JNZ->JG (7f 0f) preserves
# positive-category resolution (EDI>0 branch) while routing zero/negative categories through
# the existing Browse/list-all path -> no NULL lookup, no crash, Store opens on Browse Packs.
#
# CAVEAT: this guards the category SIGN only. It does NOT protect a stale *positive* invalid
# ordinal produced by changing the Store group topology (sentinel-present <-> sentinel-absent)
# DURING one running FIFA process -- that reproduced the same crash in the confounded run F3.
# The empty-My-Packs representation MUST stay stable for a FIFA session (see the SESSION-STABLE
# invariant in the client-fix plan).
#
# Orig-verified / fail-closed: applied only when the live bytes are the known original (75 0f);
# already-patched (7f 0f) is a no-op; anything else is logged and SKIPPED (never blindly
# overwritten), so an unrecognised CardsDLL build is not patched.
STORE_PATCHES_GUARDED = {
0x180014858: (bytes.fromhex("750f"), bytes.fromhex("7f0f")), # JNZ 0x14869 -> JG 0x14869
}
# Capability advertised to the launcher/backend once the resolver guard is VERIFIED
# live in a specific FIFA process (docs/plans/FIFA17_PATCHED_CLIENT_CAPABILITY.md #3/#4).
EMPTY_MYPACKS_RESOLVER_CAPABILITY = "fifa17.empty_mypacks_resolver"
EMPTY_MYPACKS_RESOLVER_VERSION = 1
# The guarded site whose verified enforcement backs the capability above.
RESOLVER_GUARD_VA = 0x180014858
# Per-FIFA-pid guard status (fail-closed; FIFA17_PATCHED_CLIENT_CAPABILITY.md #4).
GUARD_NOT_ATTEMPTED = "NOT_ATTEMPTED" # CardsDLL not mapped / guard not yet evaluated
GUARD_VERIFIED = "VERIFIED" # live bytes == patch after enforcement (patch or noop)
GUARD_UNSUPPORTED_BUILD = "UNSUPPORTED_BUILD" # neither original nor patched (guarded_action -> skip)
GUARD_WRITE_FAILED = "WRITE_FAILED" # /proc/<pid>/mem write raised
GUARD_VERIFY_FAILED = "VERIFY_FAILED" # post-write re-read != patch
LOG=os.environ.get("OPENFUT_AUTOPATCH_LOG", f"/tmp/openfut-autopatch-{os.getuid()}.log")
def log(m):
line=f"[{time.strftime('%H:%M:%S')}] {m}"
@@ -52,11 +91,55 @@ def wr(pid,va,b):
with open(f'/proc/{pid}/mem','r+b') as f:
f.seek(va); f.write(b)
def guarded_action(cur, orig, patch):
"""Fail-closed decision for a guarded byte patch (see STORE_PATCHES_GUARDED).
Returns "noop" when the live bytes are already patched, "patch" when they are the
known original (safe to apply), or "skip" for anything else -- an unrecognised
CardsDLL build that must never be blindly overwritten.
"""
if cur == patch:
return "noop"
if cur == orig:
return "patch"
return "skip"
def guard_state_after(cur_before, orig, patch, wrote_ok, cur_after):
"""Map a guarded-patch enforcement outcome to a per-pid guard STATE (pure).
Mirrors guarded_action's decision, extended with post-write verification so the
caller advertises the capability only on VERIFIED. No /proc access -- unit-testable.
- cur_before == patch -> VERIFIED (already patched; guarded_action "noop")
- cur_before == orig -> WRITE_FAILED if the write raised, else VERIFIED when the
re-read is patch, else VERIFY_FAILED (guarded_action "patch")
- otherwise -> UNSUPPORTED_BUILD (guarded_action "skip")
"""
if cur_before == patch:
return GUARD_VERIFIED
if cur_before == orig:
if not wrote_ok:
return GUARD_WRITE_FAILED
if cur_after == patch:
return GUARD_VERIFIED
return GUARD_VERIFY_FAILED
return GUARD_UNSUPPORTED_BUILD
patched=set()
store_patched=set()
guard_reported=set()
log("=== AUTOPATCH watching for FIFA17.exe ===")
while True:
if __name__ == "__main__":
launcher_pid = None
if "--launcher-pid" in sys.argv:
try: launcher_pid = int(sys.argv[sys.argv.index("--launcher-pid") + 1])
except (ValueError, IndexError): raise SystemExit("invalid --launcher-pid")
log("=== AUTOPATCH watching for FIFA17.exe ===")
while True:
if launcher_pid and not os.path.exists(f"/proc/{launcher_pid}"):
log(f"launcher pid {launcher_pid} exited; stopping autopatch")
break
for pid in find_pids():
if pid not in patched:
try:
@@ -82,6 +165,34 @@ while True:
if rd(pid, live, len(data)) != data:
wr(pid, live, data)
log(f"pid {pid}: ENFORCED store patch @ {live:#x}")
for va, (orig, patch) in STORE_PATCHES_GUARDED.items():
live = cbase + (va - IMG_BASE)
cur = rd(pid, live, len(patch))
action = guarded_action(cur, orig, patch)
wrote_ok = True
cur_after = cur
if action == "patch":
try:
wr(pid, live, patch)
log(f"pid {pid}: ENFORCED guarded store patch @ {live:#x} (JNZ->JG, empty My Packs)")
except Exception as e:
wrote_ok = False
log(f"pid {pid}: guarded patch write failed @ {live:#x}: {e}")
if wrote_ok:
try:
cur_after = rd(pid, live, len(patch))
except Exception:
cur_after = b""
elif action == "skip":
log(f"pid {pid}: SKIP guarded patch @ {live:#x}: unexpected {cur.hex()} (build mismatch)")
# action == "noop": already patched; nothing to write.
if va == RESOLVER_GUARD_VA and pid not in guard_reported:
state = guard_state_after(cur, orig, patch, wrote_ok, cur_after)
if state == GUARD_VERIFIED:
log(f"[store-guard] verified capability {EMPTY_MYPACKS_RESOLVER_CAPABILITY}={EMPTY_MYPACKS_RESOLVER_VERSION} fifa_pid={pid}")
else:
log(f"[store-guard] guard status={state} fifa_pid={pid} (no capability advertised)")
guard_reported.add(pid)
if pid not in store_patched:
log(f"pid {pid}: PATCHED store gates in CardsDLL @ {cbase:#x}")
store_patched.add(pid)
+98 -30
View File
@@ -128,14 +128,52 @@ CLIENT_ID = ACCOUNT.CLIENT_ID
PLATFORM = ACCOUNT.PLATFORM
SERVER_VERSION = "Blaze 15.1.1.3.0 (OpenFUT)\n"
# ================================================================== config
HOST = "127.0.0.1"
def refresh_account_identity():
"""Refresh launcher-selected identity before constructing a Blaze session.
The account sync endpoint runs in the separate UTAS process and atomically
replaces the shared active-account file. Blaze snapshots these aliases for
its response builders, so refresh them once at each new TCP session.
"""
global PERSONA_ID, PERSONA_NAME, USER_ID, EXT_ID, EMAIL, ACCOUNT_LOCALE_FALLBACK
ACCOUNT.load(force=True)
PERSONA_ID = ACCOUNT.persona_id
PERSONA_NAME = ACCOUNT.persona_name
USER_ID = ACCOUNT.user_id
EXT_ID = ACCOUNT.ext_id
EMAIL = ACCOUNT.email
ACCOUNT_LOCALE_FALLBACK = ACCOUNT.account_locale_int
# ================================================================== config
#
# Client/server split support (OpenFUT dev-container): two env vars, both
# defaulting to loopback so the original all-on-localhost flow is byte-identical.
# OPENFUT_BIND — the address the listeners bind (0.0.0.0 in a container).
# OPENFUT_ADVERTISE — the address this server hands back to the client for the
# NEXT hop (Blaze host, roster/UTAS/telemetry/QoS URLs). On
# 105-local this is 127.0.0.1; on the 120 server it is the
# server's LAN IP so the game dials 120 directly after the
# first (hook/DNAT-redirected) contact.
import os as _os_cfg
_ADVERTISE = _os_cfg.environ.get("OPENFUT_ADVERTISE", "127.0.0.1")
_BIND = _os_cfg.environ.get("OPENFUT_BIND", "127.0.0.1")
def _ip_str_to_u32(ip):
"""Dotted-quad -> big-endian u32 (matches the original (127<<24)|1 layout).
Falls back to loopback if the advertise value isn't a bare IPv4 literal."""
try:
a, b, c, d = (int(x) for x in ip.split("."))
return (a << 24) | (b << 16) | (c << 8) | d
except Exception:
return (127 << 24) | 1
HOST = _BIND
REDIR_PORT = 42127
BLAZE_PORT = 42130
NUCLEUS_PORT = 42131
BLAZE_IP_STR = "127.0.0.1"
BLAZE_IP_U32 = (127 << 24) | 1
BLAZE_IP_STR = _ADVERTISE
BLAZE_IP_U32 = _ip_str_to_u32(_ADVERTISE)
LOG = "/tmp/blaze_responder.log"
RXDIR = "/tmp/blaze_rx"
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -157,7 +195,9 @@ REPLY_EMPTY_TO_UNKNOWN = True
# (grid-blaze order) or after (pamplona order). Both are reported to work.
NOTIFY_BEFORE_LOGIN_REPLY = False
DUMP_FRAMES = True
# Raw Fire2 frames and decoded TDF can contain auth/session material. Keep the
# reverse-engineering capture path, but require an explicit opt-in for it.
DUMP_FRAMES = os.environ.get("OPENFUT_BLAZE_DUMP_FRAMES") == "1"
_log_lock = threading.Lock()
@@ -525,7 +565,8 @@ OSDK_TICKER = []
# branch does NOT wrap the value ("https://%s" is only the ini path) -> ABSOLUTE url.
# Serve HTTPS (EA's production value is https; the DirtySDK download mgr may reject
# http). Our ProtoSSL cert-verify is patched (autopatch), so a self-signed cert is OK.
ROSTER_HOST = "127.0.0.1:8081"
ROSTER_HOST = "%s:8081" % _ADVERTISE
POW_CONTENT_HOST = os.environ.get("POW_CONTENT_HOST", "127.0.0.1:8080")
OSDK_ROSTER = [
("ROSTERUPDATE_URL", "https://%s/fifa17/fut/rosterupdate.xml" % ROSTER_HOST),
("ROSTER_URL", "https://%s/fifa17/roster/" % ROSTER_HOST), # @0x143973aa0
@@ -562,7 +603,6 @@ IDENTITY_PARAMS = [
# FUT_POW=1 ./openfut-fut.sh restart
# and read /tmp/pow_server.log. FUT_POW=off is the instant fallback.
POW_HOST = os.environ.get("POW_HOST", "127.0.0.1:8094")
POW_CONTENT_HOST = os.environ.get("POW_CONTENT_HOST", "127.0.0.1:8080")
_POW_ON = os.environ.get("FUT_POW", "").lower() in ("1", "true", "on", "yes")
OSDK_POW = [
("FIFA_POW_URL", "http://%s/" % POW_HOST),
@@ -571,6 +611,14 @@ OSDK_POW = [
("POW_IS_ON", "1"),
] if _POW_ON else []
# CardsDLL's shared web-file downloader also reads this key for FUT-owned content.
# In particular, opening SBC downloads /fut/packs/loc/storepackdescriptions.<locale>.xml
# after /sbs/sets succeeds. Keep the content base available even while the unrelated
# POW API remains opt-in through FUT_POW/POW_IS_ON.
FUT_CONTENT_CONFIG = [
("FIFA_POW_CONTENT_SERVER_URL", "http://%s" % POW_CONTENT_HOST),
]
CLIENT_CONFIGS = {
"BlazeSDK": None, # built dynamically, see below
"netres": OSDK_NETRES, # CFID (verified @0x143962be0)
@@ -595,7 +643,7 @@ CLIENT_CONFIGS = {
# /etc/hosts easw.easports.com->127.0.0.1 redirect. MUST be exactly "http://127.0.0.1:8099/"
# (scheme + trailing slash mandatory on the auth path). Do NOT serve FUT_TARGET_PORT
# (bug @0x1801808e8 reads FUT_MAX_HOPS instead) nor FUT/MODULE_BASEURL_* (dead code).
UTAS_BASE = "http://127.0.0.1:8099/"
UTAS_BASE = "http://%s:8099/" % _ADVERTISE
FUT_RS4_MODULES = [
"AUCTIONHOUSE", "CLUB_USER", "CLUB_INFO", "CLUB", "DREAM", "SQUAD",
"DELETE_SQUAD", "LBOPTIONS", "LBDEFAULT", "PAFPRACTICE", "UT", "USER",
@@ -731,18 +779,21 @@ FUT_RS4_CONFIG = (
def client_config_for(cfid: str) -> list:
"""-> sorted [(key, value)]. Unknown CFID -> [] (an EMPTY MAP, which we
still wrap in a present CONF field -- never an empty frame).
FUT_RS4_* base-URL keys ride on EVERY CFID (merged '_all' store; which section
CardsDLL reads is unproven, so serve them everywhere)."""
"""Return sorted config rows for one section.
Unknown CFIDs still receive the shared FUT/content/POW rows because those
consumers read the merged ``_all`` store and the contributing section is
unproven. The response always carries a present CONF field.
"""
# OSDK_POW rides on EVERY CFID for the same reason FUT_RS4_* does: powdll's
# FUN_18005a460 reads FIFA_POW_URL out of the merged '_all' store, and which
# section it happens to read is unproven. Empty list when FUT_POW is unset, so
# this is a no-op by default. (Putting the keys ONLY under a hypothetical
# "OSDK_POW" CFID would be dead code -- nothing is known to request that name.)
if cfid == "BlazeSDK":
return sorted(blazesdk_config() + FUT_RS4_CONFIG + OSDK_POW)
return sorted((CLIENT_CONFIGS.get(cfid) or []) + FUT_RS4_CONFIG + OSDK_POW)
return sorted(blazesdk_config() + FUT_RS4_CONFIG + FUT_CONTENT_CONFIG + OSDK_POW)
return sorted((CLIENT_CONFIGS.get(cfid) or []) + FUT_RS4_CONFIG
+ FUT_CONTENT_CONFIG + OSDK_POW)
def fetch_config_response_fields(cfid: str) -> "OrderedDict":
@@ -765,7 +816,7 @@ def qos_config() -> "OrderedDict":
has NO SVID, unlike Mirror's Edge Catalyst)."""
return OrderedDict([
("BWPS", (STRUCT, OrderedDict([ # Blaze::QosPingSiteInfo
("PSA", (STRING, "127.0.0.1")),
("PSA", (STRING, _ADVERTISE)),
("PSP", (INT, 17502)),
]))),
("LNP", (INT, 10)),
@@ -1091,7 +1142,7 @@ def post_auth_response_fields(sess: Session) -> "OrderedDict":
client to have a well-formed config and then fail to connect quietly rather
than resolve a real EA hostname."""
tele = OrderedDict([ # GetTelemetryServerResponse (15)
("ADRS", (STRING, "127.0.0.1")),
("ADRS", (STRING, _ADVERTISE)),
("ANON", (INT, 0)),
("DISA", (STRING, "")),
("EDCT", (INT, 0)),
@@ -1108,7 +1159,7 @@ def post_auth_response_fields(sess: Session) -> "OrderedDict":
("SVNM", (STRING, "telemetry-openfut")),
])
tick = OrderedDict([ # GetTickerServerResponse (3)
("ADRS", (STRING, "127.0.0.1")),
("ADRS", (STRING, _ADVERTISE)),
("PORT", (INT, 8999)),
("SKEY", (STRING, "")),
])
@@ -1252,8 +1303,10 @@ def dispatch(hdr: dict, fields, raw_payload: bytes, sess: Session) -> list:
log(" -- client locale 0x%08x captured for ALOC" % loc)
resp = preauth_response_fields(service_name=sess.service_name)
payload = encode_tdf(resp)
log(" -> PreAuthResponse (INST=%r, %d payload bytes):\n%s"
% (sess.service_name, len(payload), heat2.dump(resp)))
log(" -> PreAuthResponse (INST=%r, %d payload bytes)"
% (sess.service_name, len(payload)))
if DUMP_FRAMES:
log(" -> PreAuthResponse TDF:\n%s" % heat2.dump(resp))
return [reply_to(hdr, payload)]
if cmd == CMD_PING:
@@ -1267,6 +1320,7 @@ def dispatch(hdr: dict, fields, raw_payload: bytes, sess: Session) -> list:
n = len(resp["CONF"][1][2])
log(" -> FetchConfigResponse CFID=%r -> %d key(s)%s"
% (cfid, n, "" if n else " (EMPTY MAP, unknown CFID)"))
if DUMP_FRAMES:
for k, v in resp["CONF"][1][2]:
log(" %-32s = %s" % (k, v))
return [reply_to(hdr, encode_tdf(resp))]
@@ -1302,12 +1356,13 @@ def dispatch(hdr: dict, fields, raw_payload: bytes, sess: Session) -> list:
sess.auth_code = get_str(fields or {}, "AUTH", "")
sess.logged_in = True
sess.login_time = int(time.time())
log(" == Authentication::login AUTH=%r (accepted WITHOUT Nucleus "
"validation -- forged offline session)" % sess.auth_code)
log(" == Authentication::login AUTH=[REDACTED] "
"(accepted as an offline OpenFUT session)")
resp = login_response_fields(sess)
payload = encode_tdf(resp)
log(" -> LoginResponse (%d bytes):\n%s"
% (len(payload), heat2.dump(resp)))
log(" -> LoginResponse (%d bytes)" % len(payload))
if DUMP_FRAMES:
log(" -> LoginResponse TDF:\n%s" % heat2.dump(resp))
notifs = build_login_notifications(sess, sess.login_time)
out = []
if NOTIFY_BEFORE_LOGIN_REPLY:
@@ -1458,9 +1513,10 @@ _frame_counter = [0]
def blaze_handle(raw: socket.socket, addr) -> None:
refresh_account_identity()
log("*** BLAZE CONNECT from %s ***" % (addr,))
sess = Session()
log(" session key minted: %s" % sess.session_key)
log(" session key minted: [REDACTED]")
buf = bytearray()
raw.settimeout(300)
try:
@@ -1491,10 +1547,10 @@ def blaze_handle(raw: socket.socket, addr) -> None:
MSGTYPE_NAME.get(hdr["msg_type"], hdr["msg_type"]),
hdr["msg_num"], hdr["user_index"], hdr["options"],
hdr["metadata_len"], hdr["payload_len"]))
if DUMP_FRAMES:
log("RX #%d HEX:\n%s" % (n, hexdump(frame)))
if metadata:
log("RX #%d METADATA:\n%s" % (n, hexdump(metadata)))
if DUMP_FRAMES:
try:
os.makedirs(RXDIR, exist_ok=True)
fn = os.path.join(RXDIR, "rx_%04d_%04x_%04x.bin"
@@ -1509,6 +1565,7 @@ def blaze_handle(raw: socket.socket, addr) -> None:
if payload:
try:
fields = decode_tdf(payload)
if DUMP_FRAMES:
log("RX #%d TDF:\n%s" % (n, heat2.dump(fields)))
except Exception as e:
log("RX #%d TDF DECODE FAILED: %s" % (n, e))
@@ -1530,6 +1587,7 @@ def blaze_handle(raw: socket.socket, addr) -> None:
ohdr["msg_type"]),
MSGTYPE_NAME.get(ohdr["msg_type"], ohdr["msg_type"]),
ohdr["msg_num"], len(out), ohdr["payload_len"]))
if DUMP_FRAMES:
log("TX #%d.%d HEX:\n%s" % (n, k, hexdump(out, limit=1024)))
except ConnectionResetError:
log("BLAZE %s: connection reset by client" % (addr,))
@@ -1628,6 +1686,10 @@ def redir_handle(raw: socket.socket, addr) -> None:
# client can never reach accounts.ea.com. Note the exact spacing in the JSON:
# the client searches for the literal '"access_token" : "'.
def nucleus_sent_log(addr, size):
return "NUCLEUS SENT %s %dB access_token=[REDACTED]" % (addr, size)
def nucleus_handle(raw: socket.socket, addr) -> None:
try:
raw.settimeout(10)
@@ -1640,9 +1702,9 @@ def nucleus_handle(raw: socket.socket, addr) -> None:
head, _, rest = req.partition(b"\r\n\r\n")
line0 = head.split(b"\r\n", 1)[0].decode(errors="replace") if head else ""
log("NUCLEUS REQ %s: %s" % (addr, line0))
if head:
if head and DUMP_FRAMES:
log("NUCLEUS HEADERS:\n%s" % head.decode(errors="replace"))
if rest:
if rest and DUMP_FRAMES:
log("NUCLEUS BODY: %r" % rest[:512])
token = "OPENFUT_" + "".join(
@@ -1656,7 +1718,7 @@ def nucleus_handle(raw: socket.socket, addr) -> None:
b"Cache-Control: no-store\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\nConnection: close\r\n\r\n" + body)
raw.sendall(out)
log("NUCLEUS SENT %s %dB access_token=%s" % (addr, len(out), token))
log(nucleus_sent_log(addr, len(out)))
except Exception as e:
log("NUCLEUS ERR %s: %s" % (addr, e))
finally:
@@ -1708,6 +1770,10 @@ def _selftest() -> None:
sess.account_locale = 0x656E5553
now = 1469000000
nucleus_summary = nucleus_sent_log(("127.0.0.1", 1234), 380)
assert "[REDACTED]" in nucleus_summary
assert "OPENFUT_selftest_secret" not in nucleus_summary
# ---- 1. preAuth still round-trips (regression guard vs v2)
pre = preauth_response_fields()
p = _check_roundtrip("PreAuthResponse", pre)
@@ -1731,9 +1797,11 @@ def _selftest() -> None:
assert items == client_config_for(cfid), cfid
print("[ok] fetchClientConfig %-26s %2d keys, %4d payload bytes"
% (cfid, len(items), len(pb)))
assert client_config_for("TOTALLY_UNKNOWN") == [], "unknown CFID must be []"
shared = sorted(FUT_RS4_CONFIG + FUT_CONTENT_CONFIG + OSDK_POW)
assert client_config_for("TOTALLY_UNKNOWN") == shared, \
"unknown CFID must carry only the shared merged-store rows"
assert len(fetch_config_response_fields("TOTALLY_UNKNOWN")) == 1, \
"unknown CFID must still carry a CONF field (empty map, not empty frame)"
"unknown CFID must still carry a CONF field"
# ---- 3. LoginResponse
lr = login_response_fields(sess)
+18 -4
View File
@@ -158,6 +158,7 @@ launch() {
local trace_enabled=0
local request_trace_enabled=0
local notifier_trace_enabled=0
local commit_enabled=0
case "$mode" in
baseline)
[[ "${OPENFUT_FIFA17_LAUNCH:-}" == "I_ACCEPT_M1_BASELINE_LAUNCH" ]] ||
@@ -176,6 +177,15 @@ launch() {
request_trace_enabled=1
notifier_trace_enabled=1
;;
commit)
[[ "${OPENFUT_FIFA17_COMMIT:-}" == "I_ACCEPT_POST_PARSE_READY_BYTE" ]] ||
die "launch-commit requires OPENFUT_FIFA17_COMMIT=I_ACCEPT_POST_PARSE_READY_BYTE"
hook_enabled=1
trace_enabled=1
request_trace_enabled=1
notifier_trace_enabled=1
commit_enabled=1
;;
*) die "unknown launch mode: $mode" ;;
esac
need_file "$deployed_dll"
@@ -192,12 +202,12 @@ launch() {
[[ "$(sha256 "$deployed_dll")" == "$recorded" ]] ||
die "deployed version.dll does not match the staged M1 artifact"
command -v umu-run >/dev/null || die "umu-run is required"
for name in OPENFUT_SBC_DISPATCH OPENFUT_SBC_COMMIT OPENFUT_SBC_ARM_ONLY OPENFUT_SBC_POPULATE; do
for name in OPENFUT_SBC_DISPATCH OPENFUT_SBC_ARM_ONLY OPENFUT_SBC_POPULATE; do
[[ -z "${!name:-}" || "${!name}" == "0" ]] || die "$name must be unset or 0 for this launch"
done
mkdir -p "${wine_prefix}/dosdevices"
ln -sfn /mnt "${wine_prefix}/dosdevices/w:"
note "Launching $mode mode (SBC_HOOK=$hook_enabled; SBC_TRACE=$trace_enabled; SBC_REQUEST_TRACE=$request_trace_enabled; SBC_NOTIFIER_TRACE=$notifier_trace_enabled; every mutation feature disabled); log=/tmp/fifa17-hook-m1-launch.log"
note "Launching $mode mode (SBC_HOOK=$hook_enabled; SBC_TRACE=$trace_enabled; SBC_REQUEST_TRACE=$request_trace_enabled; SBC_NOTIFIER_TRACE=$notifier_trace_enabled; SBC_COMMIT=$commit_enabled); log=/tmp/fifa17-hook-m1-launch.log"
cd "$game_dir"
env \
GAMEID=fifa17 \
@@ -209,7 +219,7 @@ launch() {
OPENFUT_SBC_REQUEST_TRACE="$request_trace_enabled" \
OPENFUT_SBC_NOTIFIER_TRACE="$notifier_trace_enabled" \
OPENFUT_SBC_DISPATCH=0 \
OPENFUT_SBC_COMMIT=0 \
OPENFUT_SBC_COMMIT="$commit_enabled" \
OPENFUT_SBC_ARM_ONLY=0 \
OPENFUT_SBC_POPULATE=0 \
umu-run _fifa17.exe 2>&1 | tee /tmp/fifa17-hook-m1-launch.log
@@ -217,7 +227,7 @@ launch() {
usage() {
cat <<'EOF'
Usage: fifa17-hook-m1.sh [inspect|build|stage|deploy|launch|launch-resolve|launch-trace]
Usage: fifa17-hook-m1.sh [inspect|build|stage|deploy|launch|launch-resolve|launch-trace|launch-commit]
inspect Read-only PE/hash/export preflight (default).
build Cross-build the inert FIFA17 hook, then run inspect.
@@ -232,6 +242,9 @@ Usage: fifa17-hook-m1.sh [inspect|build|stage|deploy|launch|launch-resolve|launc
launch-trace
Start the single M3 passive factory/deserializer trace; requires:
OPENFUT_FIFA17_TRACE=I_ACCEPT_M3_PASSIVE_TRACE
launch-commit
Trace and arm the SBC cache only after a validated native parse; requires:
OPENFUT_FIFA17_COMMIT=I_ACCEPT_POST_PARSE_READY_BYTE
Optional path overrides:
OPENFUT_FIFA17_HOOK_DLL, OPENFUT_FIFA17_GAME_DIR,
@@ -247,6 +260,7 @@ case "${1:-inspect}" in
launch) launch baseline ;;
launch-resolve) launch resolve ;;
launch-trace) launch trace ;;
launch-commit) launch commit ;;
-h|--help|help) usage ;;
*) usage >&2; die "unknown command: $1" ;;
esac
+38 -1
View File
@@ -204,6 +204,7 @@ class Account:
def __init__(self, path=None):
self.path = path or ACCOUNT_PATH
self._loaded = False
self._file_signature = None
self._stored = {} # what is on disk (tier 2+3 only)
for f in _FIELDS:
setattr(self, "_" + f, None)
@@ -214,7 +215,8 @@ class Account:
save the first time. Never raises on a malformed file -- a broken
account file must not stop the harness booting."""
with _LOCK:
if self._loaded and not force:
signature = self._signature()
if self._loaded and not force and signature == self._file_signature:
return self
stored = {}
if os.path.exists(self.path):
@@ -239,8 +241,22 @@ class Account:
% (self.path, e))
self._stored = stored
self._loaded = True
self._file_signature = self._signature()
return self
def _signature(self):
"""Identity of the active-account file across atomic replacements.
The launcher can select an account while Blaze/POW are already running
in separate processes. inode + mtime + size lets every process notice
the replacement on its next property read without restarting Docker.
"""
try:
st = os.stat(self.path)
return st.st_dev, st.st_ino, st.st_mtime_ns, st.st_size
except OSError:
return None
def _migrate_from_profile(self):
"""Lift identity/club out of a pre-existing fifa17_profile.json so an
existing club name survives the move to this module. Read-only: the game
@@ -266,11 +282,32 @@ class Account:
return out
def _write(self):
parent = os.path.dirname(self.path)
if parent:
os.makedirs(parent, exist_ok=True)
tmp = self.path + ".tmp"
with open(tmp, "w") as f:
json.dump(self._stored, f, indent=1, sort_keys=True)
f.write("\n")
os.replace(tmp, self.path)
self._file_signature = self._signature()
def replace(self, values):
"""Atomically replace the active identity with validated persisted values."""
with _LOCK:
clean = {k: v for k, v in values.items() if k in _FIELDS and v is not None}
if "persona_id" not in clean or "persona_name" not in clean:
raise ValueError("persona_id and persona_name are required")
clean["persona_id"] = int(clean["persona_id"])
clean["persona_name"] = str(clean["persona_name"]).strip()
if clean["persona_id"] <= 0 or not clean["persona_name"]:
raise ValueError("persona_id must be positive and persona_name must not be empty")
self._stored = clean
for field in _FIELDS:
setattr(self, "_" + field, None)
self._loaded = True
self._write()
return self
def save(self):
"""Persist tiers 2+3 (only fields that differ from the built-in default,
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Launcher-to-server active-account selection for the single-player stack."""
import json
import os
from fut_account import ACCOUNT
from fut_store import STORE, profile_path_for
def _existing_identity(persona_id):
path = profile_path_for(persona_id)
try:
with open(path) as f:
profile = json.load(f)
except (OSError, ValueError):
return {}
if not isinstance(profile, dict):
return {}
return {
"club_name": profile.get("clubName"),
"club_abbr": profile.get("clubAbbr"),
"established": profile.get("established"),
"pow_level": profile.get("powLevel"),
"pow_exp": profile.get("powExp"),
"pow_exp_max": profile.get("powExpMax"),
"pow_funds": profile.get("powFunds"),
"pow_funds_cap": profile.get("powFundsCap"),
}
def activate(payload):
"""Select/create one persistent profile and publish it to all responders."""
if not isinstance(payload, dict):
raise ValueError("account payload must be an object")
try:
persona_id = int(payload.get("personaId"))
except (TypeError, ValueError):
raise ValueError("personaId must be a positive integer") from None
persona_name = payload.get("personaName")
if persona_id <= 0 or not isinstance(persona_name, str) or not persona_name.strip():
raise ValueError("personaId must be positive and personaName must not be empty")
values = _existing_identity(persona_id)
values.update(persona_id=persona_id, persona_name=persona_name.strip())
for wire, field in (("clubName", "club_name"), ("clubAbbr", "club_abbr"),
("established", "established"), ("squadName", "squad_name"),
("level", "pow_level"), ("experience", "pow_exp"),
("experienceMax", "pow_exp_max"), ("accountFunds", "pow_funds"),
("accountFundsCap", "pow_funds_cap")):
if payload.get(wire) not in (None, ""):
values[field] = payload[wire]
ACCOUNT.replace(values)
ACCOUNT.set_online_profile()
ACCOUNT.save()
profile = STORE.select_account(persona_id)
STORE.ensure_security_question()
return {
"personaId": ACCOUNT.persona_id,
"personaName": ACCOUNT.persona_name,
"clubName": ACCOUNT.club_name,
"clubAbbr": ACCOUNT.club_abbr,
"level": ACCOUNT.pow_level,
"experience": ACCOUNT.pow_exp,
"experienceMax": ACCOUNT.pow_exp_max,
"accountFunds": ACCOUNT.pow_funds,
"accountFundsCap": ACCOUNT.pow_funds_cap,
"profilePath": os.path.relpath(STORE.path, os.path.dirname(ACCOUNT.path)),
"coins": profile.get("coins", 0),
"unopenedPacks": len(profile.get("unopenedPackIds", [])),
}
+159 -11
View File
@@ -17,7 +17,19 @@ sys.path.insert(0, HERE)
import fut_cards
from fut_account import ACCOUNT # single source of truth for identity/club
PROFILE_PATH = os.environ.get("FUT_PROFILE", os.path.join(HERE, "fifa17_profile.json"))
PROFILE_ROOT = os.environ.get("FUT_PROFILE_ROOT", "")
def profile_path_for(persona_id):
explicit = os.environ.get("FUT_PROFILE")
if explicit:
return explicit
if PROFILE_ROOT:
return os.path.join(PROFILE_ROOT, str(int(persona_id)), "fifa17_profile.json")
return os.path.join(HERE, "fifa17_profile.json")
PROFILE_PATH = profile_path_for(ACCOUNT.persona_id)
# ---- FUT_DISCARD_TABLE: the REAL FIFA 17 quick-sell values ------------------
#
@@ -226,6 +238,56 @@ def _item(item_id, asset, rating, pos, nation, league, team, attrs, version=0x00
# the club showing different numbers for the same card.
SPECIAL_CARD_TYPES = {
# name: (rareflag, revision byte, rating/attribute boost, selection weight)
# rareflag names come from FIFA 17's ItemRareType enum. Revisions are local,
# stable identities; the client resolves the footballer from the low 24 bits.
"TOTW": (3, 1, 2, 34),
"PURPLE": (4, 2, 3, 7),
"TOTY": (5, 3, 6, 3),
"RECORD_BREAKER": (6, 4, 5, 2),
"TOTS": (11, 5, 5, 7),
"OTW": (21, 6, 2, 14),
"HALLOWEEN": (22, 7, 3, 8),
"MOVEMBER": (23, 8, 3, 8),
"SBC": (24, 9, 4, 17),
}
def choose_special_type(player, rng=None):
"""Choose a rating-appropriate FIFA 17 promo family for one pool row."""
import random
rng = rng or random
rating = player[1]
eligible = []
for name, spec in SPECIAL_CARD_TYPES.items():
if name in ("TOTY", "RECORD_BREAKER") and rating < 85:
continue
if name == "TOTS" and rating < 75:
continue
eligible.append((name, spec[3]))
names, weights = zip(*eligible)
return rng.choices(names, weights=weights, k=1)[0]
def player_item(item_id, player, special=False):
"""Build a base or named FIFA 17 special revision from a pool row.
`special=True` remains supported and chooses a weighted eligible family;
callers and tests may also pass an explicit name such as ``"TOTY"``.
"""
asset, rating, pos, nation, league, team, attrs = player
if special:
special_name = choose_special_type(player) if special is True else special
rareflag, version, boost, _weight = SPECIAL_CARD_TYPES[special_name]
rating = min(99, rating + boost)
attrs = [min(99, value + boost) for value in attrs]
else:
rareflag, version = 1, 0
return _item(item_id, asset, rating, pos, nation, league, team, attrs,
version=version, rareflag=rareflag)
# FUT_DISCARD_SEND: put discardValue (atom 0xd7) on the wire so the CLIENT DISPLAYS
# the same number the server pays.
#
@@ -293,6 +355,10 @@ def _new_profile():
"purchased": [], # unassigned/pending items from opened packs
"squads": [], # saved squads (raw squad objects from PUT /squad)
"packsOpened": 0,
# Owned reward packs are separate from purchased items. Pack 70 is a
# one-time migration grant used to bring the retail My Packs flow online.
"unopenedPackIds": [70],
"unopenedSeeded": True,
}
@@ -311,6 +377,10 @@ class Store:
self._p = _new_profile()
self._sync_identity()
self._save()
if not self._p.get("unopenedSeeded"):
self._p.setdefault("unopenedPackIds", []).append(70)
self._p["unopenedSeeded"] = True
self._save()
self._sync_identity()
return self._p
@@ -328,18 +398,51 @@ class Store:
p["clubName"] = ACCOUNT.club_name
p["clubAbbr"] = ACCOUNT.club_abbr
p["established"] = ACCOUNT.established
# EA/EASFC account-bar state belongs to the same persona as the FUT
# save, but remains a distinct balance from FUT coins.
p["powLevel"] = ACCOUNT.pow_level
p["powExp"] = ACCOUNT.pow_exp
p["powExpMax"] = ACCOUNT.pow_exp_max
p["powFunds"] = ACCOUNT.pow_funds
p["powFundsCap"] = ACCOUNT.pow_funds_cap
return p
def _save(self):
parent = os.path.dirname(self.path)
if parent:
os.makedirs(parent, exist_ok=True)
tmp = self.path + ".tmp"
with open(tmp, "w") as f:
json.dump(self._p, f, indent=1)
os.replace(tmp, self.path)
def select_account(self, persona_id):
"""Switch the single active session to its isolated persistent FUT save."""
with _LOCK:
self.path = profile_path_for(persona_id)
self._p = None
return self.load()
# ---- accessors used by utas_server -------------------------------------
def profile(self):
return self.load()
def ensure_security_question(self):
"""Persist OpenFUT's account-scoped compatibility state for the FUT gate.
FIFA 17 transforms any entered answer before sending it. OpenFUT does not
need that value to emulate a retired service, so neither the clear text nor
the transformed value is stored. The only durable fact is that this
OpenFUT profile has an initialized, verified compatibility record.
"""
expected = {"version": 1, "verified": True}
with _LOCK:
p = self.load()
if p.get("securityQuestion") != expected:
p["securityQuestion"] = dict(expected)
self._save()
return dict(p["securityQuestion"])
def refresh_identity(self):
"""Re-mirror ACCOUNT into the save AND persist it.
@@ -513,6 +616,32 @@ class Store:
sq = self.load()["squads"]
return sq[0] if sq else None
def unopened_packs(self):
"""Owned reward-pack template IDs, including repeated grants."""
return list(self.load().get("unopenedPackIds", []))
def consume_unopened_pack(self, pack_id):
"""Atomically consume one owned instance of a reward pack."""
with _LOCK:
p = self.load()
owned = p.setdefault("unopenedPackIds", [])
try:
owned.remove(pack_id)
except ValueError:
return False
self._save()
return True
def grant_unopened_pack(self, pack_id):
"""Persist one additional owned reward-pack instance."""
if pack_by_id(pack_id) is None:
return False
with _LOCK:
p = self.load()
p.setdefault("unopenedPackIds", []).append(pack_id)
self._save()
return True
def reconstruct_squad(self, squad):
"""FIFA's updateActiveSquad PUT stores each slot as itemData={id:<clubItemId>}
(a reference). Re-embed the FULL club item by id so the squad reloads with
@@ -557,7 +686,8 @@ class Store:
return i
def open_pack(self, price, count, gold=True, tiers=None):
def open_pack(self, price, count, gold=True, tiers=None, special_chance=0.0,
players_only=False):
"""Deduct `price` coins, generate `count` player items from the pool, and
place them in the PENDING purchased pile (unassigned). They are NOT owned
club items until moved there via FutMoveCard (PUT /item). Returns None if
@@ -579,19 +709,31 @@ class Store:
# fixed number so it scales from a 5-card bronze to an 11-card premium.
n_extra = 0
extras = []
if PACK_MIX and count >= 5:
if PACK_MIX and not players_only and count >= 5:
n_extra = max(1, count // 4)
extras = _pack_extras(n_extra, self)
n_extra = len(extras)
n_players = max(1, count - n_extra)
if tiers:
picks = [random.choice(fut_cards.pool_for(random.choice(tiers)))
for _ in range(n_players)]
# Draw each tier independently but reject duplicate asset IDs inside
# one pack. The real pool is large enough that this normally succeeds
# on the first attempt; the cap makes malformed tiny test pools safe.
picks = []
used_assets = set()
for _ in range(n_players):
tier_pool = fut_cards.pool_for(random.choice(tiers))
available = [p for p in tier_pool if p[0] not in used_assets]
pick = random.choice(available or tier_pool)
picks.append(pick)
used_assets.add(pick[0])
else:
pool = [p for p in PACK_POOL if (p[1] >= 75) == gold] or PACK_POOL
picks = [random.choice(pool) for _ in range(n_players)]
items = [_item(self.new_item_id(), a, r, p, n, lg, tm, at)
for (a, r, p, n, lg, tm, at) in picks]
picks = random.sample(pool, min(n_players, len(pool)))
while len(picks) < n_players:
picks.append(random.choice(pool))
items = [player_item(self.new_item_id(), pick,
special=random.random() < special_chance)
for pick in picks]
items += extras
random.shuffle(items)
with _LOCK:
@@ -677,11 +819,17 @@ _LEGACY_POOL = STARTER_PLAYERS + [
# no silver or bronze players at all, so all three packs were identical in practice.
PACK_CATALOG = [
{"id": 1, "name": "Bronze Pack", "price": 400, "count": 5, "gold": False,
"tiers": ["bronze"] * 8 + ["silver"] * 2},
"tiers": ["bronze"] * 8 + ["silver"] * 2, "specialChance": 0.005},
{"id": 5, "name": "Gold Pack", "price": 5000, "count": 7, "gold": True,
"tiers": ["gold"] * 6 + ["silver"] * 4},
"tiers": ["gold"] * 6 + ["silver"] * 4, "specialChance": 0.03},
{"id": 6, "name": "Premium Gold", "price": 15000, "count": 11, "gold": True,
"tiers": ["gold"] * 9 + ["silver"] * 1},
"tiers": ["gold"] * 9 + ["silver"] * 1, "specialChance": 0.08},
{"id": 7, "name": "Special Players Pack", "price": 25000, "count": 11,
"gold": True, "tiers": ["gold"], "specialChance": 1.0,
"playersOnly": True},
{"id": 70, "name": "Reward Special Players Pack", "price": 0, "count": 11,
"gold": True, "tiers": ["gold"], "specialChance": 1.0,
"playersOnly": True, "ownedOnly": True},
]
@@ -0,0 +1,25 @@
"""Trace FutPurchaseDraftModeServerResponse beyond its known seven-int parser."""
cls = "FutPurchaseDraftModeServerResponse"
print("CLASS", cls, class_deser(cls))
seen = set()
for deser, vt, factory in class_deser(cls):
print("\nVTABLE", hex(vt), "FACTORY", hex(factory), "DESER", hex(deser))
print(vtable(vt, 32))
for target in [factory, deser] + [t for _, t, name in vtable(vt, 32) if name]:
if target in seen:
continue
seen.add(target)
print("\n===", hex(target), fname(target), "===")
print(dec(target, 300))
print("XREFS", xrefs_to(target)[:100])
for target in (0x18014C090, 0x18014C260, 0x18014C820, 0x18014C8A0):
if target in seen:
continue
print("\n=== CANDIDATE", hex(target), fname(target), "===")
print(dec(target, 300))
print("XREFS", xrefs_to(target)[:100])
print("QUERY_DONE")
@@ -0,0 +1,22 @@
"""Bind the live draft-purchase URI builder to one of its two response factories."""
for literal in (
"purchase/mode/",
"/purchase/mode/",
"draft",
"ut/%s/draft/mode",
"FutPurchaseDraftModeServerResponse",
):
print("\nLITERAL", repr(literal))
for hit in find_all(literal.encode() + b"\x00"):
print(hex(hit), rd_str(hit), xrefs_to(hit)[:100])
for target in (0x180224EF8, 0x1802262F0, 0x18014C090, 0x180150260):
print("\nTARGET", hex(target), fname(target))
print("XREFS", xrefs_to(target)[:200])
for frm, typ, fn, ent in xrefs_to(target):
if ent:
print("\nOWNER", hex(ent), fn)
print(dec(ent, 300))
print("QUERY_DONE")
@@ -0,0 +1,16 @@
"""Dump both request vtables sharing FutPurchaseDraftModeServerResponse."""
for vt in (0x180226300, 0x180224F08):
print("\nREQUEST_VTABLE", hex(vt))
rows = vtable(vt, 40)
print(rows)
seen = set()
for off, target, name in rows:
if not name or target in seen:
continue
seen.add(target)
print("\n=== SLOT", hex(off), hex(target), name, "===")
print(dec(target, 300))
print("XREFS", xrefs_to(target)[:100])
print("QUERY_DONE")
@@ -0,0 +1,23 @@
"""Recover the JSON element shape consumed by the array-root draft response."""
targets = (
0x180138BD0, # helper called once per array element
0x180150310, # array-root FutPurchaseDraftModeServerResponse parser
)
seen = set()
for target in targets:
print("\n=== TARGET", hex(target), fname(target), "===")
print(dec(target, 500))
print("XREFS", xrefs_to(target)[:150])
# Include direct callees so small string/value accessors used by the helper
# are visible without broad, noisy whole-program searching.
for callee, name in callees(target):
if callee in seen:
continue
seen.add(callee)
print("\n--- CALLEE", hex(callee), name, "---")
print(dec(callee, 250))
print("QUERY_DONE")
@@ -0,0 +1,17 @@
"""Trace active draft-state enum literals and the current-state response consumers."""
for literal in ("DRAFTSQUAD_ON", "DRAFTSQUAD_OFF", "DRAFT_SQUAD", "squadState",
"stateParam1", "stateParam2", "roundsInfo"):
print("\n=== LITERAL", literal, "===")
for hit in find_all(literal.encode() + b"\x00", (".rdata", ".data")):
print("HIT", hex(hit), "XREFS", xrefs_to(hit)[:100])
for _frm, _typ, _name, entry in xrefs_to(hit):
print("\n--- XREF FUNCTION", hex(entry), fname(entry), "---")
print(dec(entry, 500))
for target in (0x180147070,):
print("\n=== STATE DESERIALIZER", hex(target), fname(target), "===")
print(dec(target, 500))
print("CALLERS", callers(target))
print("QUERY_DONE")
@@ -0,0 +1,21 @@
"""Resolve draft-state atom IDs to their authoritative wire strings."""
ATOM_TABLE = 0x1802D2760
def atom_name(index):
pointer = qword(ATOM_TABLE + index * 8)
return rd_str(pointer, 96)
groups = {
"squadState values": (0x1AC, 0x6A, 0x9C, 0x12C, 0x169, 0x225, 0x23E, 0x277, 0x278),
"stateParam1 values": (0x169, 0x1AA, 0x22D),
"entranceCriteria keys": (0x96, 0xDF, 0x241),
"top-level keys": (0x108, 0x13B, 0x293, 0x2CD, 0x2D5, 0x2EE, 0x2EF),
}
for group, indices in groups.items():
print("\n===", group, "===")
for index in indices:
print(hex(index), repr(atom_name(index)))
print("QUERY_DONE")
@@ -0,0 +1,50 @@
"""Resolve the concrete owner behind request+0x08 for the SBC category request.
q_md_sbc_9 proved generic slot +0x88 (0x1801631e0) invokes:
owner = *(request + 8)
owner.vtable[+0x18](owner, parsed_response, 0)
Work backwards from the category request constructor and its callers to identify who
supplies request+8, then map candidate owner vtables and their +0x18 consumers.
"""
import traceback
try:
def show(a, label):
f = func(a)
print("\n=== %s %#x %s ===" % (label, a, f.getName() if f else "?"))
print(dec(a))
ctor = 0x18017a7c0
show(ctor, "category request constructor")
print("\n=== ctor callers ===")
for ent, name in callers(ctor):
print(" %#x %s" % (ent, name))
show(ent, "ctor caller")
print("\n=== ctor xrefs ===")
for frm, typ, name, ent in xrefs_to(ctor):
print(" from=%#x type=%s fn=%s entry=%#x" % (frm, typ, name, ent))
# The request base constructor is usually visible as the first direct call in
# the category constructor. Dump every direct callee so request+8 initialization
# can be distinguished from URI/tag setup.
print("\n=== constructor direct callees ===")
for target, name in callees(ctor):
print(" %#x %s" % (target, name))
show(target, "ctor callee")
# Ghidra did not create a function at the traced +0x90 thunk. Print its raw
# instructions and nearby containing-function identity without assuming a body.
print("\n=== raw callback thunk at 0x180154830 ===")
ad = addr(0x180154830)
for _ in range(48):
ins = listing.getInstructionAt(ad)
if ins is None:
print(" %s <not disassembled>" % ad)
ad = ad.add(1)
continue
print(" %s %s" % (ad, ins))
ad = ins.getNext().getAddress() if ins.getNext() else ad.add(ins.getLength())
except Exception:
traceback.print_exc()
@@ -0,0 +1,34 @@
"""Trace the FUT-root constructor's third argument, inherited by every request at +8.
The category request lives at FUT root +0x4140 (qword index 0x828). Its base ctor
stores the root constructor's param_3 at request+8, making that object the receiver
of owner.vtable[+0x18](owner, parsed_response, 0).
"""
import traceback
try:
root_ctor = 0x18010cdc0
print("=== root ctor callers ===")
for ent, name in callers(root_ctor):
print("\n--- %#x %s ---" % (ent, name))
print(dec(ent))
print("\n=== root ctor xrefs ===")
for frm, typ, name, ent in xrefs_to(root_ctor):
print(" from=%#x type=%s fn=%s entry=%#x" % (frm, typ, name, ent))
if ent:
print(dec(ent))
# Static singleton slot and root vtables provide adjacent factory/type metadata.
for site in (0x1802e6398, 0x18021c2a0, 0x18021cda8, 0x18021cdb8):
print("\n=== qwords around %#x ===" % site)
for i in range(-8, 16):
p = site + i * 8
try:
value = qword(p)
except Exception:
continue
print(" [%#x] = %#x %s" % (p, value, fname(value)))
except Exception:
traceback.print_exc()
@@ -0,0 +1,29 @@
"""Map the category success notifier already instrumented at 0x18017aa80.
The checkpoint hook can passively record ctx+0x88 and the +0x58..+0x60 handler
vector. Establish where this notifier sits relative to request ownership transfer and
whether it is the concrete receiver-side publication path we need to observe live.
"""
import traceback
try:
target = 0x18017aa80
print("=== notifier 0x18017aa80 ===")
print(dec(target))
print("\n=== notifier callers ===")
for ent, name in callers(target):
print(" %#x %s" % (ent, name))
print(dec(ent))
print("\n=== notifier xrefs ===")
for frm, typ, name, ent in xrefs_to(target):
print(" from=%#x type=%s fn=%s entry=%#x" % (frm, typ, name, ent))
# Adjacent category request methods often expose the notifier through a vtable
# or callback descriptor; inspect nearby functions and data references.
for a in (0x18017aa80, 0x18017aaf0, 0x18017ab80, 0x18017b1c0):
f = func(a)
print("\n=== %#x %s ===" % (a, f.getName() if f else "?"))
print(dec(a))
except Exception:
traceback.print_exc()
@@ -0,0 +1,31 @@
"""Map the sole live category-notifier listener into CardsDLL.
Live capture 2026-08-07:
listener object 0x4216ca48
listener vtable 0x6ffffc20d6d0
vtable +0x08 0x6ffffc1e577a
CardsDLL slide 0x6ffe7c020000
static method 0x1801c577a
"""
TARGET = 0x1801C577A
VTABLE = 0x1801ED6D0
print("=== live notifier listener method ===")
target_function = func(TARGET)
if target_function is None:
print("no Ghidra function at %#x" % TARGET)
print("raw PE decoding: jmp [0x1801e5200], imported CRT _purecall")
else:
print("containing function:", target_function.getName(),
hex(int(target_function.getEntryPoint().getOffset())))
print(dec(TARGET))
print("\n=== listener vtable ===")
for slot, target, name in vtable(VTABLE, 12):
print("%+#04x %#x %s" % (slot, target, name))
print("\n=== method callers/xrefs ===")
print("callers:", callers(TARGET) if target_function is not None else [])
for row in xrefs_to(TARGET):
print(row)
@@ -0,0 +1,29 @@
"""Find concrete siblings of the live notifier listener's abstract vtable."""
import struct
VTABLE = 0x1801ED6D0
DTOR = 0x180018EF0
PURECALL_THUNK = 0x1801C577A
print("=== exact vtable references ===")
for row in xrefs_to(VTABLE):
print(row)
print("\n=== vtables sharing the live listener destructor ===")
for hit in find_all(struct.pack("<Q", DTOR), blocks=(".rdata", ".data")):
try:
slots = [qword(hit + i * 8) for i in range(12)]
except Exception:
continue
# Require the same broad interface shape: destructor in slot 0 and at least
# one CardsDLL code pointer after it. This filters incidental data matches.
if slots[0] != DTOR or not any(0x180000000 <= x < 0x1801E5000 for x in slots[1:]):
continue
print("vtable=%#x slot8=%#x %s" %
(hit, slots[1], "PURE" if slots[1] == PURECALL_THUNK else "CONCRETE"))
for i, target in enumerate(slots):
print(" +%#04x %#x %s" % (i * 8, target, fname(target)))
refs_here = xrefs_to(hit)
if refs_here:
print(" refs:", refs_here)
@@ -0,0 +1,31 @@
"""Locate event 0x753c users and category-listener registration/removal paths."""
import struct
EVENT = 0x753C
NOTIFIER = 0x18017AA80
print("=== immediate/data occurrences of event 0x753c ===")
seen = set()
for hit in find_all(struct.pack("<I", EVENT)):
print("hit", hex(hit))
owner = func(hit)
if owner is not None:
entry = int(owner.getEntryPoint().getOffset())
print(" containing", hex(entry), owner.getName())
seen.add(entry)
for row in xrefs_to(hit):
print(" ", row)
if row[3]:
seen.add(row[3])
print("\n=== decompile functions referencing event literal ===")
for entry in sorted(seen):
print("\n--- %#x %s ---" % (entry, fname(entry)))
print(dec(entry))
print("\n=== category request ctor/dtor and notifier neighborhood ===")
for target in (0x18017A7C0, 0x18017AA10, NOTIFIER, 0x18017AAF0, 0x18017B1C0):
print("\n--- %#x %s ---" % (target, fname(target)))
print("callers", callers(target))
print("xrefs", xrefs_to(target))
@@ -0,0 +1,16 @@
"""Resolve the SBC controller and its 0x756c refresh registration/dispatch contract."""
TARGETS = (
(0x1800B5260, "SBC controller allocation/ctor neighborhood"),
(0x1800B53F0, "SBC controller constructor"),
(0x1800B5760, "SBC service/controller constructor"),
(0x1800B5E00, "SBC tile builder"),
(0x1801A4A70, "event registration"),
(0x1801A4CD0, "event dispatch"),
)
for target, label in TARGETS:
print("\n=== %s %#x %s ===" % (label, target, fname(target)))
print(dec(target))
print("callers", callers(target))
print("xrefs", xrefs_to(target))
@@ -0,0 +1,10 @@
"""Decompile the concrete SBC controller event-listener vtable."""
VTABLE = 0x18020A888
print("=== SBC controller event subobject vtable ===")
for off in range(0, 0x80, 8):
target = qword(VTABLE + off)
print("\nslot +%#x -> %#x %s" % (off, target, fname(target)))
if 0x180001000 <= target < 0x180200000:
print(dec(target, 180))
print("callers", callers(target)[:30])
@@ -0,0 +1,7 @@
"""Follow the SBC category-completion continuation registered by event 0x753c."""
for target in (0x1800B8950, 0x1800B89D0, 0x1800B8C30, 0x1800BA460, 0x1800B7090):
print("\n=== %#x %s ===" % (target, fname(target)))
print(dec(target, 300))
print("callers", callers(target)[:50])
print("xrefs", xrefs_to(target)[:50])
@@ -0,0 +1,10 @@
"""Resolve manager +0xe0 used to schedule the ServerErrSets continuation."""
for target in (0x180009C80, 0x1800D7170, 0x180154830, 0x1801631E0):
print("\n=== %#x %s ===" % (target, fname(target)))
print(dec(target, 300))
print("xrefs", xrefs_to(target)[:80])
print("\n=== candidate manager vtables referencing category request callbacks ===")
for target in (0x1800B8950, 0x18017AA80, 0x18017B2B0):
print(hex(target), xrefs_to(target)[:100])
@@ -0,0 +1,21 @@
"""Find completion callbacks that test the same status field at response+0x1c."""
patterns = (
bytes.fromhex("83 7a 1c 00"), # cmp dword ptr [rdx+1c],0
bytes.fromhex("83 79 1c 00"), # cmp dword ptr [rcx+1c],0
bytes.fromhex("83 78 1c 00"), # cmp dword ptr [rax+1c],0
)
seen = set()
for pattern in patterns:
print("\npattern", pattern.hex())
for hit in find_all(pattern):
f = func(hit)
if f is None:
continue
entry = int(f.getEntryPoint().getOffset())
if entry in seen:
continue
seen.add(entry)
print("\n=== hit %#x function %#x %s ===" % (hit, entry, f.getName()))
print(dec(f, 180)[:5000])
@@ -0,0 +1,14 @@
"""Map the live category response object's vtable and status-bearing base class."""
VTABLE = 0x18022E5B0
print("=== live category response vtable ===")
print("vtable xrefs", xrefs_to(VTABLE)[:100])
for off in range(0, 0x100, 8):
target = qword(VTABLE + off)
print("slot +%#x -> %#x %s" % (off, target, fname(target)))
if 0x180001000 <= target < 0x180200000 and off < 0x60:
print(dec(target, 120)[:3000])
print("\n=== direct references to vtable entries/address ===")
for a in range(VTABLE - 0x20, VTABLE + 0x20, 8):
print(hex(a), xrefs_to(a)[:40])
@@ -0,0 +1,22 @@
"""Find static assignments/usages of completion status 999 (0x3e7)."""
patterns = []
for modrm in (0x40, 0x41, 0x42, 0x43, 0x46, 0x47, 0x80, 0x81, 0x82, 0x83, 0x86, 0x87):
patterns.append(bytes((0xC7, modrm, 0x1C, 0xE7, 0x03, 0x00, 0x00)))
patterns.extend((bytes.fromhex("b8 e7 03 00 00"), bytes.fromhex("b9 e7 03 00 00"),
bytes.fromhex("ba e7 03 00 00"), bytes.fromhex("41 b8 e7 03 00 00")))
seen = set()
for pattern in patterns:
for hit in find_all(pattern):
f = func(hit)
entry = int(f.getEntryPoint().getOffset()) if f else 0
key = (entry, hit)
if key in seen:
continue
seen.add(key)
print("\n=== pattern %s hit %#x function %#x %s ===" %
(pattern.hex(), hit, entry, f.getName() if f else "?"))
if f:
print(dec(f, 240)[:10000])
print("callers", callers(f)[:80])
@@ -0,0 +1,8 @@
"""Trace callers of the HTTP/FUT status mapper returning 999."""
for target in (0x1801844C0, 0x180163120, 0x180165050, 0x180165CC0,
0x18016C060, 0x180184A90):
print("\n=== %#x %s ===" % (target, fname(target)))
print(dec(target, 300)[:18000])
print("callers", callers(target)[:100])
print("xrefs", xrefs_to(target)[:100])
@@ -0,0 +1,26 @@
"""Decompile the transport-result conversion and SBC response base methods."""
TARGETS = (
0x180184420,
0x1801844C0,
0x180184A90,
0x180163120,
0x1801631E0,
0x180165050,
0x180165CC0,
0x18016C060,
0x18016C110,
0x18016C950,
0x18016CA40,
0x18016CAC0,
0x18016CB20,
0x18016CB90,
0x18016CBE0,
0x18016CCA0,
0x18016D230,
)
for address in TARGETS:
print("\n===== %#x %s =====" % (address, fname(address)))
print(dec(address, 60))
@@ -0,0 +1,31 @@
"""Enumerate CardsDLL instructions that write a dword-like value to object +0x1c.
This is intentionally a read-only listing query. It finds explicit memory writes whose
rendered destination operand contains displacement 0x1c, then groups them by function.
"""
listing = prog.getListing()
seen = set()
for insn in listing.getInstructions(True):
text = insn.toString().lower()
if "0x1c" not in text and "+1ch" not in text:
continue
refs = insn.getReferencesFrom()
has_write = any(ref.getReferenceType().isWrite() for ref in refs)
# Register-relative memory writes do not always produce a Ghidra reference, so retain
# the common write mnemonics and require the first rendered operand to contain +0x1c.
mnemonic = insn.getMnemonicString().lower()
dst = insn.getDefaultOperandRepresentation(0).lower()
if "0x1c" not in dst and "+1ch" not in dst:
continue
if not has_write and mnemonic not in ("mov", "movzx", "and", "or", "xor", "inc", "dec"):
continue
owner = func(int(insn.getAddress().getOffset()))
entry = int(owner.getEntryPoint().getOffset()) if owner else 0
key = (entry, int(insn.getAddress().getOffset()))
if key in seen:
continue
seen.add(key)
print("%#x function=%#x %s :: %s" %
(key[1], entry, owner.getName() if owner else "?", insn.toString()))
@@ -0,0 +1,7 @@
"""Inspect the two additional CardsDLL functions with explicit dword writes to +0x1c."""
for target in (0x180171970, 0x1801790A0):
print("\n===== %#x %s =====" % (target, fname(target)))
print(dec(target, 180))
print("callers", callers(target)[:100])
print("xrefs", xrefs_to(target)[:100])
@@ -0,0 +1,61 @@
"""Continue the SBC response handoff analysis after the 2026-08-07 passive trace.
Proven live boundary:
request +0x80 factory -> response 0x18022e5b0
response +0x08 -> 0x18017b2b0 returns true
request +0x90 -> parsed response callback returns normally
request +0x88 -> ownership transfer returns normally
The next unknown is the receiving owner's virtual +0x18 consumer called by
0x1801631e0. Recover the concrete receiver, its vtable, and downstream publication.
"""
import traceback
try:
def dump_function(a, label):
f = func(a)
print("\n=== %s @%#x (%s) ===" % (label, a, f.getName() if f else "?"))
if f:
print("entry=%s body=%s" % (f.getEntryPoint(), f.getBody()))
print(dec(a))
def dump_instructions(a, before=0, count=80):
f = func(a)
print("\n=== instructions around %#x ===" % a)
if not f:
return
rows = []
for ad in f.getBody().getAddresses(True):
ins = listing.getInstructionAt(ad)
if ins:
rows.append(ins)
pivot = next((i for i, ins in enumerate(rows)
if int(ins.getAddress().getOffset()) >= a), 0)
for ins in rows[max(0, pivot-before):pivot+count]:
print(" %s %s" % (ins.getAddress(), ins))
dump_function(0x1801631e0, "post-request ownership handoff / owner consumer")
dump_instructions(0x1801631e0, count=120)
print("\n=== callers/xrefs of 0x1801631e0 ===")
for ent, name in callers(0x1801631e0):
print(" caller %#x %s" % (ent, name))
print(dec(ent))
for frm, typ, name, ent in xrefs_to(0x1801631e0):
print(" xref from=%#x type=%s fn=%s entry=%#x" %
(frm, typ, name, ent))
request_vtable = 0x18022e5c0
print("\n=== category request vtable %#x ===" % request_vtable)
for off, target, name in vtable(request_vtable, 40):
print(" +%#04x -> %#x %s" % (off, target, name))
for slot, label in ((0x80, "typed factory"),
(0x88, "ownership transfer"),
(0x90, "completion callback")):
target = qword(request_vtable + slot)
dump_function(target, "request %s slot +%#x" % (label, slot))
dump_instructions(target, count=100)
except Exception:
traceback.print_exc()
@@ -0,0 +1,30 @@
"""Find indirect calls to service-interface slot +0xe0 and compare contracts."""
PATTERNS = (
bytes.fromhex("ff 90 e0 00 00 00"),
bytes.fromhex("ff 91 e0 00 00 00"),
bytes.fromhex("ff 92 e0 00 00 00"),
bytes.fromhex("ff 93 e0 00 00 00"),
bytes.fromhex("ff 96 e0 00 00 00"),
bytes.fromhex("ff 97 e0 00 00 00"),
bytes.fromhex("41 ff 90 e0 00 00 00"),
bytes.fromhex("41 ff 91 e0 00 00 00"),
bytes.fromhex("41 ff 92 e0 00 00 00"),
bytes.fromhex("41 ff 93 e0 00 00 00"),
)
seen = set()
for pattern in PATTERNS:
for hit in find_all(pattern, blocks=(".text",)):
owner = func(hit)
if owner is None:
continue
entry = int(owner.getEntryPoint().getOffset())
if entry in seen:
continue
seen.add(entry)
print("\n===== call %#x function %#x %s =====" %
(hit, entry, owner.getName()))
print(dec(owner, 120)[:12000])
print("callees", callees(owner)[:80])
@@ -0,0 +1,27 @@
"""Map the FIFA response-registry primitives surrounding state-3 completion."""
TARGETS = (
0x145336C50,
0x145336E60,
0x1453370B0,
0x1453371B0,
0x145337B20,
0x1453388A0,
0x145338950,
0x145339650,
0x1453396A0,
0x145339B10,
0x145374E10,
0x145375070,
0x145376200,
0x145376270,
0x1453762E0,
0x145376360,
)
for target in TARGETS:
print("\n===== %#x %s =====" % (target, fname(target)))
print(dec(target, 180)[:16000])
print("callers", callers(target)[:120])
print("callees", callees(target)[:120])
@@ -0,0 +1,16 @@
"""Analyze the unpacked FIFA17 SBC completion route offline."""
TARGETS = (
(0x146B805B0, "SBC request owner thunk"),
(0x145374E80, "generic request-state dispatcher"),
(0x145376270, "state-3 completion handler"),
(0x1453388A0, "response registry lookup (manager mode 1)"),
(0x145338950, "response registry lookup (manager mode 2)"),
(0x146162F50, "completion broadcast invoked on lookup miss"),
)
for target, label in TARGETS:
print("\n=== %s %#x %s ===" % (label, target, fname(target)))
print(dec(target, 300))
print("callers", callers(target)[:100])
print("xrefs", xrefs_to(target)[:100])
@@ -0,0 +1,17 @@
"""Resolve the two data tables that reference the SBC request-owner thunk."""
THUNK = 0x146B805B0
REFERENCES = (0x14366D3E0, 0x14381B5D0)
print("thunk bytes", read_bytes(THUNK, 32).hex(" "))
for reference in REFERENCES:
print("\n=== reference %#x ===" % reference)
print("raw", read_bytes(reference - 0x40, 0x90).hex(" "))
for slot in range(reference - 0x40, reference + 0x48, 8):
target = qword(slot)
print("%#x rel=%+#x -> %#x %s xrefs=%s" %
(slot, slot - reference, target, fname(target), xrefs_to(slot)[:8]))
if func(target) is not None:
print(dec(target, 60)[:5000])
+27 -9
View File
@@ -15,16 +15,27 @@ reimplementations (the `tdf` crate cloned in this scratchpad), which were used
only as a cross-check of *structure*, never copied.
NO EA/FIFA leaked source was consulted.
VALIDATED RULES (byte-exact round-trip against the 219-byte capture)
--------------------------------------------------------------------
Fire2 frame header, 16 bytes big-endian:
[0:4] u32 payload length (bytes after the header)
[4:6] u16 always 0 (observed)
VALIDATED RULES (the TDF body; byte-exact round-trip against the 219-byte capture)
---------------------------------------------------------------------------------
Fire2 frame header, 16 bytes big-endian.
!!! SUPERSEDED — the [10:16] FIELD SEMANTICS below are WRONG for FIFA 17. !!!
The "byte-exact round-trip" only proves the payload length and the TDF body
encoding: decoding then re-encoding with the SAME (mis)labelled header layout
trivially reproduces the capture, so it never tested the header's field
boundaries. The authoritative, live-driven layout is
`openfut-protocol-blaze::fire2` / `blaze_responder_v3b.py::fire2`:
[0:4] u32 payload length (bytes after header + metadata)
[4:6] u16 metadata length (0 when absent — what this file called "always 0")
[6:8] u16 component
[8:10] u16 command
[10:12]u16 error / msgId
[12] u8 msgType (0x01 ping, 0x02 request, 0x03 pong/response)
[13:16]3 reserved bytes (observed 00 00 00)
[10:13] u24 msgNum (this file WRONGLY split it as [10:12] msgId + [12] msgType)
[13] u8 (msgType << 5) | (userIndex & 0x1F)
[14] u8 options
[15] u8 reserved
There is NO error field in Fire2 (that is Fire v1) and NO jumbo escape — the
length is already a full u32. `build_fire2_frame`/`decode_fire2` below keep the
old wrong `>IHHHHB3s` layout; they are dead and retained only for history.
Heat2 field = 3-byte packed tag + 1 type byte + value.
@@ -359,7 +370,14 @@ MSG_ERROR = 0x05 # UNVERIFIED
def build_fire2_frame(component: int, command: int, msgType: int,
msgId: int, tdf_bytes: bytes) -> bytes:
"""16-byte big-endian Fire2 header + TDF payload."""
"""16-byte big-endian Fire2 header + TDF payload.
WRONG HEADER (dead code): the ``>IHHHHB3s`` layout mislabels [10:16] — it
puts a u16 msgId at [10:12] and msgType at [12]. FIFA 17's real Fire2 header
is [10:13] u24 msgNum, [13] (msgType<<5)|userIndex, [14] options, [15]
reserved, and has no error field. Use ``openfut-protocol-blaze::fire2`` or
``blaze_responder_v3b.py::fire2``; this is retained only for history.
"""
tdf_bytes = bytes(tdf_bytes)
hdr = struct.pack(">IHHHHB3s", len(tdf_bytes), 0, component & 0xFFFF,
command & 0xFFFF, msgId & 0xFFFF, msgType & 0xFF,
+27 -8
View File
@@ -162,6 +162,22 @@ def log(*a):
print("[lsx]", *a, flush=True)
_SECRET_ATTR_RE = re.compile(
r'(?i)\b(AuthCode|AuthToken|SessionKey|Token|Sid)="[^"]*"')
_AUTH_CODE_ATTR_RE = re.compile(r'(?i)\b(value|Code|Return)="[^"]*"')
_CHALLENGE_ATTR_RE = re.compile(r'(?i)\b(response)="[^"]*"')
def safe_xml_for_log(xml):
"""Redact credential-bearing LSX attributes from ordinary diagnostics."""
safe = _SECRET_ATTR_RE.sub(lambda m: '%s="[REDACTED]"' % m.group(1), xml)
if "<AuthCode " in safe:
safe = _AUTH_CODE_ATTR_RE.sub(lambda m: '%s="[REDACTED]"' % m.group(1), safe)
if "<ChallengeAccepted " in safe:
safe = _CHALLENGE_ATTR_RE.sub(lambda m: '%s="[REDACTED]"' % m.group(1), safe)
return safe
# ---------------------------------------------------------------- crypto
# (verbatim from v1 -- verified end-to-end by decrypting captured
# captures/lsx/lsx_raw/C1_ENC-IN_*.bin. DO NOT TOUCH.)
@@ -389,8 +405,7 @@ def build_reply(mid, req_name, attrs, conn, recipient=""):
conn.stop_events = True
log("*** GetAuthCode ISSUED ***")
log(f" ClientId={client_id!r} Scope={scope!r}")
log(f" code={code} -- this must arrive as Blaze "
f"LoginRequest.AUTH in Authentication::login (1/0x0A)")
log(" code=[REDACTED] -- issued for Blaze Authentication::login (1/0x0A)")
return resp(mid,
f'AuthCode value="{code}" Code="{code}" Return="{code}"')
@@ -489,8 +504,7 @@ def serve(sock, addr):
client_resp = mr.group(1) if mr else ""
h = challenge_response(client_key, client_resp)
conn.key = derive_session_key(h)
log(f"client key={client_key} response={h[:16]}... "
f"session_key={conn.key.hex()}")
log("handshake accepted; session crypto initialized")
# 3. plaintext ChallengeAccepted
conn.send_plain(resp(1, f'ChallengeAccepted response="{h}"', "EALS"))
@@ -525,7 +539,7 @@ def serve(sock, addr):
continue
mm = REQ_RE.search(xml)
if not mm:
log("<<", xml)
log("<<", safe_xml_for_log(xml))
continue
mid, name, rest = mm.group(1), mm.group(2), mm.group(3)
attrs = dict(ATTR_RE.findall(rest))
@@ -533,7 +547,7 @@ def serve(sock, addr):
recip = rm.group(1) if rm else ""
reply = build_reply(mid, name, attrs, conn, recip)
log(f"<< id={mid} {name} recipient={recip!r} {attrs}")
log(f">> {reply}")
log(">>", safe_xml_for_log(reply))
conn.send_enc(reply)
why = PUSH_AFTER.get(name)
@@ -560,7 +574,7 @@ def serve(sock, addr):
def main():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", 4216))
s.bind((os.environ.get("OPENFUT_BIND", "127.0.0.1"), 4216))
s.listen(8)
log("v2 listening on 127.0.0.1:4216 (start FIFA 17 now)")
log(f"login-state event push: {'ENABLED' if EVENTS_ENABLED else 'DISABLED'}"
@@ -591,7 +605,12 @@ def selftest():
# 'value' is the only attribute lsx::AuthCodeT's deserializer (0x1471312a0)
# actually reads; Code=/Return= are legacy padding.
assert '<AuthCode value=' in r, r
print("[ok] GetAuthCode ->", r)
redacted = safe_xml_for_log(
'<AuthCode value="secret" Code="secret" Return="secret"/>')
assert "secret" not in redacted and redacted.count("[REDACTED]") == 3, redacted
status = safe_xml_for_log('<ErrorSuccess Code="0" Description=""/>')
assert 'Code="0"' in status, status
print("[ok] GetAuthCode response shape and log redaction")
print("[ok] selftest passed")
+18 -3
View File
@@ -32,11 +32,26 @@ c() { printf ' %s\n' "$*"; }
up() { ss -tlnp 2>/dev/null | grep -q ":$1 "; }
ensure_cert() {
[ -s "$CERT" ] && [ -s "$KEY" ] && return 0
echo "[*] generating self-signed TLS cert (redirector MITM; ProtoSSL verify is patched)"
# The cert MUST carry the address the client dials in its SAN, or the roster
# HTTPS handshake is rejected with fatal certificate_unknown and the FUT hub
# fails to load (docs/FIFA17_FUT_SQUAD_UPDATE_TLS.md): the client dials the
# roster/redirector by IP and that path validates the SAN against it. Default to
# this host's primary LAN IP so a client on another machine works;
# OPENFUT_ADVERTISE overrides. Reissue when absent OR when the current cert lacks
# that IP, so this self-heals rather than serving a stale DNS-only cert.
local adv ip_sans regen=0
adv="${OPENFUT_ADVERTISE:-$(ip route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}')}"
ip_sans="IP:127.0.0.1"; [ -n "$adv" ] && ip_sans="IP:$adv,IP:127.0.0.1"
if [ ! -s "$CERT" ] || [ ! -s "$KEY" ]; then
regen=1
elif [ -n "$adv" ] && ! openssl x509 -in "$CERT" -noout -ext subjectAltName 2>/dev/null | grep -qF "IP Address:$adv"; then
regen=1
fi
[ "$regen" = 0 ] && return 0
echo "[*] issuing self-signed TLS cert (SAN includes $ip_sans; redirector MITM; ProtoSSL verify is patched)"
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$KEY" -out "$CERT" -days 3650 \
-subj "/CN=winter15.gosredirector.ea.com" \
-addext "subjectAltName=DNS:winter15.gosredirector.ea.com,DNS:*.gosredirector.ea.com,DNS:*.ea.com,IP:127.0.0.1" \
-addext "subjectAltName=DNS:winter15.gosredirector.ea.com,DNS:*.gosredirector.ea.com,DNS:*.ea.com,$ip_sans" \
>/dev/null 2>&1
}
+23
View File
@@ -65,6 +65,18 @@ MODE = os.environ.get("POW_MODE", "serve")
API_ADDR = os.environ.get("POW_ADDR", "127.0.0.1:8094")
CONTENT_ADDR = os.environ.get("POW_CONTENT_ADDR", "127.0.0.1:8080")
# CardsDLL's store-description localizer accepts an empty translation catalogue;
# transport/XML success is the gate. It discovers individual <trans-unit> records
# when present, so keep a standards-shaped empty XLIFF document rather than invent
# labels for server content we do not yet expose.
STOREPACK_DESCRIPTIONS_XML = b"""<?xml version="1.0" encoding="UTF-8"?>
<xliff version="1.2">
<file source-language="en_us" datatype="plaintext" original="storepackdescriptions">
<body />
</file>
</xliff>
"""
def _split(hostport, default_port):
host, _, port = hostport.partition(":")
@@ -296,6 +308,17 @@ class _Handler(http.server.BaseHTTPRequestHandler):
log(" body: %s" % body[:65536].decode("utf-8", "replace"))
if self.kind == "content":
content_path = self.path.split("?", 1)[0]
if content_path.rstrip("/") == "/fut/packs/loc/storepackdescriptions.en_us.xml":
raw = STOREPACK_DESCRIPTIONS_XML
self.send_response(200)
self.send_header("Content-Type", "application/xml; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(raw)
log(" -> 200 storepack descriptions XML (%d bytes)" % len(raw))
return
# Art assets (.dds/.png). We have none; 404 is the honest answer and is
# what a missing-asset CDN would return. Logged so we learn what art the
# client wants before deciding to synthesise any.
+1 -1
View File
@@ -20,7 +20,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
CERT = os.path.join(HERE, "redir_cert.pem")
KEY = os.path.join(HERE, "redir_key.pem")
LOG = "/tmp/roster_server.log"
ADDR = ("127.0.0.1", 8081)
ADDR = (os.environ.get("OPENFUT_BIND", "127.0.0.1"), 8081)
# Minimal "no update available" roster body. Unknown-format -> iterate from the log.
ROSTER_XML = b'<?xml version="1.0" encoding="utf-8"?>\n<rosterupdate version="0"/>\n'
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Dump CardsDLL's 45-row route table from the ON-DISK PE. READ-ONLY, static.
The transfer-market analysis locates the table at .rdata 0x18021df80 as
{char*, char*} rows. This resolves VA->file offset properly through the PE section
table rather than assuming a single .text mapping, then prints every row so we can
see whether any route other than `tradePile` could own a trade-pile ITEM list.
"""
import struct, sys
DLL = "/mnt/games/FIFA 17/CardsDLL_Win64_retail.dll"
TABLE_VA = 0x18021DF80
MAX_ROWS = 64
pe = open(DLL, "rb").read()
e_lfanew = struct.unpack_from("<I", pe, 0x3C)[0]
assert pe[e_lfanew:e_lfanew + 4] == b"PE\0\0", "not a PE"
coff = e_lfanew + 4
nsec, opt_size = struct.unpack_from("<HH", pe, coff + 2), None
num_sections = struct.unpack_from("<H", pe, coff + 2)[0]
opt_size = struct.unpack_from("<H", pe, coff + 16)[0]
opt = coff + 20
magic = struct.unpack_from("<H", pe, opt)[0]
assert magic == 0x20B, "expected PE32+"
image_base = struct.unpack_from("<Q", pe, opt + 24)[0]
sec_off = opt + opt_size
sections = []
for i in range(num_sections):
b = sec_off + i * 40
name = pe[b:b + 8].rstrip(b"\0").decode("ascii", "replace")
vsize, vaddr, rawsize, rawptr = struct.unpack_from("<IIII", pe, b + 8)
sections.append((name, vaddr, vsize, rawptr, rawsize))
print("image_base=%#x sections=%d" % (image_base, num_sections))
for s in sections:
print(" %-8s rva=%#010x vsize=%#x rawptr=%#010x rawsize=%#x" % s)
def va2off(va):
rva = va - image_base
for name, vaddr, vsize, rawptr, rawsize in sections:
if vaddr <= rva < vaddr + max(vsize, rawsize):
off = rva - vaddr + rawptr
if off < len(pe):
return off
return None
def cstr(va, limit=96):
off = va2off(va)
if off is None:
return None
end = pe.find(b"\0", off, off + limit)
if end < 0:
return None
try:
return pe[off:end].decode("ascii")
except UnicodeDecodeError:
return None
base = va2off(TABLE_VA)
print("\nroute table VA %#x -> file offset %s" % (TABLE_VA, hex(base) if base else None))
assert base, "table VA did not resolve"
print("\n%-4s %-34s %s" % ("#", "field A", "field B"))
rows = 0
for i in range(MAX_ROWS):
a_va, b_va = struct.unpack_from("<QQ", pe, base + i * 16)
a, b = cstr(a_va), cstr(b_va)
if a is None and b is None:
print("-- table ends after %d rows --" % rows)
break
print("%-4d %-34s %s" % (i, repr(a), repr(b)))
rows += 1
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Regression tests for launcher-selected persistent FIFA 17 accounts."""
import importlib
import json
import os
import sys
import tempfile
TOOLS = os.path.dirname(os.path.abspath(__file__))
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
def main():
with tempfile.TemporaryDirectory() as state:
os.environ["FUT_ACCOUNT_PATH"] = os.path.join(state, "active_account.json")
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
import fut_account
import fut_store
import fut_accounts
import utas_server
importlib.reload(fut_account)
importlib.reload(fut_store)
importlib.reload(fut_accounts)
importlib.reload(utas_server)
a = fut_accounts.activate({
"personaId": 111001, "personaName": "TEST_A",
"level": 12, "experience": 345, "experienceMax": 1000,
"accountFunds": 50, "accountFundsCap": 100000,
})
assert a["personaId"] == 111001
assert a["level"] == 12
assert fut_store.STORE.coins() == 15000
assert fut_store.STORE.unopened_packs() == [70]
fut_store.STORE.spend(400)
fut_store.STORE.consume_unopened_pack(70)
b = fut_accounts.activate({"personaId": 222002, "personaName": "TEST_B"})
assert b["personaId"] == 222002
assert fut_store.STORE.coins() == 15000
assert fut_store.STORE.unopened_packs() == [70]
a2 = fut_accounts.activate({"personaId": 111001, "personaName": "TEST_A"})
assert a2["personaId"] == 111001
assert fut_store.STORE.coins() == 14600
assert fut_store.STORE.unopened_packs() == []
assert a2["level"] == 12
assert a2["accountFunds"] == 50
active = json.load(open(os.environ["FUT_ACCOUNT_PATH"]))
assert active["persona_id"] == 111001
assert active["persona_name"] == "TEST_A"
# A second process-like Account instance must observe an atomic active
# account file replacement rather than retaining its first loaded value.
observer = fut_account.Account(os.environ["FUT_ACCOUNT_PATH"])
assert observer.persona_id == 111001
fut_accounts.activate({"personaId": 222002, "personaName": "TEST_B"})
assert observer.persona_id == 222002
class Purchase:
command = "POST"
_body = b'{"packId":6,"useCredits":1,"usePreOrder":0,"currency":"COINS"}'
utas_server._OPENED_PACK_GRACE.clear()
status, _ = utas_server.purchased_items(Purchase())
assert status == 200
assert utas_server._OPENED_PACK_GRACE == [6]
status, catalog = utas_server.store_catalog(None)
assert status == 200
grace = [p for p in catalog["purchase"]
if p.get("id") == 6 and p.get("unopened")]
assert len(grace) == 1
assert grace[0]["state"] == "active"
assert grace[0]["displayGroup"]["value"] == "mypacks"
print("account profile isolation: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Pure unit test for the empty-My-Packs store resolver guard in autopatch.py.
Covers the fail-closed guard decision (original -> PATCH, already-patched -> NOOP,
unknown -> SKIP) and pins the guarded patch table to the exact RVA/bytes proven on
the tested FIFA 17 build (JNZ 0x14869 -> JG 0x14869 at CardsDLL RVA 0x14858).
Run: python3 test_autopatch_guard.py
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import autopatch # importable: runtime loop is guarded by `if __name__ == "__main__"`
GUARD_VA = 0x180014858
ORIG = bytes.fromhex("750f") # JNZ 0x14869
PATCH = bytes.fromhex("7f0f") # JG 0x14869
def test_table_exact():
assert autopatch.STORE_PATCHES_GUARDED == {GUARD_VA: (ORIG, PATCH)}, \
autopatch.STORE_PATCHES_GUARDED
# Byte-level pin so a bad hex literal cannot slip through.
assert ORIG == b"\x75\x0f" and PATCH == b"\x7f\x0f"
def test_decision():
assert autopatch.guarded_action(ORIG, ORIG, PATCH) == "patch" # apply
assert autopatch.guarded_action(PATCH, ORIG, PATCH) == "noop" # already patched
assert autopatch.guarded_action(b"\x00\x00", ORIG, PATCH) == "skip" # build mismatch
assert autopatch.guarded_action(b"\x90", ORIG, PATCH) == "skip" # wrong length
def test_guard_state_after():
# already patched (7f0f) -> VERIFIED (guarded_action "noop"); write args irrelevant.
assert autopatch.guard_state_after(PATCH, ORIG, PATCH, True, PATCH) == autopatch.GUARD_VERIFIED
# original (750f) + write ok + reread 7f0f -> VERIFIED (guarded_action "patch").
assert autopatch.guard_state_after(ORIG, ORIG, PATCH, True, PATCH) == autopatch.GUARD_VERIFIED
# original + write FAILS -> WRITE_FAILED.
assert autopatch.guard_state_after(ORIG, ORIG, PATCH, False, ORIG) == autopatch.GUARD_WRITE_FAILED
# original + write ok but reread != 7f0f -> VERIFY_FAILED.
assert autopatch.guard_state_after(ORIG, ORIG, PATCH, True, ORIG) == autopatch.GUARD_VERIFY_FAILED
assert autopatch.guard_state_after(ORIG, ORIG, PATCH, True, b"") == autopatch.GUARD_VERIFY_FAILED
# unknown bytes -> UNSUPPORTED_BUILD (guarded_action "skip"); write args irrelevant.
assert autopatch.guard_state_after(b"\x00\x00", ORIG, PATCH, True, PATCH) == autopatch.GUARD_UNSUPPORTED_BUILD
def test_capability_constants():
assert autopatch.EMPTY_MYPACKS_RESOLVER_VERSION == 1
assert autopatch.EMPTY_MYPACKS_RESOLVER_CAPABILITY == "fifa17.empty_mypacks_resolver"
# State constant values are the exact tokens carried in the emitted status line.
assert autopatch.GUARD_VERIFIED == "VERIFIED"
assert autopatch.GUARD_UNSUPPORTED_BUILD == "UNSUPPORTED_BUILD"
assert autopatch.GUARD_WRITE_FAILED == "WRITE_FAILED"
assert autopatch.GUARD_VERIFY_FAILED == "VERIFY_FAILED"
assert autopatch.GUARD_NOT_ATTEMPTED == "NOT_ATTEMPTED"
if __name__ == "__main__":
test_table_exact()
test_decision()
test_guard_state_after()
test_capability_constants()
print("OK: autopatch guard table + fail-closed decision + guard-state function + capability constants")
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Regression: autopatch logging is per-launcher/user writable.
The watcher is run with a definitely-absent launcher PID, so it writes its
startup/ownership-exit diagnostics and terminates without touching FIFA.
"""
import os
import pathlib
import subprocess
import sys
import tempfile
def main():
script = pathlib.Path(__file__).with_name("autopatch.py")
with tempfile.TemporaryDirectory(prefix="openfut-autopatch-test-") as root:
log_path = pathlib.Path(root) / "autopatch.log"
env = os.environ.copy()
env["OPENFUT_AUTOPATCH_LOG"] = str(log_path)
result = subprocess.run(
[sys.executable, str(script), "--launcher-pid", "999999999"],
env=env,
text=True,
capture_output=True,
timeout=5,
)
assert result.returncode == 0, result.stderr or result.stdout
assert log_path.is_file(), "OPENFUT_AUTOPATCH_LOG was ignored"
text = log_path.read_text()
assert "watching for FIFA17.exe" in text
assert "launcher pid 999999999 exited" in text
print("autopatch writable-log override: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+301
View File
@@ -0,0 +1,301 @@
#!/usr/bin/env python3
"""Tests for the FIFA 17 verified-patched-client capability negotiation.
The additive empty-My-Packs switch on top of the P2 65534 sentinel: the sentinel is
suppressed for ONE FIFA session only when the launcher has registered a verified
resolver capability (v1) that binds to THAT process's UTAS session (keyed by the
per-login-unique X-UT-SID; source IP + persona are auxiliary). Every failure /
unknown / late / cross-process / cross-session case is fail-closed to the sentinel.
The initial prototype keyed by source IP alone; this suite proves the hardened
per-session binding, including two sessions that SHARE a source IP.
Matrix (docs/plans/FIFA17_PATCHED_CLIENT_CAPABILITY.md):
A no-capability, zero packs -> sentinel
B verified v1, zero packs -> clean (no 65534)
C real unopened pack + no capability -> genuine pack, no sentinel
D real unopened pack + capability -> genuine pack, no sentinel
E unsupported version / capability -> endpoint 400 AND mode sentinel
F late capability after sentinel freeze -> stays sentinel
G capability disappears after clean freeze -> stays clean (immutable)
H two IPs (A verified, B none) -> A clean, B sentinel (no global leak)
I new session after reset -> fresh unpatched -> sentinel
J autopatch mismatch => never registers -> sentinel
K SAME IP, two sessions (A patched, B not) -> A clean, B sentinel
L SAME IP+persona relaunch (old ok, new not) -> new session sentinel
M SAME IP, failed-patch second session -> first clean, second sentinel
N late registration when sessions are frozen -> does not modify active sessions
O session cleanup / TTL expiry -> capability gone, sentinel
P duplicate registration for a session -> idempotent; no post-freeze change
Q register-before-login (pending consumed) -> clean
R topology freeze immutable per SID -> no flip either way; new SID fresh
Standalone unit test in the project style: `python3 test_capability_negotiation.py`.
"""
import importlib
import json
import os
import sys
import tempfile
TOOLS = os.path.dirname(os.path.abspath(__file__))
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
SENTINEL_ID = 65534
REAL_PACK_ID = 1
PERSONA = 111001
class _H:
"""Minimal request-handler stand-in: peer IP, optional X-UT-SID, optional body."""
def __init__(self, ip, body=None, sid=None):
self.client_address = (ip, 54321)
self.headers = {"X-UT-SID": sid} if sid is not None else {}
self._body = json.dumps(body).encode("utf-8") if body is not None else b""
def _ids(catalog):
return [p["id"] for p in catalog["purchase"]]
def main():
with tempfile.TemporaryDirectory() as state:
os.environ["FUT_ACCOUNT_PATH"] = os.path.join(state, "active_account.json")
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
import fut_account
import fut_store
import fut_accounts
import utas_server
importlib.reload(fut_account)
importlib.reload(fut_store)
importlib.reload(fut_accounts)
importlib.reload(utas_server)
us = utas_server
CLEAN, SENT = us.FIFA17_MODE_CLEAN, us.FIFA17_MODE_SENTINEL
_orig_visible = us.visible_unopened_packs
def set_zero_packs():
us.visible_unopened_packs = lambda: []
def set_real_pack():
us.visible_unopened_packs = lambda: [REAL_PACK_ID]
def reset_state():
us._FIFA17_SESSIONS.clear()
us._FIFA17_PENDING.clear()
def auth(sid, ip, persona=PERSONA):
"""Simulate /ut/auth opening a per-login session with a chosen sid."""
us.fifa17_open_session(sid, ip, persona)
def register(ip, version, persona=PERSONA, pid=4242):
return us.fifa17_capability_route(_H(ip, {
"capability": "empty_mypacks_resolver", "version": version,
"personaId": persona, "fifaPid": pid,
}))
def store(sid, ip):
status, cat = us.store_catalog(_H(ip, sid=sid))
assert status == 200, status
return _ids(cat)
def mode_of(sid):
return us._FIFA17_SESSIONS[sid]["mode"]
try:
# ---- A. no capability, zero packs -> sentinel ----------------------
reset_state(); set_zero_packs()
auth("sidA", "10.0.0.1")
assert SENTINEL_ID in store("sidA", "10.0.0.1")
assert mode_of("sidA") == SENT
print("A no-capability zero-packs -> sentinel: OK")
# ---- B. verified v1, zero packs -> clean ---------------------------
reset_state(); set_zero_packs()
auth("sidB", "10.0.0.2")
assert register("10.0.0.2", 1)[0] == 200
ids = store("sidB", "10.0.0.2")
assert SENTINEL_ID not in ids, ids
assert mode_of("sidB") == CLEAN
print("B verified-v1 zero-packs -> clean: OK")
# ---- C. real pack + no capability -> genuine, no sentinel ----------
reset_state(); set_real_pack()
auth("sidC", "10.0.0.3")
ids = store("sidC", "10.0.0.3")
assert REAL_PACK_ID in ids and SENTINEL_ID not in ids, ids
print("C real-pack no-capability -> genuine, no sentinel: OK")
# ---- D. real pack + capability -> genuine, no sentinel -------------
reset_state(); set_real_pack()
auth("sidD", "10.0.0.4"); register("10.0.0.4", 1)
ids = store("sidD", "10.0.0.4")
assert REAL_PACK_ID in ids and SENTINEL_ID not in ids, ids
print("D real-pack capability -> genuine, no sentinel: OK")
# ---- E. unsupported version / capability -> 400 + sentinel ---------
reset_state(); set_zero_packs()
auth("sidE", "10.0.0.5")
assert register("10.0.0.5", 2)[0] == 400
assert register("10.0.0.5", 99)[0] == 400
assert us.fifa17_capability_route(
_H("10.0.0.5", {"capability": "bogus", "version": 1}))[0] == 400
assert SENTINEL_ID in store("sidE", "10.0.0.5")
assert mode_of("sidE") == SENT
print("E unsupported version/capability -> 400 + sentinel: OK")
# ---- F. late capability after sentinel freeze -> sentinel ----------
reset_state(); set_zero_packs()
auth("sidF", "10.0.0.6")
assert SENTINEL_ID in store("sidF", "10.0.0.6") # freezes sentinel
assert register("10.0.0.6", 1)[0] == 200 # session frozen -> ignored-late
assert SENTINEL_ID in store("sidF", "10.0.0.6")
assert mode_of("sidF") == SENT
print("F late capability after sentinel freeze -> sentinel: OK")
# ---- G. capability disappears after clean freeze -> clean ----------
reset_state(); set_zero_packs()
auth("sidG", "10.0.0.7"); register("10.0.0.7", 1)
assert SENTINEL_ID not in store("sidG", "10.0.0.7") # freezes clean
us._FIFA17_SESSIONS["sidG"]["resolver"] = None # capability vanishes
assert SENTINEL_ID not in store("sidG", "10.0.0.7")
assert mode_of("sidG") == CLEAN
print("G capability disappears after clean freeze -> clean: OK")
# ---- H. two IPs (A verified, B none) -> no global leak -------------
reset_state(); set_zero_packs()
auth("sidH1", "10.0.1.1"); register("10.0.1.1", 1)
auth("sidH2", "10.0.1.2")
assert SENTINEL_ID not in store("sidH1", "10.0.1.1")
assert SENTINEL_ID in store("sidH2", "10.0.1.2")
print("H two IPs (A clean, B sentinel) -> no global leak: OK")
# ---- I. new session after reset -> fresh unpatched -> sentinel -----
reset_state(); set_zero_packs()
auth("sidI1", "10.0.1.3"); register("10.0.1.3", 1)
assert SENTINEL_ID not in store("sidI1", "10.0.1.3") # A clean
us.fifa17_clear_pending("10.0.1.3") # relaunch boundary
auth("sidI2", "10.0.1.3") # new SID, autopatch failed
assert SENTINEL_ID in store("sidI2", "10.0.1.3")
print("I new session after reset -> sentinel (no cross-process leak): OK")
# ---- J. autopatch mismatch => never registers -> sentinel ----------
reset_state(); set_zero_packs()
auth("sidJ", "10.0.1.4")
assert SENTINEL_ID in store("sidJ", "10.0.1.4")
print("J autopatch mismatch (never registers) -> sentinel: OK")
# ---- K. SAME IP, two sessions: patched A clean, unpatched B sent ---
reset_state(); set_zero_packs()
IP = "10.0.2.1"
auth("sidK_A", IP)
assert register(IP, 1)[0] == 200 # A sole candidate -> bound
auth("sidK_B", IP) # B joins, never registers
assert SENTINEL_ID not in store("sidK_A", IP)
assert SENTINEL_ID in store("sidK_B", IP)
print("K same-IP two sessions -> A clean, B sentinel: OK")
# ---- L. SAME IP+persona relaunch: old ok, new not -> new sentinel --
reset_state(); set_zero_packs()
IP = "10.0.2.2"
auth("sidL_old", IP, PERSONA); register(IP, 1, PERSONA)
assert SENTINEL_ID not in store("sidL_old", IP)
us.fifa17_clear_pending(IP)
auth("sidL_new", IP, PERSONA) # same persona, unverified
assert SENTINEL_ID in store("sidL_new", IP)
print("L same-IP+persona relaunch -> new session sentinel: OK")
# ---- M. SAME IP, failed-patch second session -----------------------
reset_state(); set_zero_packs()
IP = "10.0.2.3"
auth("sidM1", IP); register(IP, 1)
assert SENTINEL_ID not in store("sidM1", IP)
auth("sidM2", IP) # autopatch failed
assert SENTINEL_ID in store("sidM2", IP)
print("M same-IP failed-patch second session -> sentinel: OK")
# ---- N. late reg when sessions frozen -> no active session change --
reset_state(); set_zero_packs()
IP = "10.0.2.4"
auth("sidN1", IP); register(IP, 1)
assert SENTINEL_ID not in store("sidN1", IP) # N1 frozen clean
auth("sidN2", IP)
assert SENTINEL_ID in store("sidN2", IP) # N2 frozen sentinel
assert register(IP, 1)[0] == 200 # late: both frozen -> ignored
assert SENTINEL_ID not in store("sidN1", IP) # unchanged
assert SENTINEL_ID in store("sidN2", IP) # unchanged
print("N late registration does not modify active sessions: OK")
# ---- O. session cleanup / TTL expiry -> capability gone ------------
reset_state(); set_zero_packs()
IP = "10.0.2.5"
auth("sidO", IP); register(IP, 1)
assert SENTINEL_ID not in store("sidO", IP) # clean while live
us._FIFA17_SESSIONS["sidO"]["last_seen"] = (
us._fifa17_now() - us.FIFA17_SESSION_TTL - 10.0)
store("sidUNKNOWN", IP) # any op triggers reap
assert "sidO" not in us._FIFA17_SESSIONS, "expired session not reaped"
assert SENTINEL_ID in store("sidO", IP) # gone -> sentinel
print("O session cleanup / TTL expiry -> sentinel: OK")
# ---- P. duplicate registration -> idempotent, no post-freeze change
reset_state(); set_zero_packs()
IP = "10.0.2.6"
auth("sidP", IP)
assert register(IP, 1)[0] == 200 # bound
assert register(IP, 1)[0] == 200 # duplicate -> ignored-late
assert SENTINEL_ID not in store("sidP", IP) # still clean
assert register(IP, 1)[0] == 200 # after freeze
assert SENTINEL_ID not in store("sidP", IP) # unchanged
assert mode_of("sidP") == CLEAN
print("P duplicate registration -> idempotent: OK")
# ---- Q. register-before-login: pending consumed at auth -> clean ---
reset_state(); set_zero_packs()
IP = "10.0.2.7"
assert register(IP, 1)[0] == 200 # no session yet -> pending
assert (IP, PERSONA) in us._FIFA17_PENDING
auth("sidQ", IP, PERSONA) # consumes pending
assert (IP, PERSONA) not in us._FIFA17_PENDING # single-use
assert SENTINEL_ID not in store("sidQ", IP)
assert mode_of("sidQ") == CLEAN
print("Q register-before-login pending consumed -> clean: OK")
# ---- R. topology freeze immutable per SID; new SID decides fresh ----
# F3 invariant: once a SID's store topology is decided it NEVER flips,
# in either direction, and a different SID may decide differently.
reset_state(); set_zero_packs()
IP = "10.0.2.8"
# frozen Sentinel never becomes Clean, even if a capability appears later
auth("sidR_s", IP)
assert SENTINEL_ID in store("sidR_s", IP) # freeze Sentinel
register(IP, 1)
us._FIFA17_SESSIONS["sidR_s"]["resolver"] = 1 # force-present capability
assert SENTINEL_ID in store("sidR_s", IP) # STILL Sentinel
assert mode_of("sidR_s") == SENT
# frozen Clean never becomes Sentinel, even if the capability is wiped
auth("sidR_c", IP); register(IP, 1)
assert SENTINEL_ID not in store("sidR_c", IP) # freeze Clean
us._FIFA17_SESSIONS["sidR_c"]["resolver"] = None # capability vanishes
assert SENTINEL_ID not in store("sidR_c", IP) # STILL Clean
assert mode_of("sidR_c") == CLEAN
# a fresh SID (same IP) decides independently
auth("sidR_new", IP)
assert SENTINEL_ID in store("sidR_new", IP)
print("R topology freeze immutable per SID; new SID fresh: OK")
finally:
us.visible_unopened_packs = _orig_visible
print("capability negotiation matrix A-R: OK")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Regression tests for the empty-My-Packs FIFA 17 compatibility workaround (bug 6c).
Pins the behavior store_catalog() now depends on:
- unopenedPackIds == [] -> exactly one synthetic active `mypacks` placeholder id 65534
- unopenedPackIds == [70] -> no synthetic placeholder; the genuine owned pack is shown
- synthetic id 65534 stays economy-safe (non-resolvable, non-openable, non-granting)
- normal store packs (1/5/6/7) are untouched by the empty-state behavior
See docs/evidence/STORE_TILE_6C.md and FIFA17_EMPTY_MYPACKS_CLIENT_CONTRACT.md.
Standalone unit test in the project style: `python3 test_empty_mypacks.py`.
"""
import importlib
import os
import sys
import tempfile
TOOLS = os.path.dirname(os.path.abspath(__file__))
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
SENTINEL_ID = 65534
def _set_unopened(fut_store, ids):
"""Deterministically set the active profile's owned unopened packs."""
p = fut_store.STORE.load()
p["unopenedPackIds"] = list(ids)
fut_store.STORE._save()
def _mypacks(catalog):
return [p for p in catalog["purchase"]
if (p.get("displayGroup") or {}).get("value") == "mypacks"]
def _fake_request(command, body):
class _H:
pass
h = _H()
h.command = command
h._body = body
return h
def main():
with tempfile.TemporaryDirectory() as state:
os.environ["FUT_ACCOUNT_PATH"] = os.path.join(state, "active_account.json")
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
import fut_account
import fut_store
import fut_accounts
import utas_server
importlib.reload(fut_account)
importlib.reload(fut_store)
importlib.reload(fut_accounts)
importlib.reload(utas_server)
fut_accounts.activate({"personaId": 111001, "personaName": "TEST_A"})
catalog_ids = [p["id"] for p in fut_store.PACK_CATALOG]
# ---- A. Empty unopened packs -> one active synthetic 65534 placeholder ----
_set_unopened(fut_store, [])
utas_server._OPENED_PACK_GRACE.clear()
status, cat = utas_server.store_catalog(None)
assert status == 200
myp = _mypacks(cat)
assert len(myp) == 1, "expected exactly one mypacks entry, got %r" % myp
s = myp[0]
assert s["id"] == SENTINEL_ID, s
assert s["state"] == "active", s # the P2 fix: active, not inactive
assert (s.get("displayGroup") or {}).get("value") == "mypacks", s
assert SENTINEL_ID not in catalog_ids, "65534 must not be in PACK_CATALOG"
assert fut_store.pack_by_id(SENTINEL_ID) is None
print("A empty-state active placeholder: PASS")
# ---- D (empty half). Normal packs untouched in empty state ----
norm = {p["id"]: p for p in cat["purchase"] if p["id"] in (1, 5, 6, 7)}
assert set(norm) == {1, 5, 6, 7}, sorted(norm)
assert all(norm[i]["state"] == "active" for i in norm), norm
assert norm[1]["packType"] == "BRONZE" and norm[1]["description"] == "Bronze Pack"
# ---- B. Non-empty unopened packs -> NO synthetic; genuine owned pack shown ----
_set_unopened(fut_store, [70])
utas_server._OPENED_PACK_GRACE.clear()
status, cat = utas_server.store_catalog(None)
assert status == 200
ids = [p["id"] for p in cat["purchase"]]
assert SENTINEL_ID not in ids, "synthetic placeholder must be suppressed when a pack exists"
myp = _mypacks(cat)
assert len(myp) == 1 and myp[0]["id"] == 70, myp
assert myp[0]["state"] == "active" and myp[0]["unopened"] is True, myp[0]
# normal packs still intact alongside the owned pack
assert {1, 5, 6, 7}.issubset(set(ids)), sorted(ids)
print("B non-empty-state genuine pack: PASS")
# ---- C. Economy safety of the synthetic placeholder ----
_set_unopened(fut_store, [])
utas_server._OPENED_PACK_GRACE.clear()
coins0 = fut_store.STORE.coins()
items0 = len(fut_store.STORE.items())
next0 = fut_store.STORE.load()["nextItemId"]
assert fut_store.pack_by_id(SENTINEL_ID) is None
# store_buy: a confirmed-buy transaction for 65534 must be a no-op {}
status, body = utas_server.store_buy(
_fake_request("PUT", b'{"packId":65534,"state":"TRANSACTIONCREATED"}'))
assert status == 200 and body == {}, (status, body)
# purchased_items: POST buy for 65534 must not open/grant anything
status, body = utas_server.purchased_items(
_fake_request("POST", b'{"packId":65534,"useCredits":1,"usePreOrder":0,"currency":"COINS"}'))
assert status == 200, (status, body)
assert "createPackResponse" not in body, body
# 65534 cannot enter the owned-pack pile (not a catalog pack)
assert fut_store.STORE.grant_unopened_pack(SENTINEL_ID) is False
assert SENTINEL_ID not in fut_store.STORE.unopened_packs()
# nothing mutated
assert fut_store.STORE.coins() == coins0, (fut_store.STORE.coins(), coins0)
assert len(fut_store.STORE.items()) == items0
assert fut_store.STORE.load()["nextItemId"] == next0
assert not any(i.get("id") == SENTINEL_ID or i.get("resourceId") == SENTINEL_ID
for i in fut_store.STORE.items())
print("C economy safety (65534 non-openable / non-granting): PASS")
print("empty My Packs compatibility: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+13 -3
View File
@@ -104,11 +104,21 @@ def test_store_catalog():
check("catalog.purchase is array", is_arr(d.get("purchase")), repr(type(d.get("purchase"))))
for p in d.get("purchase", []):
check("pack has assetId (real identity)", "assetId" in p, repr(p.get("assetId")))
check("pack.currencies is array (coin price)", is_arr(p.get("currencies")))
check("pack.packContentInfo is object", is_obj(p.get("packContentInfo")))
check("pack.extPrice is object", is_obj(p.get("extPrice")))
# The inactive zero-item sentinel keeps FIFA's hardcoded `mypacks`
# navigation destination resolvable when no owned packs remain. It is
# intentionally neither owned nor purchasable and therefore has no
# pricing. Validate prices only for active store packs.
if p.get("state") == "active" and not p.get("unopened"):
check("store pack currencies is array (coin price)",
is_arr(p.get("currencies")))
check("store pack extPrice is object", is_obj(p.get("extPrice")))
ep = p.get("extPrice", {})
check("extPrice.finalPrice is object", is_obj(ep.get("finalPrice")))
check("store extPrice.finalPrice is object",
is_obj(ep.get("finalPrice")))
elif p.get("unopened"):
check("owned pack omits purchase currencies", "currencies" not in p)
check("owned pack omits external purchase price", "extPrice" not in p)
def test_market_bodies():
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Regression for the FIFA 17 FUT hub offline-Seasons summary.
CardsDLL's hub parser at 0x180139610 recognizes offlineSeason (atom 0x1ec)
and passes its object to 0x18013c3a0. That nested parser recognizes the
string-valued divisionId, gamesPlayed, points, totalGames, and
progressDataVersion fields. Without offlineSeason, the Single Player Season
UI rejects the otherwise-successful GetHubData response before /season is sent.
"""
import os
import pathlib
import sys
import tempfile
TOOLS = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(TOOLS))
def main():
with tempfile.TemporaryDirectory(prefix="openfut-hub-season-test-") as state:
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
os.environ["FUT_MODES"] = "1"
import utas_server
body = utas_server.hub_data()
assert isinstance(body, dict), "hub response root must be an object"
summary = body.get("offlineSeason")
assert isinstance(summary, dict), "hub.offlineSeason must be an object"
expected = {"divisionId", "gamesPlayed", "points", "totalGames",
"progressDataVersion"}
assert set(summary) == expected, repr(summary)
for key in expected:
assert isinstance(summary[key], str), "%s must be a string: %r" % (key, summary[key])
assert summary["divisionId"] == "10", repr(summary)
assert summary["gamesPlayed"] == "0", repr(summary)
assert summary["points"] == "0", repr(summary)
if __name__ == "__main__":
main()
print("PASS: FUT hub includes the recovered offline-Seasons summary")
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Isolated account-scoped regression for the FUT match HTTP lifecycle.
Drives CREATE -> READY -> PLAY -> END through match_route using a temporary
profile root. No live profile or server is touched.
"""
import importlib
import json
import os
import sys
import tempfile
TOOLS = os.path.dirname(os.path.abspath(__file__))
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
class Request:
def __init__(self, path, body, command="POST"):
self.path = path
self.command = command
self._body = json.dumps(body).encode("utf-8")
def main():
with tempfile.TemporaryDirectory() as state:
os.environ["FUT_ACCOUNT_PATH"] = os.path.join(state, "active_account.json")
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
import fut_account
import fut_store
import fut_accounts
import utas_server
importlib.reload(fut_account)
importlib.reload(fut_store)
importlib.reload(fut_accounts)
importlib.reload(utas_server)
persona_id = 909001
fut_accounts.activate({"personaId": persona_id, "personaName": "MATCH_TEST"})
initial = fut_store.STORE.load()
initial_coins = initial["coins"]
initial_next_id = initial["nextItemId"]
status, created = utas_server.match_route(
Request("/ut/game/fifa17/match", {}))
assert status == 200
match_id = created["id"]
assert created["reportIdEnabled"] is False
assert fut_store.STORE.load()["nextItemId"] == initial_next_id + 1
status, ready = utas_server.match_route(
Request("/ut/game/fifa17/match/ready", {"matchId": match_id}))
assert status == 200
assert ready == {"matchId": match_id, "opponentPersonaId": 0}
next_id_before_play = fut_store.STORE.load()["nextItemId"]
status, played = utas_server.match_route(
Request("/ut/game/fifa17/match", {"matchId": match_id}))
assert status == 200
assert played == {}
assert fut_store.STORE.load()["nextItemId"] == next_id_before_play
status, ended = utas_server.match_route(Request(
"/ut/game/fifa17/match/end",
{"matchId": match_id, "endReason": "WIN",
"myMatchStats": {"goals": 2},
"opponentMatchStats": {"goals": 1}},
))
assert status == 200
expected_reward = (utas_server.MATCH_COINS["won"]
+ utas_server.MATCH_PARTICIPATION)
assert ended["allCoins"] == initial_coins + expected_reward
profile_path = os.path.join(state, "accounts", str(persona_id),
"fifa17_profile.json")
persisted = json.load(open(profile_path, encoding="utf-8"))
assert persisted["coins"] == initial_coins + expected_reward
assert persisted["record"] == {"won": 1, "draw": 0, "loss": 0}
assert persisted["matchesPlayed"] == 1
print("match lifecycle persistence: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+31 -1
View File
@@ -11,6 +11,8 @@ Guards the two things that would silently break the loop:
* `destroy_match_body()` drifting from FutDestroyMatchServerResponse
(deser 0x180121b60): a non-scalar there is the freeze class at 0x1801c7f1a,
and a renamed key is silently SKIP'd, i.e. the reward vanishes with no error.
* the shared base `/match` path distinguishing CREATEMATCH from PLAYGAME by
the body-level matchId that CardsDLL serializes for subsequent operations
Run: python3 tools/test_match_rewards.py (exit 0 = pass)
"""
@@ -152,9 +154,37 @@ def test_payout_table():
check("draw pays >= loss", U.MATCH_COINS["draw"] >= U.MATCH_COINS["loss"])
def test_match_call_classification():
"""CREATEMATCH and PLAYGAME share a path; only the latter has a matchId."""
cases = (
("/ut/game/fifa17/match", "POST", {}, "create"),
("/ut/game/fifa17/match", "POST", {"matchId": 1234}, "play"),
("/ut/game/fifa17/match/ready", "POST", {"matchId": 1234}, "ready"),
("/ut/game/fifa17/match/end", "POST", {"matchId": 1234}, "end"),
("/ut/game/fifa17/match/reset", "PUT", {"matchId": 1234}, "reset"),
("/ut/game/fifa17/match/keepalive", "POST", {"matchId": 1234}, "keepalive"),
)
for path, method, body, want in cases:
got = U._match_call(path, method, body)
check("%s %s -> %s" % (method, path, want), got == want, "got %s" % got)
def test_match_ready_body():
"""FutMatchReadyServerResponse parses these two scalar identifiers."""
body = U.match_ready_body(1234, 33068179)
check("ready echoes matchId", body.get("matchId") == 1234, repr(body))
check("ready has opponentPersonaId", body.get("opponentPersonaId") == 33068179,
repr(body))
check("ready IDs are scalar ints",
all(isinstance(v, int) and not isinstance(v, bool) for v in body.values()),
repr(body))
check("ready omits unproven nested items", "items" not in body, repr(body))
def main():
for t in (test_result_detection, test_reward_body,
test_end_reason_is_authoritative, test_payout_table):
test_end_reason_is_authoritative, test_payout_table,
test_match_call_classification, test_match_ready_body):
try:
t()
except Exception as e:
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Regression tests for FIFA 17's account-scoped phishing/security gate."""
import importlib
import json
import os
import sys
import tempfile
TOOLS = os.path.dirname(os.path.abspath(__file__))
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
DEVICE_ID = "1" * 32
TRANSFORMED_ANSWER = "a" * 32 # sanitized replay value, not a real answer
class Request:
def __init__(self, method, path, sid=None):
self.command = method
self.path = path
self.headers = {"X-UT-SID": sid} if sid is not None else {}
self._body = b""
def request(utas_server, method, suffix, sid=None):
sid = utas_server.SID if sid is None else sid
h = Request(method, "/ut/game/fifa17/phishing/" + suffix, sid)
return utas_server.security_question_route(h)
def profile(state, persona_id):
path = os.path.join(state, "accounts", str(persona_id), "fifa17_profile.json")
with open(path) as f:
return json.load(f)
def main():
with tempfile.TemporaryDirectory() as state:
os.environ["FUT_ACCOUNT_PATH"] = os.path.join(state, "active_account.json")
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
import fut_account
import fut_store
import fut_accounts
import utas_server
importlib.reload(fut_account)
importlib.reload(fut_store)
importlib.reload(fut_accounts)
importlib.reload(utas_server)
# New/missing state: launcher account selection initializes one account only.
fut_accounts.activate({"personaId": 771001, "personaName": "SEC_A"})
p = profile(state, 771001)
assert p["securityQuestion"] == {"version": 1, "verified": True}
# Actual trusted-device response fields parsed by CardsDLL 0x18012a170.
code, body = request(
utas_server, "GET", "trusteddevice?deviceId=" + DEVICE_ID)
assert code == 200
assert body == {
"changed": False,
"exists": True,
"locked": False,
"trusted": True,
}
# Existing initialized state survives a fresh Store instance/process view.
reopened = fut_store.Store(fut_store.profile_path_for(771001))
assert reopened.profile()["securityQuestion"] == {
"version": 1, "verified": True}
# FIFA's observed repeat-session request: POST, empty body, opaque 32-hex
# deviceId and transformed answer in the query string. The answer is accepted
# for OpenFUT compatibility but never persisted.
code, body = request(
utas_server,
"POST",
"validate?deviceId=%s&answer=%s" % (DEVICE_ID, TRANSFORMED_ANSWER),
)
assert (code, body) == (200, {})
saved = profile(state, 771001)
assert TRANSFORMED_ANSWER not in json.dumps(saved)
# Question lookup uses the three fields parsed by CardsDLL 0x180129850.
code, body = request(
utas_server, "GET", "question?deviceId=" + DEVICE_ID)
assert code == 200
assert set(body) == {"question", "attempts", "recoverAttempts"}
assert all(isinstance(body[k], int) for k in body)
# Malformed values/methods and missing sessions fail explicitly.
code, _ = request(utas_server, "POST", "validate?deviceId=bad&answer=bad")
assert code == 400
code, _ = request(
utas_server, "DELETE", "trusteddevice?deviceId=" + DEVICE_ID)
assert code == 405
h = Request(
"GET", "/ut/game/fifa17/phishing/trusteddevice?deviceId=" + DEVICE_ID)
code, _ = utas_server.security_question_route(h)
assert code == 400
# Ordinary request logging must redact answer query values.
raw_path = "/ut/game/fifa17/phishing/validate?deviceId=%s&answer=%s" % (
DEVICE_ID, TRANSFORMED_ANSWER)
safe_path = utas_server.safe_request_path(raw_path)
assert TRANSFORMED_ANSWER not in safe_path
assert "answer=%5BREDACTED%5D" in safe_path
# Multiple profiles receive independent persisted state; selecting B must not
# alter A's initialized record.
fut_accounts.activate({"personaId": 771002, "personaName": "SEC_B"})
assert profile(state, 771002)["securityQuestion"] == {
"version": 1, "verified": True}
assert profile(state, 771001)["securityQuestion"] == {
"version": 1, "verified": True}
# Legacy profile with the field removed is repaired once and persisted.
b_path = os.path.join(state, "accounts", "771002", "fifa17_profile.json")
b = profile(state, 771002)
b.pop("securityQuestion")
with open(b_path, "w") as f:
json.dump(b, f)
fut_store.STORE._p = None
code, body = request(
utas_server, "GET", "trusteddevice?deviceId=" + DEVICE_ID)
assert code == 200 and body["exists"] and body["trusted"]
assert profile(state, 771002)["securityQuestion"]["verified"] is True
print("security-question compatibility: PASS")
if __name__ == "__main__":
main()
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Regression for the FIFA 17 tournament-list response wrapper.
CardsDLL's endpoint response parser at 0x18016b220 accepts an OBJECT root,
recognizes only tournament (atom 0x328), then opens its ARRAY and invokes the
element parser at 0x180169ef0. A bare array therefore parses as no tournament
list at all.
"""
import os
import pathlib
import sys
import tempfile
TOOLS = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(TOOLS))
def main():
with tempfile.TemporaryDirectory(prefix="openfut-tournament-test-") as state:
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ.pop("FUT_PROFILE", None)
import utas_server
body = utas_server.tournament_list()
assert isinstance(body, dict), "tournament response root must be an object"
body_dict = dict(body)
assert set(body_dict) == {"tournament"}, repr(body_dict)
tournaments = body_dict["tournament"]
assert isinstance(tournaments, list), "tournament must be an array"
assert tournaments, "the offline tournament catalog must not be empty"
assert all(isinstance(entry, dict) for entry in tournaments)
if __name__ == "__main__":
main()
print("PASS: tournament response uses the recovered object/array wrapper")
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Regression: ordinary UTAS diagnostics never expose session credentials."""
import importlib
import os
import sys
import tempfile
TOOLS = os.path.dirname(os.path.abspath(__file__))
if TOOLS not in sys.path:
sys.path.insert(0, TOOLS)
CANARY = "OPENFUT_UTAS_CANARY_SECRET"
def main():
with tempfile.TemporaryDirectory() as state:
os.environ["FUT_ACCOUNT_PATH"] = os.path.join(state, "active_account.json")
os.environ["FUT_PROFILE_ROOT"] = os.path.join(state, "accounts")
os.environ["FUT_LOG"] = os.path.join(state, "utas.log")
os.environ.pop("FUT_PROFILE", None)
import utas_server
importlib.reload(utas_server)
for name in ("X-UT-SID", "Authorization", "Cookie", "Set-Cookie"):
rendered = utas_server.safe_header_for_log(name, CANARY)
assert rendered == "[REDACTED]", (name, rendered)
assert CANARY not in rendered
assert utas_server.safe_header_for_log("Content-Type", "application/json") == "application/json"
assert utas_server.safe_header_for_log("X-Request-Id", "status-0") == "status-0"
print("UTAS header redaction: PASS")
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Read the FIFA 17 TRADING gate byte out of the live client. READ-ONLY.
Extends tools/gate_byte_probe.py with vtable slot +0x270 (IS_TRADING_ENABLED,
displacement 0x1fd2e) plus the two pile-size dwords, which the transfer-market
analysis names as the market screen's CardsDLL-supplied inputs.
Opens /proc/<pid>/mem O_RDONLY and preads. Nothing here can write.
"""
import os, struct
pid = None
for d in os.listdir('/proc'):
if d.isdigit():
try:
if open('/proc/%s/comm' % d).read().strip() == 'FIFA17.exe':
pid = int(d)
break
except Exception:
pass
assert pid, "FIFA17.exe not running"
base = None
for ln in open('/proc/%d/maps' % pid):
if 'CardsDLL' in ln:
base = int(ln.split('-')[0], 16)
assert base, "CardsDLL not mapped (client has not reached Ultimate Team)"
slide = base - 0x180000000
fd = os.open('/proc/%d/mem' % pid, os.O_RDONLY)
def rd(va, n):
return os.pread(fd, n, va)
# Control: the FNV atom-hash prologue must match the on-disk PE before any other
# address is trusted.
pe = open('/mnt/games/FIFA 17/CardsDLL_Win64_retail.dll', 'rb').read()
def f(va):
return va - 0x180000000 - 0x1000 + 0x400
ok = pe[f(0x180180d00):f(0x180180d00) + 32] == rd(0x180180d00 + slide, 32)
print("pid=%d slide=%#x FNV control=%s" % (pid, slide, "MATCH" if ok else "MISMATCH"))
assert ok, "slide not proven; refusing to read further"
obj = struct.unpack('<Q', rd(0x1802e6398 + slide, 8))[0]
vt = struct.unpack('<Q', rd(obj, 8))[0]
print("model=%#x vtable(static)=%#x" % (obj, vt - slide))
SLOTS = [
(0x270, 'IS_TRADING_ENABLED '),
(0x2b0, 'IS_FRIENDLY_SEASON '),
(0x2c8, 'IS_DRAFT_MODE '),
(0x2e0, 'packOpeningAnimation '),
]
print("\n-- gate bytes decoded from their accessor stubs --")
for off, name in SLOTS:
slot = struct.unpack('<Q', rd(vt + off, 8))[0]
stub = rd(slot, 8)
if stub[:3] == b'\x0f\xb6\x81':
disp = struct.unpack('<I', stub[3:7])[0]
val = rd(obj + disp, 1)[0]
print(" slot +%#05x %s disp=%#x VALUE=%d" % (off, name, disp, val))
else:
print(" slot +%#05x %s NOT a movzx stub: %s" % (off, name, stub.hex()))
print("\n-- market screen inputs --")
for disp, name in [(0x1fd1c, 'TRADE_PILE_SIZE'), (0x1fd20, 'watchListSize '),
(0x1fd2e, 'tradingEnabled '), (0x1fd2f, 'storeEnabled ')]:
print(" model+%#x %s = %d" % (disp, name, rd(obj + disp, 1)[0]))
os.close(fd)
File diff suppressed because it is too large Load Diff
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Dump CardsDLL's NULL-terminated {const char*, int} vocabulary tables from the
ON-DISK PE. READ-ONLY, static.
The transfer-market analysis records tradeState as decoding through a table walk at
0x180229e40 and lists sibling vocabularies (type/zone/lev/pos) as tables of the same
shape. This prints the exact token spellings and their integer codes, so the accepted
strings come from the client rather than from inference.
"""
import struct
DLL = "/mnt/games/FIFA 17/CardsDLL_Win64_retail.dll"
TABLES = [
(0x180229E40, "tradeState (table walk)"),
(0x180229C30, "type"),
(0x1802296E0, "zone"),
(0x180229A60, "lev"),
(0x1802295C0, "pos"),
(0x180229AB0, "cat"),
(0x180229880, "form"),
]
MAX_ROWS = 64
pe = open(DLL, "rb").read()
e_lfanew = struct.unpack_from("<I", pe, 0x3C)[0]
coff = e_lfanew + 4
num_sections = struct.unpack_from("<H", pe, coff + 2)[0]
opt_size = struct.unpack_from("<H", pe, coff + 16)[0]
opt = coff + 20
image_base = struct.unpack_from("<Q", pe, opt + 24)[0]
sec_off = opt + opt_size
sections = []
for i in range(num_sections):
b = sec_off + i * 40
vsize, vaddr, rawsize, rawptr = struct.unpack_from("<IIII", pe, b + 8)
sections.append((vaddr, vsize, rawptr, rawsize))
def va2off(va):
rva = va - image_base
for vaddr, vsize, rawptr, rawsize in sections:
if vaddr <= rva < vaddr + max(vsize, rawsize):
off = rva - vaddr + rawptr
if 0 <= off < len(pe):
return off
return None
def cstr(va, limit=64):
off = va2off(va)
if off is None:
return None
end = pe.find(b"\0", off, off + limit)
if end < 0:
return None
try:
s = pe[off:end].decode("ascii")
except UnicodeDecodeError:
return None
return s if s.isprintable() else None
for table_va, name in TABLES:
base = va2off(table_va)
print("\n=== %s VA %#x -> off %s ===" % (name, table_va, hex(base) if base else None))
if base is None:
print(" (VA did not resolve)")
continue
for i in range(MAX_ROWS):
ptr, code = struct.unpack_from("<Qi", pe, base + i * 16)
if ptr == 0:
print(" -- NULL terminator after %d rows --" % i)
break
s = cstr(ptr)
if s is None:
print(" row %d: ptr %#x does not resolve to a string; stopping" % (i, ptr))
break
print(" %-28s = %d" % (repr(s), code))
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "openfut-adapter-fifa17"
version = "0.1.0"
edition = "2021"
license = "MIT"
description = "FIFA 17 game adapter: Blaze command tables, response bodies and dispatch"
publish = false
[dependencies]
openfut-protocol-blaze = { path = "../openfut-protocol-blaze" }
# Reads the bundled fetchClientConfig table (227-243 rows per CFID), which is
# generated from the Python oracle rather than transcribed by hand. Unlike the
# protocol crate below it, this crate is ordinary server-side code, so a real
# JSON parser is the right call — hand-rolling one to preserve a zero-dependency
# streak would be reinventing a solved problem in the riskiest possible place.
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Seeded RNG for the Store pack-content generator (`fut::pack_content`). The
# generator is pure over an injected `rand::Rng`, so packs are deterministic
# under a seeded `StdRng` in tests and reproducible in production.
rand = "0.8"
[dev-dependencies]
# Differential fixtures are JSONL; the runtime dependency already covers it.
+115
View File
@@ -0,0 +1,115 @@
# openfut-adapter-fifa17
The FIFA 17 game adapter. Everything true of *FIFA 17 specifically* lives here,
so that neither OpenFUT Core nor the generic protocol crates have to know about
it.
```
openfut-protocol-blaze generic Blaze: Fire2 framing, Heat2/TDF codec
▲
openfut-adapter-fifa17 THIS: command tables, response bodies, dispatch order
▲
OpenFUT Core game-independent FUT domain (not yet wired)
```
## Status
| Surface | Port | State |
|---|---|---|
| **Blaze / Fire2 RPC** | 42130 | **Implemented**, byte-for-byte parity-tested |
| Redirector (HTTPS + XML) | 42127 | Python only |
| Nucleus OAuth stub | 42131 | Python only |
| LSX / Origin | 4216 | Python only |
| Roster XML | 8081 | Python only |
| UTAS / RS4 | 8099 | Python only |
| POW / EASFC | 8094 / 8080 | Python only |
**Nothing here is wired into the running backend.** The crate answers frames; it
opens no socket, terminates no TLS and owns no runtime. The Python backend
remains the live service and the behavioural oracle.
## What the adapter owns, and what it must not
Owns: component/command/notification IDs, response body shapes, dispatch
ordering, session identity, the `fetchClientConfig` tables.
Must not own: FUT domain state. Blaze is an auth/session/config protocol — no
coins, packs, clubs or squads appear on this wire — so `Session` holds a session
key, a locale, a service name, an auth code and a flag, and that is all. When
UTAS is migrated that boundary will need active defending; here it comes free.
## Parity
```bash
./check-parity.sh # oracle freshness + byte-for-byte replay
./check-parity.sh --regen # after an intentional oracle change
```
`fixtures/blaze_transactions.jsonl` holds 49 request→response(s) transactions
produced by calling the real `blaze_responder_v3b.dispatch()`. They replay in
order against a shared session per connection, so ordering-dependent behaviour
is exercised rather than assumed: preAuth captures the locale that later `ALOC`
fields echo, and login sets the auth code `getAuthToken` returns afterwards.
Comparison is byte-for-byte including frame count and order — a missing
post-login notification or a reply where the oracle stays silent fails here.
The suite was **mutation-tested**: swapping two post-login notifications,
flipping one enum deep inside `AccountInfo`, and hardcoding an address in
`utas_base()`/`nucleus_base()` were each verified to turn it red. The third
initially did *not*, because the config templating had made those helpers dead
code; the table now templates on URL-level tokens so they are the single place a
URL shape is defined.
## Three behaviours that are easy to get wrong
* **Login answers with four frames, in order**: reply, then `UserAuthenticated`,
`UserSessionExtendedDataUpdate`, `UserAdded`.
* **An unimplemented RPC still gets an empty reply.** Silence makes the client
wait for a timeout; an empty reply lets every field fall back to a client-side
default and the boot continues.
* **Non-request message types get nothing at all.**
No error replies are emitted. `msgType` 3 exists, but the error-code placement
is UNRESOLVED — three clean-room sources disagree between `header[14:16]`, a
metadata `ERRC`, and a payload `CNTX`/`ERRC` — so emitting one would be a guess
on the wire.
## The client config table
`fixtures/client_config.json` carries 227–243 rows per CFID, generated from the
Python oracle and templated on `{utas_base}`, `{nucleus_base}`,
`{pow_content_url}`, `{advertise}`, `{bind}`, `{pow_host}`. It is
reverse-engineered *data*, not logic, and deriving it mechanically removes a
class of transcription typo no reviewer could catch. The generator does not take
its own templating on trust: it substitutes real addresses back in and diffs
against the oracle for every section before writing the file.
The table must be *complete*, not representative. The client resolves a per-call
key (`FUT_RS4_URL_<CALL>`) before a per-module one, and any unresolved call falls
back to a real, dead EA host — that is what produced "there has been an error
connecting to FIFA 17 Ultimate Team" mid-session when only the boot subset was
served.
## Known defect reproduced deliberately
`nucleusConnect` and `nucleusConnectTrusted` are built from the **bind** address,
not the advertised one. On the live split deployment that means the backend
tells a client on another machine to reach Nucleus at `http://0.0.0.0:42131`,
which it cannot. Verified against the running container, not inferred.
This is reproduced exactly, because it is what the only proven-working
configuration does and changing it would break parity. It also implies the
Nucleus stub is not actually reached in the current remote flow. Fixing it is a
separate change that needs live validation — see the vault.
## Configuration
Nothing is hardcoded. `AdapterConfig` carries `Identity` (persona, ids, email,
namespace, entitlement group, …) and `Endpoints` (advertise, bind, POW hosts,
telemetry/ticker/QoS ports). `Default` gives the project's synthetic offline
identity on loopback; a remote deployment must override `advertise`.
Bind and advertise are deliberately distinct: an advertised URL must carry the
address the *client* can reach, which on a two-machine deployment is not the
address the server binds.
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Differential check: the Rust FIFA 17 Blaze adapter vs the Python responder.
#
# 1. assert the committed fixtures still match what the Python oracle emits
# 2. replay every recorded transaction through the Rust adapter, byte-for-byte
#
# Read-only with respect to the running backend: the oracle is imported as a
# library, no responder is started, no port is bound, no live service is
# touched. Safe to run while the Python backend is serving a live FIFA client.
#
# Use --regen to rewrite the fixtures after an intentional oracle change.
set -euo pipefail
cd "$(dirname "$(readlink -f "$0")")"
if [[ "${1:-}" == "--regen" ]]; then
echo "==> regenerating fixtures from the Python oracle"
python3 fixtures/generate.py
else
echo "==> checking committed fixtures against the Python oracle"
python3 fixtures/generate.py --check
fi
echo "==> replaying transactions through the Rust adapter"
cargo test -p openfut-adapter-fifa17
echo
echo "PARITY OK — the adapter reproduces the Python dispatcher byte-for-byte."
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+460
View File
@@ -0,0 +1,460 @@
#!/usr/bin/env python3
"""Freeze the Python Blaze responder's DISPATCH contract as replayable fixtures.
The crate-level fixtures in `openfut-protocol-blaze` pin the *codec*: given a
field tree, what bytes come out. This file pins the layer above: given an
inbound Fire2 frame and a session, **which frames go back, in what order**.
That is the whole contract of a Blaze adapter, and it is the thing a rewrite can
silently get wrong in ways a codec test cannot see — a missing post-login
notification, a reply where the oracle stays silent, notifications in the wrong
order, session state not carried between RPCs.
Every transaction is produced by calling the real
`blaze_responder_v3b.dispatch()`. Session state is threaded across a scripted
connection exactly as it would be on a live socket, so ordering-dependent
behaviour (preAuth captures the locale; login sets the auth code that
getAuthToken later returns) is captured rather than assumed.
Determinism: the oracle's clock is pinned and its PRNG seeded, and the
deployment-dependent addresses are set before import (the responder reads them
at import time). See the sibling generator in openfut-protocol-blaze.
NO SECRETS. The identity here (persona 33068179 / "CAGE") is the project's fixed
synthetic offline identity. Session keys are minted from a seeded PRNG.
Usage: python3 fixtures/generate.py (write)
python3 fixtures/generate.py --check (verify committed files are current)
"""
from __future__ import annotations
import json
import os
import random
import sys
from collections import OrderedDict
HERE = os.path.dirname(os.path.abspath(__file__))
TOOLS = os.path.normpath(os.path.join(HERE, "..", "..", "fifa17-recon", "tools"))
if not os.path.isdir(TOOLS):
sys.exit("cannot find the Python oracle at %s" % TOOLS)
sys.path.insert(0, TOOLS)
CHECK_ONLY = "--check" in sys.argv[1:]
# Internal mode: re-exec of this script with sentinel addresses, used to derive
# the templated client-config table (see emit_config_table).
CONFIG_TABLE_MODE = "--_config_table" in sys.argv[1:]
sys.argv = [sys.argv[0]]
# Sentinels substituted back into template tokens. Deliberately not IP-shaped so
# a stray literal cannot be mistaken for a real address.
SENTINELS = [
("ADVERTISE-SENTINEL", "{advertise}"),
("BIND-SENTINEL", "{bind}"),
("POWCONTENT-SENTINEL", "{pow_content_host}"),
("POWHOST-SENTINEL", "{pow_host}"),
]
if CONFIG_TABLE_MODE:
os.environ["OPENFUT_ADVERTISE"] = "ADVERTISE-SENTINEL"
os.environ["OPENFUT_BIND"] = "BIND-SENTINEL"
os.environ["POW_CONTENT_HOST"] = "POWCONTENT-SENTINEL"
os.environ["POW_HOST"] = "POWHOST-SENTINEL"
import blaze_responder_v3b as _B # noqa: E402
out = {cfid: _B.client_config_for(cfid) for cfid in sorted(_B.CLIENT_CONFIGS)}
out["__default__"] = _B.client_config_for("__no_such_section__")
print(json.dumps(out))
raise SystemExit(0)
# Pin deployment config BEFORE import — the responder snapshots these at import
# time into module globals used by the response builders.
#
# Distinct, obviously-fake values on purpose: if the Rust adapter hardcoded an
# address instead of reading its config, these make the failure loud rather than
# accidentally matching a loopback default.
ADVERTISE = "198.51.100.7"
BIND = "0.0.0.0"
POW_CONTENT_HOST = "198.51.100.7:8085"
POW_HOST = "198.51.100.7:8094"
os.environ["OPENFUT_ADVERTISE"] = ADVERTISE
os.environ["OPENFUT_BIND"] = BIND
os.environ["POW_CONTENT_HOST"] = POW_CONTENT_HOST
os.environ["POW_HOST"] = POW_HOST
import heat2 # noqa: E402
import blaze_responder_v3b as B # noqa: E402
from fut_account import ACCOUNT # noqa: E402
FIXED_NOW = 1754870400
INT, STRING, STRUCT, LIST, MAP, BLOB = (
heat2.INT, heat2.STRING, heat2.STRUCT, heat2.LIST, heat2.MAP, heat2.BLOB)
RECORDS = []
# ------------------------------------------------------------------ helpers
def req_frame(component, command, fields=None, msg_num=1, msg_type=None,
user_index=0):
"""Build an inbound request frame the way the client would."""
msg_type = B.MESSAGE if msg_type is None else msg_type
payload = heat2.encode_tdf(fields) if fields else b""
return B.fire2(component, command, msg_num, msg_type, payload,
user_index=user_index)
def tx(session, name, frame, note=""):
"""Run one frame through the real dispatcher and record what came back."""
hdr = B.parse_fire2_header(frame)
body = frame[16 + hdr["metadata_len"]:]
fields = heat2.decode_tdf(body) if body else OrderedDict()
out = B.dispatch(hdr, fields, body, session["sess"])
RECORDS.append(OrderedDict((
("kind", "tx"),
("session", session["id"]),
("name", name),
("note", note),
("request_hex", frame.hex()),
("responses", [f.hex() for f in out]),
)))
return out
def new_session(sid):
s = {"id": sid, "sess": B.Session()}
RECORDS.append(OrderedDict((
("kind", "session"),
("id", sid),
# Minted per connection by the oracle; the Rust side must be able to
# inject it, because it appears in LoginResponse.SESS.KEY, the
# UserAuthenticated push and PostAuthResponse.TELE.SESS and all three
# must be the same string.
("session_key", s["sess"].session_key),
("account_locale", s["sess"].account_locale),
("service_name", s["sess"].service_name),
)))
return s
# ------------------------------------------------------------------ script
def build():
RECORDS.append(OrderedDict((
("kind", "config"),
("advertise", ADVERTISE),
("bind", BIND),
("pow_content_host", POW_CONTENT_HOST),
("pow_host", POW_HOST),
("now", FIXED_NOW),
("identity", OrderedDict((
("persona_id", ACCOUNT.persona_id),
("persona_name", ACCOUNT.persona_name),
("user_id", ACCOUNT.user_id),
("ext_id", ACCOUNT.ext_id),
("email", ACCOUNT.email),
("namespace", ACCOUNT.NAMESPACE),
("client_platform", ACCOUNT.CLIENT_PLATFORM),
("persona_status", ACCOUNT.PERSONA_STATUS),
("user_session_type", ACCOUNT.USER_SESSION_TYPE),
("account_locale_int", ACCOUNT.account_locale_int),
("locale", ACCOUNT.locale),
("content_id", ACCOUNT.CONTENT_ID),
("entitlement_tag", ACCOUNT.ENTITLEMENT_TAG),
("entitlement_group", ACCOUNT.ENTITLEMENT_GROUP),
("title_id", ACCOUNT.TITLE_ID),
("client_id", ACCOUNT.CLIENT_ID),
("platform", ACCOUNT.PLATFORM),
("server_version", B.SERVER_VERSION),
))),
)))
# ================= main connection: the real boot order =================
#
# Mirrors what FIFA 17 actually does, because ordering is load-bearing:
# preAuth captures the locale that later ALOC fields echo, and login sets
# the auth code that getAuthToken returns afterwards.
m = new_session("main")
tx(m, "preauth", req_frame(B.COMP_UTIL, B.CMD_PREAUTH, OrderedDict([
("CDAT", (STRUCT, OrderedDict([
("IITO", (INT, 0)),
("LANG", (INT, 0x656E5553)), # 'enUS'
("SVCN", (STRING, "fifa-2017-pc")), # echoed back as INST
("TYPE", (INT, 0)),
]))),
("CINF", (STRUCT, OrderedDict([
("BSDK", (STRING, "15.1.1.3.0")),
("CLNT", (STRING, "FIFA17")),
("ENV", (STRING, "prod")),
("LOC", (INT, 0x656E5553)),
]))),
("FCCR", (STRUCT, OrderedDict([("CFID", (STRING, "BlazeSDK"))]))),
])), "first RPC; echoes SVCN as INST and captures LANG for ALOC")
tx(m, "ping", req_frame(B.COMP_UTIL, B.CMD_PING, msg_num=2),
"Util::ping -> STIM only")
# Every section the responder knows, plus unknown ones. The known sections
# each add their own rows on top of the shared FUT/RS4 base — OSDK_ROSTER in
# particular carries the roster URL, itself a documented loading gate — so
# covering only "BlazeSDK" would leave most of the table unverified.
for cfid in ("BlazeSDK", "netres", "IdentityParams", "OSDK_CORE",
"OSDK_CLIENT", "OSDK_NUCLEUS", "OSDK_ROSTER", "OSDK_TICKER",
"OSDK_WEBOFFER", "OSDK_POW", "OSDK_ABUSE_REPORTING",
"OSDK_XMS_ABUSE_REPORTING", "UTAS", "FUT", "",
"TOTALLY_UNKNOWN"):
tx(m, "fetch_config_%s" % (cfid or "empty"),
req_frame(B.COMP_UTIL, B.CMD_FETCHCLIENTCONFIG,
OrderedDict([("CFID", (STRING, cfid))]), msg_num=3),
"unknown CFIDs still get the shared FUT/POW rows")
tx(m, "get_auth_token_before_login",
req_frame(B.COMP_AUTH, B.CMD_GETAUTHTOKEN, msg_num=4),
"no auth code yet -> synthesised OPENFUT-<key[:16]> token")
tx(m, "logout_before_login", req_frame(B.COMP_AUTH, B.CMD_LOGOUT, msg_num=5),
"routine LoginStateLogout (state 500), NOT a failure; empty reply")
tx(m, "login", req_frame(B.COMP_AUTH, B.CMD_LOGIN, OrderedDict([
("AUTH", (STRING, "OPENFUT-TEST-AUTHCODE")),
("EXTB", (BLOB, b"")),
("PNAM", (STRING, "")),
]), msg_num=6),
"reply THEN three UserSessions pushes, in that order")
tx(m, "get_auth_token_after_login",
req_frame(B.COMP_AUTH, B.CMD_GETAUTHTOKEN, msg_num=7),
"now echoes the login's AUTH verbatim")
tx(m, "get_account", req_frame(B.COMP_AUTH, B.CMD_GETACCOUNT, msg_num=8),
"the RPC behind 'Unable to retrieve account information'")
tx(m, "get_persona", req_frame(B.COMP_AUTH, B.CMD_GETPERSONA, msg_num=9))
tx(m, "list_personas", req_frame(B.COMP_AUTH, B.CMD_LISTPERSONAS, msg_num=10))
for cmd, label in ((B.CMD_LISTUSERENTITLEMENTS2, "listUserEntitlements2"),
(0x20, "listEntitlements"),
(0x30, "listPersonaEntitlements2"),
(0x27, "grantEntitlement2")):
tx(m, "entitlements_%s" % label,
req_frame(B.COMP_AUTH, cmd, msg_num=11),
"all four aliases return the same two ONLINE_ACCESS records")
tx(m, "post_auth", req_frame(B.COMP_UTIL, B.CMD_POSTAUTH, msg_num=12),
"TELE/TICK/UROP; TELE.SESS must equal the login session key")
tx(m, "fetch_qos_config", req_frame(B.COMP_UTIL, 0x15, msg_num=13))
tx(m, "user_settings_load",
req_frame(B.COMP_UTIL, B.CMD_USERSETTINGSLOAD, msg_num=14))
tx(m, "user_settings_save",
req_frame(B.COMP_UTIL, B.CMD_USERSETTINGSSAVE, msg_num=15),
"accepted and discarded; empty reply")
tx(m, "set_client_state",
req_frame(B.COMP_UTIL, B.CMD_SETCLIENTSTATE, msg_num=16))
tx(m, "set_client_metrics",
req_frame(B.COMP_UTIL, B.CMD_SETCLIENTMETRICS, msg_num=17))
tx(m, "update_network_info",
req_frame(B.COMP_USERSESSIONS, B.CMD_UPDATENETWORKINFO, msg_num=18),
"empty reply PLUS an unsolicited ExtendedDataUpdate push")
tx(m, "get_lists", req_frame(B.COMP_ASSOCLISTS, B.CMD_GETLISTS, msg_num=19))
tx(m, "census_subscribe",
req_frame(B.COMP_CENSUSDATA, B.CMD_SUBSCRIBETOCENSUSDATAUPDATES,
OrderedDict([("RSUB", (INT, 1))]), msg_num=20),
"non-zero TimeValues or the client storms at ~30/s and hangs the FUT load")
tx(m, "logout_after_login",
req_frame(B.COMP_AUTH, B.CMD_LOGOUT, msg_num=21),
"session teardown after a login; still an empty reply")
# ============================ fallback behaviour ========================
f = new_session("fallbacks")
tx(f, "transport_ping",
req_frame(B.COMP_UTIL, B.CMD_PING, msg_num=30, msg_type=B.PING),
"msgType PING -> PING_REPLY with an empty body, whatever the command")
for mt, label in ((B.REPLY, "reply"), (B.NOTIFICATION, "notification"),
(B.ERROR_REPLY, "error_reply"),
(B.PING_REPLY, "ping_reply")):
tx(f, "ignores_%s" % label,
req_frame(B.COMP_UTIL, B.CMD_PING, msg_num=31, msg_type=mt),
"not a request -> NO frames at all")
tx(f, "unknown_command",
req_frame(B.COMP_UTIL, 0x0FFF, msg_num=32),
"unimplemented RPC still gets an EMPTY reply so the client cannot hang")
tx(f, "unknown_component",
req_frame(0x1234, 0x0001, msg_num=33),
"same fallback for an entirely unknown component")
tx(f, "user_index_is_echoed",
req_frame(B.COMP_UTIL, B.CMD_PING, msg_num=34, user_index=7),
"a reply echoes component/command/msgNum/userIndex verbatim")
# ================= locale echo on a non-default client ==================
loc = new_session("locale")
tx(loc, "preauth_de_locale",
req_frame(B.COMP_UTIL, B.CMD_PREAUTH, OrderedDict([
("CDAT", (STRUCT, OrderedDict([
("LANG", (INT, 0x64654445)), # 'deDE'
("SVCN", (STRING, "fifa-2017-pc-de")),
]))),
])),
"a non-enUS client: SVCN echo AND the captured locale must both change")
tx(loc, "login_with_de_locale",
req_frame(B.COMP_AUTH, B.CMD_LOGIN, msg_num=41),
"UserAuthenticated.ALOC must carry the captured deDE locale")
# ------------------------------------------------------------------- output
def emit_config_table():
"""Derive the fetchClientConfig tables as address-TEMPLATED data.
These are 227-243 key/value rows per CFID, almost all of them the same URL.
Hand-transcribing them into Rust would be 400 lines of string literals that
nobody can review and one typo can break; deriving them mechanically from
the oracle removes that whole class of error and keeps them regenerable.
They are reverse-engineered *data*, not logic — the same reason
`openfut-core` loads its content from `data/` rather than from source.
The values are templated on {advertise}/{bind}/{pow_content_host}/{pow_host}
so the adapter stays configurable; baking an address in here would recreate
exactly the hardcoding the client/server split removed.
Correctness is not assumed: the caller substitutes real addresses back in
and diffs against the oracle. See verify_config_table.
"""
import subprocess
raw = subprocess.run(
[sys.executable, os.path.abspath(__file__), "--_config_table"],
capture_output=True, text=True, check=True,
# Inherit nothing address-shaped; the child sets its own sentinels.
env={k: v for k, v in os.environ.items()
if not k.startswith(("OPENFUT_", "POW_", "FUT_"))},
).stdout
table = json.loads(raw)
def templatise(value):
for sentinel, token in SENTINELS:
value = value.replace(sentinel, token)
# Collapse whole URLs to URL-level tokens where one exists, so the Rust
# side builds them in exactly one place (AdapterConfig::utas_base and
# friends) instead of re-deriving the shape here. Without this the
# helpers become dead code and a hardcoded address in them goes
# undetected — verified by mutation testing. Longest first.
for whole, token in (
("http://{advertise}:8099/", "{utas_base}"),
("http://{bind}:42131", "{nucleus_base}"),
("http://{pow_content_host}", "{pow_content_url}"),
):
if value == whole:
return token
return value
return {cfid: [[k, templatise(v)] for k, v in rows]
for cfid, rows in table.items()}
def verify_config_table(table):
"""Substitute the real addresses back and require the oracle's exact rows.
This is what makes the templated table trustworthy rather than plausible.
"""
subst = {
"{utas_base}": "http://%s:8099/" % ADVERTISE,
"{nucleus_base}": "http://%s:42131" % BIND,
"{pow_content_url}": "http://%s" % POW_CONTENT_HOST,
"{advertise}": ADVERTISE,
"{bind}": BIND,
"{pow_content_host}": POW_CONTENT_HOST,
"{pow_host}": POW_HOST,
}
def render(v):
for token, real in subst.items():
v = v.replace(token, real)
return v
for cfid, rows in table.items():
expected = B.client_config_for(
"__no_such_section__" if cfid == "__default__" else cfid)
got = [(k, render(v)) for k, v in rows]
if got != [(k, v) for k, v in expected]:
for (gk, gv), (ek, ev) in zip(got, expected):
if (gk, gv) != (ek, ev):
sys.exit("config template mismatch in %s: %r -> %r, oracle "
"has %r -> %r" % (cfid, gk, gv, ek, ev))
sys.exit("config template row-count mismatch in %s: %d vs %d"
% (cfid, len(got), len(expected)))
print("config table verified against the oracle for %d sections"
% len(table))
def frozen_clock():
import time as _time
original = _time.time
_time.time = lambda: float(FIXED_NOW)
return original, _time
def write(path, records):
body = "".join(json.dumps(r, separators=(",", ":")) + "\n" for r in records)
if CHECK_ONLY:
if not os.path.exists(path):
sys.exit("MISSING: %s has never been generated" % path)
with open(path, "r", encoding="utf-8") as fh:
if fh.read() != body:
sys.exit("STALE: %s does not match the oracle; re-run without "
"--check" % path)
print("current: %s (%d records)" % (os.path.basename(path), len(records)))
return
with open(path, "w", encoding="utf-8") as fh:
fh.write(body)
print("wrote %s (%d records)" % (os.path.basename(path), len(records)))
def write_json(path, obj):
body = json.dumps(obj, indent=1, sort_keys=True) + "\n"
if CHECK_ONLY:
if not os.path.exists(path):
sys.exit("MISSING: %s has never been generated" % path)
with open(path, "r", encoding="utf-8") as fh:
if fh.read() != body:
sys.exit("STALE: %s does not match the oracle" % path)
print("current: %s" % os.path.basename(path))
return
with open(path, "w", encoding="utf-8") as fh:
fh.write(body)
print("wrote %s (%d sections)" % (os.path.basename(path), len(obj)))
def main():
# The oracle logs every dispatch to stdout; useful live, pure noise here.
B.log = lambda *_a, **_k: None
table = emit_config_table()
verify_config_table(table)
write_json(os.path.join(HERE, "client_config.json"), table)
random.seed(0xB1A2E)
original_time, time_mod = frozen_clock()
try:
build()
finally:
time_mod.time = original_time
write(os.path.join(HERE, "blaze_transactions.jsonl"), RECORDS)
txs = [r for r in RECORDS if r["kind"] == "tx"]
frames = sum(len(r["responses"]) for r in txs)
print("%d transactions, %d response frames, %d sessions"
% (len(txs), frames,
len([r for r in RECORDS if r["kind"] == "session"])))
if __name__ == "__main__":
main()
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Capture the roster oracle's responses byte-for-byte.
generate_roster.py [--check] [host:port]
Unlike `generate.py`, which imports the Blaze responder and calls its pure
functions, this captures over the wire. The roster response is shaped as much by
`http.server.BaseHTTPRequestHandler` as by the handler code -- HTTP/1.0 status
line, `Server:`/`Date:` injected ahead of the handler's own headers, POST
answered without a body -- and only the real socket shows all of that.
Two fields are volatile and are MASKED rather than recorded:
Date: changes every second
Server: carries the container's Python version
They are masked, not dropped, so their presence and position are still asserted.
The Server string is additionally recorded verbatim under `observed_server`, so
a drift between the container's Python and the adapter's `ORACLE_SERVER`
constant is visible rather than silent.
`--check` re-captures and compares. If the oracle is unreachable it FAILS rather
than passing: a check that cannot check must not report success.
"""
import json
import os
import re
import socket
import ssl
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "roster.json")
PATH = "/fifa17/fut/rosterupdate.xml"
DATE_RE = re.compile(rb"^Date: .+?\r\n", re.M)
SERVER_RE = re.compile(rb"^Server: (.+?)\r\n", re.M)
def fetch(host, port, method, body=None):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ctx.set_ciphers("ALL:@SECLEVEL=0")
s = ctx.wrap_socket(socket.create_connection((host, port), timeout=8),
server_hostname="fixture")
req = "%s %s HTTP/1.1\r\nHost: %s:%d\r\nAccept: */*\r\n" % (method, PATH, host, port)
if body is not None:
req += "Content-Length: %d\r\n" % len(body)
req += "\r\n"
s.sendall(req.encode() + (body or b""))
out = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
out += chunk
s.close()
return out
def capture(host, port):
result = {"path": PATH, "responses": {}}
servers = set()
for method, body in (("GET", None), ("HEAD", None), ("POST", b"probe=1")):
raw = fetch(host, port, method, body)
m = SERVER_RE.search(raw)
if m:
servers.add(m.group(1).decode())
masked = DATE_RE.sub(b"Date: <MASKED>\r\n", raw)
masked = SERVER_RE.sub(b"Server: <MASKED>\r\n", masked)
result["responses"][method] = masked.hex()
if len(servers) != 1:
raise SystemExit("oracle returned inconsistent Server headers: %r" % servers)
result["observed_server"] = servers.pop()
return result
def main():
check = "--check" in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith("--")]
host, port = (args[0].split(":") if args else ("127.0.0.1", "8081"))[0], \
int((args[0].split(":")[1] if args and ":" in args[0] else "8081"))
try:
fresh = capture(host, port)
except Exception as e:
# Explicitly a failure. A --check that silently passes when it could not
# reach the oracle is exactly the class of self-confirming tooling this
# project has been bitten by repeatedly.
raise SystemExit("cannot reach the roster oracle at %s:%d (%s). "
"Refusing to report success." % (host, port, e))
if check:
if not os.path.exists(OUT):
raise SystemExit("no fixture at %s -- run without --check first" % OUT)
with open(OUT) as f:
stored = json.load(f)
if stored.get("responses") != fresh["responses"]:
for m in sorted(set(stored.get("responses", {})) | set(fresh["responses"])):
a = stored.get("responses", {}).get(m)
b = fresh["responses"].get(m)
if a != b:
print("MISMATCH %s\n stored: %s\n live : %s" % (m, a, b))
raise SystemExit("roster fixtures differ from the live oracle")
if stored.get("observed_server") != fresh["observed_server"]:
raise SystemExit(
"the oracle's Server header changed: %r -> %r.\n"
"Update roster::ORACLE_SERVER and regenerate."
% (stored.get("observed_server"), fresh["observed_server"]))
print("roster fixtures match the live oracle (%d responses, server=%r)"
% (len(fresh["responses"]), fresh["observed_server"]))
return
with open(OUT, "w") as f:
json.dump(fresh, f, indent=2, sort_keys=True)
f.write("\n")
print("wrote %s (%d responses, server=%r)"
% (OUT, len(fresh["responses"]), fresh["observed_server"]))
if __name__ == "__main__":
main()
@@ -0,0 +1,6 @@
{
"127.0.0.1": "485454502f312e3120323030204f4b0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a203331350d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e0a3c736572766572696e7374616e6365696e666f3e0a093c61646472657373206d656d6265723d2230223e0a09093c76616c753e0a0909093c686f73746e616d653e3132372e302e302e313c2f686f73746e616d653e0a0909093c69703e323133303730363433333c2f69703e0a0909093c706f72743e34323133303c2f706f72743e0a09093c2f76616c753e0a093c2f616464726573733e0a093c7365637572653e303c2f7365637572653e0a093c747269616c736572766963656e616d653e3c2f747269616c736572766963656e616d653e0a093c64656661756c74646e73616464726573733e303c2f64656661756c74646e73616464726573733e0a3c2f736572766572696e7374616e6365696e666f3e0a",
"192.0.2.1": "485454502f312e3120323030204f4b0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a203331350d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e0a3c736572766572696e7374616e6365696e666f3e0a093c61646472657373206d656d6265723d2230223e0a09093c76616c753e0a0909093c686f73746e616d653e3139322e302e322e313c2f686f73746e616d653e0a0909093c69703e333232313232353938353c2f69703e0a0909093c706f72743e34323133303c2f706f72743e0a09093c2f76616c753e0a093c2f616464726573733e0a093c7365637572653e303c2f7365637572653e0a093c747269616c736572766963656e616d653e3c2f747269616c736572766963656e616d653e0a093c64656661756c74646e73616464726573733e303c2f64656661756c74646e73616464726573733e0a3c2f736572766572696e7374616e6365696e666f3e0a",
"198.51.100.7": "485454502f312e3120323030204f4b0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a203331380d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e0a3c736572766572696e7374616e6365696e666f3e0a093c61646472657373206d656d6265723d2230223e0a09093c76616c753e0a0909093c686f73746e616d653e3139382e35312e3130302e373c2f686f73746e616d653e0a0909093c69703e333332353235363731313c2f69703e0a0909093c706f72743e34323133303c2f706f72743e0a09093c2f76616c753e0a093c2f616464726573733e0a093c7365637572653e303c2f7365637572653e0a093c747269616c736572766963656e616d653e3c2f747269616c736572766963656e616d653e0a093c64656661756c74646e73616464726573733e303c2f64656661756c74646e73616464726573733e0a3c2f736572766572696e7374616e6365696e666f3e0a",
"203.0.113.42": "485454502f312e3120323030204f4b0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a203331380d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d38223f3e0a3c736572766572696e7374616e6365696e666f3e0a093c61646472657373206d656d6265723d2230223e0a09093c76616c753e0a0909093c686f73746e616d653e3230332e302e3131332e34323c2f686f73746e616d653e0a0909093c69703e333430353830333831383c2f69703e0a0909093c706f72743e34323133303c2f706f72743e0a09093c2f76616c753e0a093c2f616464726573733e0a093c7365637572653e303c2f7365637572653e0a093c747269616c736572766963656e616d653e3c2f747269616c736572766963656e616d653e0a093c64656661756c74646e73616464726573733e303c2f64656661756c74646e73616464726573733e0a3c2f736572766572696e7374616e6365696e666f3e0a"
}
@@ -0,0 +1,9 @@
{
"observed_server": "BaseHTTP/0.6 Python/3.12.13",
"path": "/fifa17/fut/rosterupdate.xml",
"responses": {
"GET": "485454502f312e3020323030204f4b0d0a5365727665723a203c4d41534b45443e0d0a446174653a203c4d41534b45443e0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a2036370d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d227574662d38223f3e0a3c726f737465727570646174652076657273696f6e3d2230222f3e0a",
"HEAD": "485454502f312e3020323030204f4b0d0a5365727665723a203c4d41534b45443e0d0a446174653a203c4d41534b45443e0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a2036370d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a",
"POST": "485454502f312e3020323030204f4b0d0a5365727665723a203c4d41534b45443e0d0a446174653a203c4d41534b45443e0d0a436f6e74656e742d547970653a206170706c69636174696f6e2f786d6c0d0a436f6e74656e742d4c656e6774683a2036370d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a"
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,14 @@
MARKER at-player-search 19:03:01 UTC
watermark=13
MARKER NO_FILTER 19:04:35 UTC
MARKER GOLD 19:16:44 UTC
NOTE: the FIFA 17 My Squad UI labels this filter SPECIAL, not Rare. Captured under label SPECIAL.
MARKER SPECIAL 19:21:05 UTC
MARKER POSITION_ST 19:22:00 UTC
MARKER NATION_ARGENTINA 19:22:53 UTC
MARKER LEAGUE_PREMIER 19:23:34 UTC
MARKER CLUB_CHELSEA 19:24:34 UTC
MARKER GOLD_PLUS_ST 19:25:26 UTC
MARKER LEAGUE_PLUS_ST 19:27:27 UTC
MARKER PAGINATION 19:28:49 UTC
NOTE: no sort control exists in the My Squad UI; sort=desc is a client constant.
@@ -0,0 +1,84 @@
{
"routes": {
"accountInfo": {
"body_len": 2,
"fields": {
"keys": []
},
"sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
"status": 200
},
"activeSquad": {
"body_len": 8034,
"fields": {
"formation": "f442",
"id": 0,
"players.count": 23,
"slots": {
"0": 100000003,
"1": 100000006,
"10": 100000010,
"11": 0,
"12": 0,
"13": 0,
"14": 0,
"15": 0,
"16": 0,
"17": 0,
"18": 0,
"19": 0,
"2": 100000005,
"20": 0,
"21": 0,
"22": 0,
"3": 100000008,
"4": 100000007,
"5": 100000002,
"6": 100000004,
"7": 100000009,
"8": 100000001,
"9": 100000025
}
},
"sha256": "07e330ed358fbefe31379cd2462aaac4bdc9c85ee28b7500dd2d963e5ea565bd",
"status": 200
},
"credits": {
"body_len": 148,
"fields": {
"credits": 28112944
},
"sha256": "0a5f3bac80c3a8ee6f088ccf180f5fdcbcbe8a2ef19c7026e4f21876016d7786",
"status": 200
},
"tradePile": {
"body_len": 862,
"fields": {
"auctionInfo.count": 1
},
"sha256": "b42bab98202209bd8309beb0eca73dba471688e69fef3e014b59901fbc21fe04",
"status": 200
},
"unassigned": {
"body_len": 16,
"fields": {
"itemData.count": 0
},
"sha256": "873f8bba8baf9c573fc51b54d100c357b3bf0caeb2ccd104245c295e073cf342",
"status": 200
},
"userMassInfo": {
"body_len": 8929,
"fields": {
"clubAbbr": "OFC",
"clubName": "OpenFUT",
"personaId": 33068179,
"trophies": 0
},
"sha256": "a616aca1742263c47ade9409693e66ec13b50114e608d88bb94141ce80237b66",
"status": 200
}
},
"unix": 1786476617.899911,
"upstream": "127.0.0.1:8099"
}
@@ -0,0 +1,84 @@
{
"routes": {
"accountInfo": {
"body_len": 2,
"fields": {
"keys": []
},
"sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
"status": 200
},
"activeSquad": {
"body_len": 8034,
"fields": {
"formation": "f442",
"id": 0,
"players.count": 23,
"slots": {
"0": 100000003,
"1": 100000006,
"10": 100000010,
"11": 0,
"12": 0,
"13": 0,
"14": 0,
"15": 0,
"16": 0,
"17": 0,
"18": 0,
"19": 0,
"2": 100000005,
"20": 0,
"21": 0,
"22": 0,
"3": 100000008,
"4": 100000007,
"5": 100000002,
"6": 100000004,
"7": 100000009,
"8": 100000001,
"9": 100000025
}
},
"sha256": "07e330ed358fbefe31379cd2462aaac4bdc9c85ee28b7500dd2d963e5ea565bd",
"status": 200
},
"credits": {
"body_len": 148,
"fields": {
"credits": 28112944
},
"sha256": "0a5f3bac80c3a8ee6f088ccf180f5fdcbcbe8a2ef19c7026e4f21876016d7786",
"status": 200
},
"tradePile": {
"body_len": 862,
"fields": {
"auctionInfo.count": 1
},
"sha256": "b42bab98202209bd8309beb0eca73dba471688e69fef3e014b59901fbc21fe04",
"status": 200
},
"unassigned": {
"body_len": 16,
"fields": {
"itemData.count": 0
},
"sha256": "873f8bba8baf9c573fc51b54d100c357b3bf0caeb2ccd104245c295e073cf342",
"status": 200
},
"userMassInfo": {
"body_len": 8929,
"fields": {
"clubAbbr": "OFC",
"clubName": "OpenFUT",
"personaId": 33068179,
"trophies": 0
},
"sha256": "a616aca1742263c47ade9409693e66ec13b50114e608d88bb94141ce80237b66",
"status": 200
}
},
"unix": 1786474768.2925124,
"upstream": "127.0.0.1:8099"
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"squad": [{"rating": 89, "chemistry": 59, "formation": "f442", "id": 0, "squadName": "OpenFUT", "squadType": "REGULAR_SQUAD"}]}
@@ -0,0 +1 @@
{"id": 0, "custom": "[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,50,0,50,40,65,0,65,50,50,1]", "squadName": "OpenFUT", "chemistry": 49, "starRating": 90, "rating": 90, "formation": "f433", "squadType": "REGULAR_SQUAD", "manager": [{"id": 100000427, "dream": false}], "players": [{"index": 0, "itemData": {"id": 100000003, "dream": false}, "kitNumber": 1}, {"index": 1, "itemData": {"id": 100000006, "dream": false}, "kitNumber": 4}, {"index": 2, "itemData": {"id": 100000005, "dream": false}, "kitNumber": 3}, {"index": 3, "itemData": {"id": 100000008, "dream": false}, "kitNumber": 6}, {"index": 4, "itemData": {"id": 100000007, "dream": false}, "kitNumber": 5}, {"index": 5, "itemData": {"id": 100000002, "dream": false}, "kitNumber": 9}, {"index": 6, "itemData": {"id": 100000004, "dream": false}, "kitNumber": 2}, {"index": 7, "itemData": {"id": 100000009, "dream": false}, "kitNumber": 7}, {"index": 8, "itemData": {"id": 100000010, "dream": false}, "kitNumber": 10}, {"index": 9, "itemData": {"id": 100000025, "dream": false}, "kitNumber": 11}, {"index": 10, "itemData": {"id": 100000001, "dream": false}, "kitNumber": 8}, {"index": 11, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 12, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 13, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 14, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 15, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 16, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 17, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 18, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 19, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 20, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 21, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 22, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}], "captain": 100000001, "kicktakers": [{"index": 0, "id": 100000001, "dream": false}, {"index": 1, "id": 100000001, "dream": false}, {"index": 2, "id": 100000001, "dream": false}, {"index": 3, "id": 100000001, "dream": false}, {"index": 4, "id": 100000001, "dream": false}]}
@@ -0,0 +1 @@
{"id":0,"custom":"[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,50,0,50,40,65,0,65,50,50,1]","squadName":"OpenFUT","chemistry":52,"starRating":90,"rating":90,"formation":"f442","squadType":"REGULAR_SQUAD","manager":[{"id":100000427,"dream":false}],"players":[{"index":0,"itemData":{"id":100000003,"dream":false},"kitNumber":1},{"index":1,"itemData":{"id":100000010,"dream":false},"kitNumber":10},{"index":2,"itemData":{"id":100000005,"dream":false},"kitNumber":3},{"index":3,"itemData":{"id":100000008,"dream":false},"kitNumber":6},{"index":4,"itemData":{"id":100000007,"dream":false},"kitNumber":5},{"index":5,"itemData":{"id":100000006,"dream":false},"kitNumber":4},{"index":6,"itemData":{"id":100000004,"dream":false},"kitNumber":2},{"index":7,"itemData":{"id":100000009,"dream":false},"kitNumber":7},{"index":8,"itemData":{"id":100000001,"dream":false},"kitNumber":8},{"index":9,"itemData":{"id":100000002,"dream":false},"kitNumber":9},{"index":10,"itemData":{"id":100000025,"dream":false},"kitNumber":11},{"index":11,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":12,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":13,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":14,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":15,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":16,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":17,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":18,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":19,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":20,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":21,"itemData":{"id":0,"dream":false},"kitNumber":0},{"index":22,"itemData":{"id":0,"dream":false},"kitNumber":0}],"captain":100000001,"kicktakers":[{"index":0,"id":100000001,"dream":false},{"index":1,"id":100000001,"dream":false},{"index":2,"id":100000001,"dream":false},{"index":3,"id":100000001,"dream":false},{"index":4,"id":100000001,"dream":false}]}
@@ -0,0 +1 @@
{"id": 0, "custom": "[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,50,0,50,40,65,0,65,50,50,1]", "squadName": "OpenFUT", "chemistry": 58, "starRating": 90, "rating": 90, "formation": "f442", "squadType": "REGULAR_SQUAD", "manager": [{"id": 100000427, "dream": false}], "players": [{"index": 0, "itemData": {"id": 100000003, "dream": false}, "kitNumber": 1}, {"index": 1, "itemData": {"id": 100000006, "dream": false}, "kitNumber": 4}, {"index": 2, "itemData": {"id": 100000005, "dream": false}, "kitNumber": 3}, {"index": 3, "itemData": {"id": 100000008, "dream": false}, "kitNumber": 6}, {"index": 4, "itemData": {"id": 100000007, "dream": false}, "kitNumber": 5}, {"index": 5, "itemData": {"id": 100000002, "dream": false}, "kitNumber": 9}, {"index": 6, "itemData": {"id": 100000004, "dream": false}, "kitNumber": 2}, {"index": 7, "itemData": {"id": 100000009, "dream": false}, "kitNumber": 7}, {"index": 8, "itemData": {"id": 100000001, "dream": false}, "kitNumber": 8}, {"index": 9, "itemData": {"id": 100000010, "dream": false}, "kitNumber": 10}, {"index": 10, "itemData": {"id": 100000025, "dream": false}, "kitNumber": 11}, {"index": 11, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 12, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 13, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 14, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 15, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 16, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 17, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 18, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 19, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 20, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 21, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}, {"index": 22, "itemData": {"id": 0, "dream": false}, "kitNumber": 0}], "captain": 100000001, "kicktakers": [{"index": 0, "id": 100000001, "dream": false}, {"index": 1, "id": 100000001, "dream": false}, {"index": 2, "id": 100000001, "dream": false}, {"index": 3, "id": 100000001, "dream": false}, {"index": 4, "id": 100000001, "dream": false}]}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,84 @@
{
"routes": {
"accountInfo": {
"body_len": 2,
"fields": {
"keys": []
},
"sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
"status": 200
},
"activeSquad": {
"body_len": 8034,
"fields": {
"formation": "f442",
"id": 0,
"players.count": 23,
"slots": {
"0": 100000003,
"1": 100000006,
"10": 100000010,
"11": 0,
"12": 0,
"13": 0,
"14": 0,
"15": 0,
"16": 0,
"17": 0,
"18": 0,
"19": 0,
"2": 100000005,
"20": 0,
"21": 0,
"22": 0,
"3": 100000008,
"4": 100000007,
"5": 100000002,
"6": 100000004,
"7": 100000009,
"8": 100000001,
"9": 100000025
}
},
"sha256": "07e330ed358fbefe31379cd2462aaac4bdc9c85ee28b7500dd2d963e5ea565bd",
"status": 200
},
"credits": {
"body_len": 148,
"fields": {
"credits": 28112944
},
"sha256": "0a5f3bac80c3a8ee6f088ccf180f5fdcbcbe8a2ef19c7026e4f21876016d7786",
"status": 200
},
"tradePile": {
"body_len": 862,
"fields": {
"auctionInfo.count": 1
},
"sha256": "b42bab98202209bd8309beb0eca73dba471688e69fef3e014b59901fbc21fe04",
"status": 200
},
"unassigned": {
"body_len": 16,
"fields": {
"itemData.count": 0
},
"sha256": "873f8bba8baf9c573fc51b54d100c357b3bf0caeb2ccd104245c295e073cf342",
"status": 200
},
"userMassInfo": {
"body_len": 8929,
"fields": {
"clubAbbr": "OFC",
"clubName": "OpenFUT",
"personaId": 33068179,
"trophies": 0
},
"sha256": "a616aca1742263c47ade9409693e66ec13b50114e608d88bb94141ce80237b66",
"status": 200
}
},
"unix": 1786472465.339646,
"upstream": "127.0.0.1:8099"
}
@@ -0,0 +1,84 @@
{
"routes": {
"accountInfo": {
"body_len": 2,
"fields": {
"keys": []
},
"sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
"status": 200
},
"activeSquad": {
"body_len": 8034,
"fields": {
"formation": "f442",
"id": 0,
"players.count": 23,
"slots": {
"0": 100000003,
"1": 100000010,
"10": 100000001,
"11": 100000002,
"12": 0,
"13": 0,
"14": 0,
"15": 0,
"16": 0,
"17": 0,
"18": 0,
"19": 0,
"2": 100000009,
"20": 0,
"21": 0,
"22": 0,
"3": 100000008,
"4": 100000007,
"5": 100000006,
"6": 100000005,
"7": 100000004,
"8": 100000025,
"9": 0
}
},
"sha256": "768bb0584ad953ac5f088ad029f161d302ee1be3a63826eb186405acaf1b6232",
"status": 200
},
"credits": {
"body_len": 148,
"fields": {
"credits": 28020656
},
"sha256": "8d39fee51c24ddee9f12d98d7833af6cd3d3399a0e7567ab7062945a1180e30f",
"status": 200
},
"tradePile": {
"body_len": 862,
"fields": {
"auctionInfo.count": 1
},
"sha256": "1575046afb8ca60c76de64427ee0c70e1d4ca2da032819a60db95d72d272d11d",
"status": 200
},
"unassigned": {
"body_len": 16,
"fields": {
"itemData.count": 0
},
"sha256": "873f8bba8baf9c573fc51b54d100c357b3bf0caeb2ccd104245c295e073cf342",
"status": 200
},
"userMassInfo": {
"body_len": 8929,
"fields": {
"clubAbbr": "OFC",
"clubName": "OpenFUT",
"personaId": 33068179,
"trophies": 0
},
"sha256": "3d89d0497661fc62f107081208a14c4fa5753ee4e6482eeda825fe4b622f871f",
"status": 200
}
},
"unix": 1786472102.908128,
"upstream": "127.0.0.1:8099"
}
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env bash
# FIFA 17 squad-adapter mutation battery.
#
# Each mutation injects a specific WRONG behaviour into the committed source,
# runs the one test that defends the invariant, and requires that test to FAIL
# (non-zero exit) — i.e. the mutant is killed. The source is reverted via
# `git checkout` after every mutation, so the tree is left untouched.
#
# A mutant that SURVIVES (its guard test still passes) means the invariant is
# not actually defended; the battery then exits non-zero.
#
# Run from the adapter crate root: bash mutation-battery.sh
set -u
cd "$(dirname "$0")"
FUT=src/fut
PASS=0
FAIL=0
declare -a SURVIVORS=()
# mutate <file> <literal-old> <literal-new> (literal, multiline-safe)
mutate() {
OLD="$2" NEW="$3" perl -0777 -pi -e \
's/\Q$ENV{OLD}\E/$ENV{NEW}/g or die "MUTATION PATTERN NOT FOUND in '"$1"'\n"' "$1"
}
# kill <n> <label> <test-filter> <file> <old> <new>
kill_test() {
local n="$1" label="$2" filter="$3" file="$4" old="$5" new="$6"
git checkout -- "$file"
mutate "$file" "$old" "$new" || { echo " [#$n] SETUP ERROR"; FAIL=$((FAIL+1)); SURVIVORS+=("#$n $label (setup)"); return; }
if cargo test --quiet "$filter" >/dev/null 2>&1; then
echo " [#$n] SURVIVED — $label (test '$filter' still passed)"
FAIL=$((FAIL+1)); SURVIVORS+=("#$n $label")
else
echo " [#$n] killed — $label"
PASS=$((PASS+1))
fi
git checkout -- "$file"
}
echo "== FIFA17 squad adapter mutation battery =="
kill_test 1 "kitNumber keyed by slot index, not owned item" \
kit_number_is_keyed_by_owned_item_not_slot "$FUT/squad_ext.rs" \
'(s.owned_card_id.clone(), s.kit_number)' '(s.index.to_string(), s.kit_number)'
kill_test 2 "captain emitted using resourceId (asset), not wire id" \
fresh_projects_full_23_slot_array_with_captain_wire_id "$FUT/squad_projection.rs" \
'captain_wire = id.item_id as i64;' 'captain_wire = id.asset_id as i64;'
kill_test 3 "client chemistry silently reconciled (shadow lost)" \
swap_moves_two_players_with_their_kits_and_round_trips "$FUT/squad_projection.rs" \
'"chemistry": ext.client_reported.chemistry,' '"chemistry": 0,'
kill_test 4 "custom[] regenerated instead of round-tripped verbatim" \
custom_is_preserved_byte_for_byte "$FUT/squad_ext.rs" \
'custom: put.custom.clone(),' 'custom: Some("[]".to_string()),'
kill_test 5 "index derived (zeroed) instead of round-tripped" \
baseline_projects_the_known_squad_round_trip "$FUT/squad.rs" \
'index: p.index,' 'index: 0,'
kill_test 6 "stale extension accepted and projected" \
stale_is_never_applied "$FUT/squad_projection.rs" \
'SquadExtInput::Stale(_) => return Ok(SquadProjection::Stale),' 'SquadExtInput::Stale(ext) => ext,'
kill_test 7 "missing extension fabricates default fields" \
missing_is_explicit_never_fabricated "$FUT/squad_projection.rs" \
'SquadExtInput::Missing => return Ok(SquadProjection::Missing),' \
'SquadExtInput::Missing => return Ok(SquadProjection::Projected(json!({"custom":"[]","manager":[]}))),'
kill_test 8 "shaper fabricates asset id, bypassing real FIFA identity" \
shapes_real_identity_and_reverse_entity_ids "$FUT/item.rs" \
'let asset = id.asset_id;' 'let asset = 0;'
kill_test 9 "duplicate definition collapses owned instances (id=asset)" \
two_owned_copies_of_one_definition_stay_distinct_on_the_wire "$FUT/item.rs" \
'"id": id.item_id,' '"id": id.asset_id,'
kill_test 10 "PUT treated as a partial slot diff (drops slots)" \
full_replacement_carries_every_occupied_slot_no_diff "$FUT/squad.rs" \
'if p.item_data.id == 0 {' 'if p.item_data.id == 0 || p.index > 1 {'
kill_test 11 "FIFA wire item id stored in canonical replacement" \
full_replacement_carries_every_occupied_slot_no_diff "$FUT/squad.rs" \
'ProposedSlot {
owned_card_id,' 'ProposedSlot {
owned_card_id: p.item_data.id.to_string(),'
kill_test 12 "projector rebuilds items independently of shared shaper" \
persisted_read_round_trips_via_reconstructed_canonical_and_extension "$FUT/squad_projection.rs" \
'"itemData": shape_item(item, id, ent),' '"itemData": json!({"id": id.item_id}),'
kill_test 13 "extension schema version ignored on read" \
unknown_schema_version_is_rejected_not_coerced "$FUT/squad_ext.rs" \
'if schema_version != EXT_SCHEMA_VERSION {' 'if false {'
kill_test 14 "player state keyed by CardDefinitionId not OwnedItemId" \
two_owned_copies_of_one_definition_project_as_distinct_players "$FUT/squad_projection.rs" \
'.get(&slot.owned_card_id)' '.get(&item.card_id)'
echo "== mutants killed: $PASS / $((PASS+FAIL)) =="
if [ "$FAIL" -ne 0 ]; then
printf 'SURVIVORS:\n'; printf ' - %s\n' "${SURVIVORS[@]}"
exit 1
fi
echo "all mutants killed"
@@ -0,0 +1,177 @@
//! `Util::fetchClientConfig` tables.
//!
//! Between 227 and 243 key/value rows per CFID, overwhelmingly the same RS4
//! base URL repeated across 212 endpoint keys. The client resolves a per-call
//! key (`FUT_RS4_URL_<CALL>`) before a per-module one
//! (`FUT_RS4_APIURL_<MODULE>`), and any call left unresolved falls back to a
//! real (dead) EA host — which is what produced "there has been an error
//! connecting to FIFA 17 Ultimate Team" mid-session when only the boot subset
//! was served. The table has to be complete, not representative.
//!
//! # Why this is data and not code
//!
//! The rows are reverse-engineered *configuration*, not logic. They live in
//! `fixtures/client_config.json`, derived mechanically from the Python oracle
//! and templated on `{advertise}`, `{bind}`, `{pow_content_host}` and
//! `{pow_host}` so the adapter stays deployable anywhere. Hand-transcribing 400
//! string literals would add a class of silent typo no reviewer can catch, and
//! `openfut-core` already loads its content from `data/` for the same reason.
//!
//! The generator does not take its own templating on trust: it substitutes real
//! addresses back in and diffs against the oracle for every section before
//! writing the file.
use std::collections::BTreeMap;
use std::sync::OnceLock;
use super::config::AdapterConfig;
/// Rows for every known CFID, plus `__default__` for unknown ones.
const TABLE_JSON: &str = include_str!("../../fixtures/client_config.json");
type Table = BTreeMap<String, Vec<(String, String)>>;
fn table() -> &'static Table {
static TABLE: OnceLock<Table> = OnceLock::new();
TABLE.get_or_init(|| {
serde_json::from_str(TABLE_JSON).expect("bundled client_config.json is valid")
})
}
/// Resolve the rows for a CFID, with addresses substituted in.
///
/// Unknown CFIDs deliberately still receive the shared FUT/RS4/POW rows: those
/// consumers read a merged `_all` store and which section contributes is
/// unproven, so a present-but-shared table is safer than an empty one.
pub fn rows_for(cfid: &str, cfg: &AdapterConfig) -> Vec<(String, String)> {
let t = table();
let rows = t
.get(cfid)
.or_else(|| t.get("__default__"))
.expect("client_config.json always carries a __default__ section");
// URL-level tokens resolve through AdapterConfig so those helpers are the
// single place a URL shape is defined. Host-level tokens cover the values
// that are not one of the three standard URLs (roster, POW API).
let utas_base = cfg.utas_base();
let nucleus_base = cfg.nucleus_base();
let pow_content_url = cfg.pow_content_url();
rows.iter()
.map(|(k, v)| {
let v = if v.contains('{') {
v.replace("{utas_base}", &utas_base)
.replace("{nucleus_base}", &nucleus_base)
.replace("{pow_content_url}", &pow_content_url)
.replace("{advertise}", &cfg.endpoints.advertise)
.replace("{bind}", &cfg.endpoints.bind)
.replace("{pow_content_host}", &cfg.endpoints.pow_content_host)
.replace("{pow_host}", &cfg.endpoints.pow_host)
} else {
v.clone()
};
debug_assert!(!v.contains('{'), "unsubstituted token left in {k}: {v}");
(k.clone(), v)
})
.collect()
}
/// Fingerprint of the bundled config table.
///
/// The table is generated data, so "which binary is this?" is only half the
/// question — "which data does it carry?" is the other half. A running host
/// logs this at startup so a live FIFA trace can be tied to an exact table, and
/// a rebuild that silently picked up regenerated fixtures is visible.
///
/// FNV-1a, not a security hash and never used as one.
pub fn table_fingerprint() -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in TABLE_JSON.as_bytes() {
hash ^= *byte as u64;
hash = hash.wrapping_mul(0x1000_0000_01b3);
}
hash
}
/// Every CFID with its own section. Unknown CFIDs are still valid requests.
pub fn known_sections() -> Vec<&'static str> {
table()
.keys()
.filter(|k| k.as_str() != "__default__")
.map(String::as_str)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn cfg() -> AdapterConfig {
let mut c = AdapterConfig::loopback();
c.endpoints.advertise = "198.51.100.7".into();
c.endpoints.bind = "0.0.0.0".into();
c.endpoints.pow_content_host = "198.51.100.7:8085".into();
c.endpoints.pow_host = "198.51.100.7:8094".into();
c
}
#[test]
fn bundled_table_parses() {
assert!(table().contains_key("__default__"));
assert!(table().contains_key("BlazeSDK"));
assert!(known_sections().len() >= 10);
}
#[test]
fn default_section_is_the_shared_fut_base() {
let rows = rows_for("literally-anything", &cfg());
assert_eq!(rows.len(), 227);
assert!(rows.iter().any(|(k, _)| k == "FUT_RS4_BASE_URL"));
}
#[test]
fn addresses_are_substituted_not_baked() {
let rows = rows_for("BlazeSDK", &cfg());
let base = rows
.iter()
.find(|(k, _)| k == "FUT_RS4_BASE_URL")
.expect("base url present");
assert_eq!(base.1, "http://198.51.100.7:8099/");
assert!(
!rows.iter().any(|(_, v)| v.contains('{')),
"a template token survived substitution"
);
}
#[test]
fn nucleus_follows_bind_reproducing_the_oracle() {
let rows = rows_for("BlazeSDK", &cfg());
let n = rows.iter().find(|(k, _)| k == "nucleusConnect").unwrap();
assert_eq!(n.1, "http://0.0.0.0:42131");
}
#[test]
fn roster_section_carries_the_roster_urls() {
let rows = rows_for("OSDK_ROSTER", &cfg());
let r = rows.iter().find(|(k, _)| k == "ROSTER_URL").unwrap();
assert_eq!(r.1, "https://198.51.100.7:8081/fifa17/roster/");
}
#[test]
fn rows_are_sorted_as_the_wire_requires() {
// The oracle sorts; the TDF map encoder does not, so order is ours to keep.
let rows = rows_for("BlazeSDK", &cfg());
let mut sorted = rows.clone();
sorted.sort();
assert_eq!(rows, sorted);
}
#[test]
fn every_known_section_substitutes_cleanly() {
for cfid in known_sections() {
for (k, v) in rows_for(cfid, &cfg()) {
assert!(!v.contains('{'), "{cfid}/{k} kept a token: {v}");
}
}
}
}
+230
View File
@@ -0,0 +1,230 @@
//! Adapter configuration: identity and endpoints.
//!
//! Everything deployment-dependent lives here, injected by the caller. No
//! address, port or persona is baked into the response builders — the
//! client/server split exists precisely because the Python responders used to
//! assume loopback, and rebuilding that assumption in Rust would undo it.
//!
//! Note the deliberate asymmetry between *bind* and *advertise*: an advertised
//! URL must carry the address the CLIENT can reach, which on a two-machine
//! deployment is not the address the server binds.
/// The forged account the whole stack agrees on.
///
/// Identity has to be byte-identical across LSX, Blaze, POW and UTAS or the
/// client rejects the session, so this is one struct passed everywhere rather
/// than constants per responder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
pub persona_id: i64,
pub persona_name: String,
/// blazeId / userId. Must be non-zero or login is refused.
pub user_id: i64,
/// XREF externalId.
pub ext_id: i64,
pub email: String,
/// Must equal `PreAuthResponse.NASP`.
pub namespace: String,
/// `Blaze::ClientPlatformType`; 4 = pc.
pub client_platform: i64,
/// `PersonaStatus::Code`; 2 = ACTIVE.
pub persona_status: i64,
/// `Blaze::UserSessionType`; 0 = normal user.
pub user_session_type: i64,
/// Fallback locale as a packed four-char int (`'enUS'`). Overwritten per
/// session by the client's own preAuth `LANG`/`LOC`.
pub account_locale: i64,
/// `AccountInfo.LN`, e.g. `"en_US"`.
pub locale: String,
/// EA offer id.
pub content_id: String,
pub entitlement_tag: String,
/// Must contain `"FIFA17PCBoxContent"` or `"FIFA16PC"` or FUT drops the
/// entitlement and the store comes up empty.
pub entitlement_group: String,
pub title_id: String,
pub client_id: String,
pub platform: String,
}
impl Default for Identity {
/// The project's fixed synthetic offline identity.
///
/// A default, not a constant: the launcher can select a different persona,
/// and FUT saves are isolated per persona id.
fn default() -> Identity {
Identity {
persona_id: 33_068_179,
persona_name: "CAGE".into(),
user_id: 33_068_179,
ext_id: 33_068_179,
email: "cage@openfut.local".into(),
namespace: "cem_ea_id".into(),
client_platform: 4,
persona_status: 2,
user_session_type: 0,
account_locale: 0x656E_5553, // 'enUS'
locale: "en_US".into(),
content_id: "1027460".into(),
entitlement_tag: "ONLINE_ACCESS".into(),
entitlement_group: "FIFA17PCBoxContent".into(),
title_id: "309111".into(),
client_id: "FIFA17-PC-SERVER-BLAZE".into(),
platform: "pc".into(),
}
}
}
/// Where the client should be told to go next.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoints {
/// Address handed to the CLIENT for every next hop. On a split deployment
/// this is the backend's LAN address as the game machine sees it.
pub advertise: String,
/// Address the server binds. Not interchangeable with `advertise`.
pub bind: String,
/// `host:port` for POW content.
pub pow_content_host: String,
/// `host:port` for the POW/EASFC API.
pub pow_host: String,
/// Blaze port ADVERTISED to the client by the redirector.
///
/// Our choice, not a protocol constant — the client goes wherever
/// `<serverinstanceinfo>` sends it. Configurable so a sidecar can be
/// advertised on a different port without a rebuild.
pub blaze_port: u16,
/// UTAS/RS4 port in generated `FUT_RS4_*` URLs.
///
/// 8099 is the client's own built-in default (`http://easw.easports.com:8099/`
/// in CardsDLL), so it is the sane value — but it is still deployment
/// configuration, not a constant we are entitled to bake in.
pub utas_port: u16,
pub telemetry_port: i64,
pub ticker_port: i64,
pub qos_port: i64,
}
// NOTE: there is deliberately NO `impl Default for Endpoints`.
//
// A default would silently supply loopback, and a remote deployment that forgot
// to set an address would then advertise `127.0.0.1` to a client on another
// machine — failing far from the cause. Choosing loopback has to be an explicit
// act, so it is a named constructor.
impl Endpoints {
/// Endpoints for a backend the client reaches at `advertise`.
///
/// POW hosts DERIVE from the advertised host, matching what the deployed
/// Python entrypoint does (`POW_HOST="${POW_HOST:-$ADV:8094}"`). They must
/// not fall back to loopback independently: that would leave a remote
/// deployment emitting loopback POW URLs while every other URL was correct.
pub fn advertising(advertise: impl Into<String>) -> Endpoints {
let advertise = advertise.into();
Endpoints {
pow_content_host: format!("{advertise}:8080"),
pow_host: format!("{advertise}:8094"),
bind: advertise.clone(),
advertise,
blaze_port: 42130,
utas_port: 8099,
telemetry_port: 9988,
ticker_port: 8999,
qos_port: 17502,
}
}
/// Explicit local-only / oracle mode: game and backend on one host.
///
/// Named rather than defaulted so that "everything is loopback" is always a
/// decision someone made, and greppable.
pub fn loopback() -> Endpoints {
Endpoints::advertising("127.0.0.1")
}
}
/// Full adapter configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdapterConfig {
pub identity: Identity,
pub endpoints: Endpoints,
/// `PreAuthResponse.SVER`. Carries a trailing newline in the oracle; kept
/// because it is on the wire, not because it is meaningful.
pub server_version: String,
}
/// `PreAuthResponse.SVER`. On the wire, so it is config rather than a literal.
pub const DEFAULT_SERVER_VERSION: &str = "Blaze 15.1.1.3.0 (OpenFUT)\n";
// No `Default` here either, for the same reason as `Endpoints`.
impl AdapterConfig {
/// Adapter serving a client that reaches this backend at `advertise`.
pub fn advertising(advertise: impl Into<String>) -> AdapterConfig {
AdapterConfig {
identity: Identity::default(),
endpoints: Endpoints::advertising(advertise),
server_version: DEFAULT_SERVER_VERSION.into(),
}
}
/// Explicit local-only / oracle mode.
pub fn loopback() -> AdapterConfig {
AdapterConfig::advertising("127.0.0.1")
}
/// `http://<advertise>:8099/` — the RS4/UTAS base.
///
/// The trailing slash and the scheme are both mandatory: CardsDLL's
/// `ServerSettings::resolve` uses the value verbatim once it contains
/// `"://"`, and the auth path breaks without the slash.
pub fn utas_base(&self) -> String {
format!(
"http://{}:{}/",
self.endpoints.advertise, self.endpoints.utas_port
)
}
/// `http://<bind>:42131` — the Nucleus OAuth stub.
///
/// This derives from **bind**, not advertise, faithfully reproducing the
/// Python oracle. On the live split deployment that makes it
/// `http://0.0.0.0:42131`, which the client cannot dial — see the crate
/// README and the vault. Reproduced deliberately: changing it would break
/// byte parity with the only configuration ever proven to work, and the
/// fix belongs in a separate, live-validated change.
pub fn nucleus_base(&self) -> String {
format!("http://{}:42131", self.endpoints.bind)
}
pub fn pow_content_url(&self) -> String {
format!("http://{}", self.endpoints.pow_content_host)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utas_base_keeps_scheme_and_trailing_slash() {
let mut cfg = AdapterConfig::loopback();
cfg.endpoints.advertise = "10.0.0.5".into();
assert_eq!(cfg.utas_base(), "http://10.0.0.5:8099/");
}
#[test]
fn nucleus_follows_bind_not_advertise() {
// Documents the oracle's behaviour, including its consequence.
let mut cfg = AdapterConfig::loopback();
cfg.endpoints.advertise = "10.0.0.5".into();
cfg.endpoints.bind = "0.0.0.0".into();
assert_eq!(cfg.nucleus_base(), "http://0.0.0.0:42131");
}
#[test]
fn pow_content_url_has_no_trailing_slash() {
let mut cfg = AdapterConfig::loopback();
cfg.endpoints.pow_content_host = "10.0.0.5:8085".into();
assert_eq!(cfg.pow_content_url(), "http://10.0.0.5:8085");
}
}

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