@sizls/minglingo-verify
v0.4.0
Published
Verify any Minglingo game or streak Save-Receipt happened as claimed. Deterministic-replay CLI + library over the public verify-artifact endpoints — engine-agnostic (bingo, trivia, prediction, competition, plus future plugin games) with a `streak` subcomm
Maintainers
Readme
@sizls/minglingo-verify — prove a Minglingo game (or streak Save-Receipt) happened
Deterministic-replay CLI + library for any game hosted on Minglingo, plus a streak subcommand for verifying paid Save-Receipts. One command, no build step, no server trust, prints a provably-fair receipt in your terminal:
npx @sizls/minglingo-verify <gameId> # legacy — game verb
npx @sizls/minglingo-verify game <gameId> # explicit game verb
npx @sizls/minglingo-verify streak <receiptId> # streak Save-Receipt✓ provably fair stream-trivia · trivia
────────────────────────────────────────
game game-abc-123
status completed
completed 2026-06-01T00:05:00.000Z
sessions 1
events 47 (2 retractions)
final prompts 45
server hash 0f8a1b3c9d4e…
local hash 0f8a1b3c9d4e… ✓Exit code 0 means the local replay hash matched the server's canonical hash. Exit code 1 means it didn't — the log was tampered with or the CLI is out of date.
Engine-agnostic by design
Minglingo hosts many game types on one runtime — traditional bingo (75-ball, 90-ball), social bingo variants (custom, speed, battle-royale, team-wars, tournament), stream-trivia, quiz-show, crowd-predictor, and any future third-party plugin game shipped through Phase E. This CLI verifies all of them from the same command.
Every game records its state changes as engine-agnostic Kite events (call.issued + call.retracted), and the retraction-aware projection is shared across engines. Bingo tracks callValue, trivia tracks questionId, prediction tracks predictionId — the CLI reads the engineKind off the artifact and replays through the same code path either way. New engines added by plugins verify with the same CLI on day one.
Plugin authors publishing a new engine kind (Phase E) SHOULD namespace it under their plugin id (e.g. chess:v1) to avoid collisions with first-party engines. @minglingo/game-events exports FIRST_PARTY_ENGINE_KINDS as an enumerable reference of the first-party engines.
Why it exists
Every social-gaming app on the market makes a "provably fair" claim ("we don't rig outcomes, wins are legitimate"). None of them let you check. You take their word or you don't.
Minglingo's game state is a pure function of an append-only event log. Given the same events + the same projection, any consumer computes byte-identical final state — there's nothing hidden in a database that changes the outcome. This CLI runs that math on your machine so you don't have to trust the server for the fair-play claim.
Install
You don't. Use it with npx:
npx @sizls/minglingo-verify <gameId>Or drop it in your CI so every closed game auto-verifies:
- name: Prove last night's game
run: npx @sizls/minglingo-verify ${{ vars.LAST_NIGHT_GAME_ID }}Flags
--host <url> Verify against a custom host (default: https://minglingo-web.sizls.workers.dev,
overridable via the MINGLINGO_VERIFY_HOST env var)
--json Emit the full receipt as JSON (colour-free, machine-readable)
On failure paths, `--json` also emits a structured `{ error: … }`
body to stdout so pipelines can jq the error without regexing stderr.
--quiet Suppress output; exit 0 on pass, 1 on fail
--version, -V Print the CLI version and exit
--help, -h Show usageEnvironment variables
MINGLINGO_VERIFY_HOST— sets the default host without needing--hoston every invocation. Useful when a third-party consumer mirrors the verify-artifact endpoint on a domain they own (e.g.verify.acme-arcade.com) and doesn't want to hard-code the Sizls-internalsizls.workers.devsubdomain.--hoststill overrides the env var when set.
Exit codes
| Code | Meaning |
|-----:|---------|
| 0 | provably fair (byte-identical replay + server hash match) |
| 1 | verification failed (see --json .failures for the list) |
| 2 | fetch failed (network, timeout, 4xx/5xx) |
| 64 | usage error |
| 70 | internal error (bug in the CLI — please file an issue) |
Library usage
The CLI is a thin wrapper over the exported library. Same primitives are available programmatically for any consumer — a leaderboard aggregator, a support-desk auto-responder, an EU AI Act audit pipeline:
import { fetchAndVerify, verifyArtifact } from '@sizls/minglingo-verify';
const { artifact, receipt } = await fetchAndVerify('game-abc-123');
if (!receipt.provablyFair) {
throw new Error(`verification failed: ${JSON.stringify(receipt.failures)}`);
}
console.log(
`✓ ${artifact.gameId} — ${artifact.gameTypeId} (${artifact.engineKind}), ` +
`${receipt.reconstructedPromptCount} prompts, ${receipt.retractionCount} retractions`,
);verifyArtifact(artifact) takes an artifact you already have in hand (from a signed export, a local file, a paste from a Slack thread) and returns the same receipt shape — useful for offline audits.
Wire format
GET https://minglingo-web.sizls.workers.dev/api/games/<id>/verify-artifact returns:
{
"schemaVersion": 1,
"gameId": "game-abc-123",
"gameTypeId": "stream-trivia", // any Minglingo game type
"engineKind": "trivia", // engine that projects the events
"status": "completed",
"completedAt": "2026-06-01T00:05:00Z",
"sessionCount": 1,
"truncated": true, // OPTIONAL: only present when the game's event
// log exceeded the server-side row cap (25,000
// events). Consumers rendering "this artifact
// is complete" should treat `truncated: true`
// as "the receipt covers the first N events;
// the game continues past what's included."
// Hashed into the artifact only when strictly
// `true`, so pre-cap games produce identical
// hashes to games that would have been fine
// without a cap.
"events": [
{ "seq": 1, "sessionNumber": 1, "kind": "call.issued", "key": "q_47", "at": "..." },
{ "seq": 2, "sessionNumber": 1, "kind": "call.issued", "key": "q_48", "at": "..." },
...
],
"hash": "sha256:0f8a1b3c9d4e..."
}Every response (success + 404 + 429 + 5xx) also carries an x-request-id header — a crypto.randomUUID()-generated correlation handle. Include it in any support-flow issue ("hash mismatch on <id>, x-request-id <uuid>") so server-side logs can be joined against the wire response.
The endpoint is:
- Public for completed non-private games across every engine. No auth.
- Rate limited at 60 req/min per IP (Cloudflare Durable-Object-backed).
- Edge-cached for 5-10 minutes — a completed game's artifact never changes, so a press-driven verify spike hits the edge cache and pays for itself.
- Never available for private or in-flight games (returns 404 — deliberate, so endpoint existence doesn't leak game state).
- Row-capped at 25,000 events per artifact; the response ships
truncated: truewhen a game exceeded the cap. The 10 MiB CLI body ceiling comfortably exceeds a 25k-row artifact today (~5 MiB) — if a future engine emits larger per-event payloads the two caps should be revisited together.
404 subcodes
Every 404 body carries a stable error.subcode so callers can distinguish "in progress" from "not found" without regexing the human-readable message. Info-leak parity is deliberate: private / password games reuse game_not_found so an unauthenticated caller can't distinguish "non-public" from "unknown id" via the response body.
// GET /api/games/<id>/verify-artifact → 404
{
"error": {
"code": "NOT_FOUND",
"message": "Game not yet completed",
"subcode": "game_in_progress" // or "game_not_found"
}
}| subcode | Meaning | CLI render |
|---------------------|--------------------------------------------------------------------------------------------|-------------------------------------------------------------------|
| game_in_progress | The game exists + is public but hasn't reached a terminal state yet. | game in progress: try again after the game finishes |
| game_not_found | The game id doesn't exist, or it does but isn't public (private / password visibility). | game not found: no public verification receipt for this id |
Library callers get the same information as VerifyFetchError.subcode on the thrown error; unknown / missing subcodes fall back to a plain "not found" render so a newer server can add branches without breaking older CLI releases.
Reproducing the hash in another language
The wire hash is deterministic and portable — nothing about it needs Node. Any language with a JSON encoder + SHA-256 primitive can recompute it. The canonicalisation rules are:
- Build the artifact object with a fixed top-level field order:
schemaVersion,gameId,gameTypeId,engineKind,status,completedAt,sessionCount, thentruncated(only iftrue— otherwise omit the key entirely), thenevents. - Sort each event's
recordkeys alphabetically (event-level fields —seq,sessionNumber,kind,key,record,at— stay in that fixed order; only the nestedrecordobject is key-sorted). JSON.stringifywith no whitespace, no replacer. The wire is byte-exact — a stray space anywhere changes the hash.- SHA-256 hex over the UTF-8 bytes, prefixed
sha256:.
Reference implementation in Python (10 lines):
import hashlib, json
def compute_hash(artifact: dict) -> str:
canonical = {k: artifact[k] for k in (
"schemaVersion", "gameId", "gameTypeId", "engineKind",
"status", "completedAt", "sessionCount",
)}
if artifact.get("truncated") is True:
canonical["truncated"] = True
canonical["events"] = [
{
"seq": e["seq"], "sessionNumber": e["sessionNumber"], "kind": e["kind"], "key": e["key"],
"record": dict(sorted(e["record"].items())) if e.get("record") else None,
"at": e["at"],
}
for e in artifact["events"]
]
body = json.dumps(canonical, separators=(",", ":"), ensure_ascii=False)
return "sha256:" + hashlib.sha256(body.encode("utf-8")).hexdigest()The source of truth is canonicalise in src/index.ts — that function's output is what the server hashes and what the wire delivers. If a downstream port disagrees, the Node canonicaliser wins by definition.
Streak receipts
Alongside the game verb, the CLI verifies streak Save-Receipts — the paid-flex artifact minted when a user consumes a Streak Shield to save a login streak, or pays for a Streak Repair to restore a broken one:
npx @sizls/minglingo-verify streak <receiptId>✓ verified: Alice saved a 21-day login streak on 2026-07-17 (kind: shield_save)
────────────────────────────────────────
receipt ck1abcdefghijklmnop
user Alice
kind shield_save
streak 20 → 21
saved at 2026-07-17T05:57:00.000Z
day 2026-07-17
shield shield-abc-123
server hash 0f8a1b3c9d4e…
local hash 0f8a1b3c9d4e… ✓
signature 4b2c9e1a7f3d… ✓ (shape only — full sig verification lands with Kite JWKS)Exit code 0 means the reproduced hash matched the server's canonical hash AND the signature is well-formed. Exit code 1 means one of them failed — the payload was tampered with, the sig is malformed, or the CLI is out of date.
Wire format
GET https://minglingo-web.sizls.workers.dev/api/streaks/receipts/<receiptId>/verify-artifact returns:
{
"schemaVersion": 2,
"receiptId": "ck1abcdefghijklmnop",
"displayName": "Alice",
"kind": "shield_save", // or "repair"
"priorStreak": 20,
"postStreak": 21,
"savedAt": "2026-07-17T05:57:00.000Z",
"dayKey": "2026-07-17", // calendar day in the user's persisted tz
"shieldId": "shield-abc-123", // null on `repair`
"hash": "sha256:0f8a1b3c9d4e...",
"sig": "hmac-sha256:4b2c9e1a7f3d..."
}schemaVersion: 2 carries no userId: the endpoint is public, and the internal user id is not something a share link should publish. displayName is the only person-identifying field. (schemaVersion: 1 receipts, minted before 2026-11-05, had a userId between receiptId and displayName; this package still verifies them, but the server no longer serves them. CLI releases before 0.4.0 only understand v1 and report unknown_schema for v2.)
dayKeyTz (the persisted IANA zone) is deliberately not on the wire — shipping it would leak the user's approximate location. dayKey alone is enough for the flex UI.
Failure modes
| kind | Meaning | CLI render |
|--------------------|-----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|
| valid | Reproduced hash matched; signature shape is valid. | green ✓ verified: … |
| hash_mismatch | The server's hash did not match the hash the CLI computed from the payload. | red server hash did not match reproduced hash |
| malformed_sig | The sig didn't match hmac-sha256:<64-hex> — transport-integrity gate. | red signature shape is invalid |
| unknown_schema | schemaVersion is not 1 or 2 — newer server than this CLI knows about. | yellow receipt uses a newer schema than this CLI supports; upgrade with npm i -g …@latest |
Fetch failures (404 for a missing receipt, 503 for a temporarily-unconfigured signing key, network / timeout) exit 2 with a subcode-differentiated message. Fetch failures under --json emit a structured { error: … } body to stdout.
Reproducing the receipt hash in another language
The wire hash is deterministic and portable — nothing about it needs Node. Any language with a JSON encoder + SHA-256 primitive can recompute it. The canonicalisation rules are:
- Build the canonical object with a fixed top-level field order:
schemaVersion,receiptId,displayName,kind,priorStreak,postStreak,savedAt,dayKey,shieldId(v2). A v1 receipt additionally hasuserIdbetweenreceiptIdanddisplayName. All fields are always present (no additive-optional keys yet). JSON.stringifywith no whitespace, no replacer. Byte-exact wire — a stray space anywhere changes the hash.- SHA-256 hex over the UTF-8 bytes, prefixed
sha256:.
Reference implementation in Python (10 lines):
import hashlib, json
def compute_receipt_hash(receipt: dict) -> str:
# v2 field list; for a v1 receipt insert "userId" after "receiptId".
canonical = {k: receipt[k] for k in (
"schemaVersion", "receiptId", "displayName", "kind",
"priorStreak", "postStreak", "savedAt", "dayKey", "shieldId",
)}
body = json.dumps(canonical, separators=(",", ":"), ensure_ascii=False)
return "sha256:" + hashlib.sha256(body.encode("utf-8")).hexdigest()The source of truth is canonicaliseReceipt in src/index.ts. If a downstream port disagrees, the Node canonicaliser wins by definition.
What the streak verifier does NOT check (yet)
The CLI cannot verify the sig cryptographically — that requires the server's STREAK_RECEIPT_SIGNING_KEY. What it CAN prove: the server's published hash is exactly the hash of the canonical payload the server also published. The sig is treated as a transport-integrity marker (structural shape validation only).
Full sig verification lands with the Kite Ed25519 dual-key rollout: at that point a --verify-signature flag reads the server's public key from ${host}/.well-known/minglingo-verify/jwks.json and verifies the sig end-to-end. schemaVersion gates the compat.
What "provably fair" means today
The CLI verifies:
- Deterministic replay — every recorded call/retraction, run through the same LIFO-per-session projection the server ran, reconstructs the authoritative prompt list. Same output for the same input, no engine-specific hidden branches.
- Content hash match — the SHA-256 of the canonical wire form matches the server's published hash. The server + the CLI observed the same event stream.
The CLI does NOT verify:
- Origin authenticity (yet). A dishonest server could serve a manufactured event sequence that hashes cleanly. Closing this needs Ed25519 signed exports + a public JWKS endpoint — that lands with the Kite plugin runtime (Phase E). Once available,
@sizls/minglingo-verifygains a--verify-signatureflag that checks the signature against the published key. TheschemaVersionfield on the wire gates the compat — older CLI releases will keep working against pre-signature artifacts.
Today's claim: any two observers running this CLI on the same game id, of any engine, see the same result byte-for-byte. That's the strongest determinism guarantee the current surface exposes.
Digests that do not reproduce (2026-09-20)
engineKind is a preimage field, and until 2026-09-20 the server computed it from a mapping
that had been written with hyphens (stream-trivia) while every game-type id is snake_case
(stream_trivia). No non-bingo branch could match, so each one fell through to a fallback
that published the raw game-type id — a label no engine answers to, and not the one this
README documents.
Correcting it changes the published digest for four game types:
| game type | engineKind before | after |
|--------------------|---------------------|--------------|
| stream_trivia | stream_trivia | trivia |
| quiz_show | quiz_show | trivia |
| crowd_predictor | crowd_predictor | prediction |
| sports_predictor | sports_predictor | prediction |
If you pinned a hash for a game of one of those four types before 2026-09-20, it will not reproduce. Re-fetch the artifact and re-pin. Every bingo type — which is most games — is unaffected: those digests are byte-identical across the change.
This deliberately did not ship as schemaVersion: 2. A bump would make every older CLI
return unknown_schema for every game of every type, including the bingo games whose digest
never moved, and it would not make a single affected artifact reproduce — the old digest was
computed over a wrong value, not a different format. The reasoning is recorded in full in
docs/technical/verify-artifact-engine-kind-2026-09-20.md.
From this release the mapping is a frozen, append-only table guarded by a test, and settlement
records the engineKind and completedAt it published so the endpoint serves them back
rather than re-deriving them. A digest published after this date is a record of what happened,
not a function of the code currently deployed.
Releasing (maintainers)
src/publishedGuard.test.ts fails CI if canonicalise() changes while package.json is not
above the version recorded in PUBLISHED_VERSION.json. That file records what is actually on
npm, so it only changes after a publish:
- Bump
versioninpackage.json(minor when the verifiable surface grows). - Merge, then from
packages/minglingo-verifyrunnpm publish(prepublishOnlybuilds). - Set
PUBLISHED_VERSION.jsonto the new version and the current source's fingerprint, and commit. The guard prints the fingerprint in its failure message; to read it once the bump has made the guard pass, setversionback temporarily and run the test. (0.4.0's iseedc161a08927c4b7aea4d86f5c68b0667ed7342b63f9ac1dbc534a66648ff7c.)
The fingerprint covers canonicalise() and its helpers only. A change to computeHash or the
digest prefix is caught by the golden hash vectors in the same test file, not the fingerprint.
Backward-compatibility
schemaVersion: 1 is the current wire shape. Additive changes stay under schemaVersion: 1; anything that reorders fields or changes hash semantics ships as schemaVersion: 2. Old CLI releases against a schemaVersion: 2 artifact return provablyFair: false with { kind: 'unknown_schema' } — never a silent success. Users upgrading get the new checks for free (npx always pulls latest).
Self-hosted deployments
--host <url> verifies against any host running the same wire endpoint. Useful for:
- Self-hosted Minglingo instances (venue partners running the platform on their own Cloudflare account)
- Staging / preview URLs during CI
- Air-gapped verification against a saved artifact (drop into a script that reads from disk via the library rather than the CLI)
Contributing
Lives in the sizls/minglingo monorepo under packages/minglingo-verify. PRs welcome — the interesting tests are in src/verifier.test.ts (unit, engine-agnostic).
License
MIT.
