Metadata-Version: 2.4
Name: pansofica-flag
Version: 0.1.0
Summary: Read, verify and render the record status flag: verify a signed record-status link offline, look a status up by slug, render the badge and the words.
Author: PXL8 Technology, Inc.
License-Expression: Apache-2.0
Project-URL: Homepage, https://pansofica.com/developers
Project-URL: Vocabulary, https://pansofica.com/vocabulary/record-status
Keywords: record status,provenance,verification,ed25519,jws,badge
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: cryptography>=41
Dynamic: license-file

# pansofica-flag

Read, verify and render the **record status flag** — the one word a record
carries about how far it can be trusted:

| status | the words |
|---|---|
| `verified` | Verified from the commission's document |
| `reported` | Reported on the open web |
| `subject_confirmed` | Confirmed by the athlete |
| `subject_corrected` | Corrected at the athlete's request |
| `disputed` | Disputed |

The vocabulary is open: <https://pansofica.com/vocabulary/record-status>.
There is one issuer. Verification costs nothing and needs no account.

Python 3.9 or later. The standard library plus
[`cryptography`](https://pypi.org/project/cryptography/) (for Ed25519) — nothing
else. Fully type-hinted (`py.typed`). Apache-2.0.

```bash
pip install pansofica-flag
```

## What this kit is — and is not

It **reads** and **verifies** the flag, and renders it. It contains **no
decision logic**: no matching, no scoring, no picking among candidates, no rule
for who a person is. It never derives a status; it only carries the one the
issuer derived. Turning a *name* into a record is not this kit's job — you look
a record up by its **slug** (the last part of its page address), which you
store once.

## Carry the flag honestly

- **Never hide a disputed fact. Never drop the row.** Show the record AND the word.
- There is no option anywhere in this kit to hide, soften, recolour away or
  skip `disputed`. `render_badge("disputed")` is the same typeset badge as
  every other status.
- The words come from the kit's closed table, looked up by `status`. A `label`
  string from the wire is never trusted and never typeset.
- A signed link says what the status **was** when it was signed. Only a lookup
  (or the hosted badge) says what it **is**. When you print a status that came
  from a link, say so: `status_line(flag, when_signed=...)`.

## 1. Verify a link offline — `verify_flag`

A record-status link is a compact signed statement (Ed25519). Verifying it
needs the issuer's public keys and nothing else: no call, no account.

```python
from pansofica_flag import fetch_keys, status_line, verify_flag

keys = fetch_keys()            # one GET, remembered for an hour — or pin the keys and skip it
result = verify_flag(link, keys, expect={"slug": "fixture-alpha"})

if result.valid:
    flag = result.flag_when_signed
    print(status_line(flag, when_signed=result.issued_at))
    # Verified from the commission's document (when signed, 2027-01-15)
elif result.expired:
    print("link expired; it said:", result.claims.status)
else:
    print("not valid:", result.reason)
```

`verify_flag(link, keys, *, now=None, expect=None) -> VerifyResult` **never
raises on a bad link**. It answers:

| member | |
|---|---|
| `valid` | `True` only for a link the issuer signed, whole, and not expired |
| `expired` | `True` when the issuer signed it and its time has passed — `claims` are still answered |
| `reason` | `None` when valid; else `malformed` · `unsupported_alg` · `unknown_key` · `bad_signature` · `bad_claims` · `expired` · `subject_mismatch` (decided in that order). `VERIFY_REASONS` also lists `unsupported_runtime` last, for parity with the TypeScript package; this package never answers it (`can_verify()` is always `True`) |
| `claims` | `iss, sub, slug, status, last_reviewed, doc, iat, exp` (`doc` is the document's sha256 hex or `None`) |
| `flag_when_signed` | `status, words, last_reviewed, document_sha256` — valid links only |
| `issued_at`, `expires_at` | aware `datetime`s (UTC) — valid links only; `None` for an instant no `datetime` can hold (never an exception) |

- `keys` is a `KeySet`, the JSON object the key address answers, or a list of
  JWKs. The key is chosen by the link's `kid` — **never by position**. **Never
  verify against `pem`**: it is the *current* signing key only, and a link
  signed under an older listed key does not verify against it. The kit never
  reads it. A JWK is used only when it is `kty: OKP`, `crv: Ed25519`, a canonical
  32-byte `x` and a non-empty string `kid` — and, when it carries them, `use`
  is exactly `sig` and `alg` exactly `EdDSA`. Anything else is skipped.
- `now` is the verifier's clock: a `datetime` (a naive one is read as UTC) or
  seconds since the epoch; the wall clock when omitted. A link is expired **at**
  `exp`, with no leeway. A clock that is not a time fails closed.
- `expect={"slug": ...}` and/or `{"sub": ...}` is the subject *you* believe the
  link is about. A well-signed link about anybody else is refused as
  `subject_mismatch` — use it whenever a link arrives next to a row. An
  `expect` that is not exactly that (another member, a value that is not a
  string, not a mapping) is a mismatch too: it fails closed. So is an EMPTY
  mapping: an `expect` that is present must name at least one of `slug` /
  `sub` — `{k: v for k, v in row.items() if v}` over a row with no slug yet
  gives `{}`, and that must not verify a link about anybody. Only `None` (or
  omitting it) means "no expectation".
- Options are keyword-only: `verify_flag(link, keys, 1800000000)` is a
  `TypeError`, never a silent use of the wall clock.
- Only `EdDSA` is accepted, exactly. `alg: none` is refused.

`fetch_keys(*, url=None, cache=True, ...)` reads
`https://www.pansofica.com/.well-known/record-status-keys.json` (the `www` host:
the kit follows no redirect), validates it and remembers it in-process for an
hour. It is the only network call verification ever needs. The key address is
the trust anchor: it must be `https` (plain `http` is accepted for loopback
only), a key set of another vocabulary is refused, and the key set handed out
is immutable.

## 2. Read a status — `lookup_status`

```python
from pansofica_flag import FlagNotFoundError, lookup_status

try:
    found = lookup_status("fixture-alpha")
except FlagNotFoundError:
    ...                                  # no record at that slug
else:
    found.record_status.status           # 'verified'
    found.record_status.label            # the kit's words for it
    found.receipt                        # the signed link — store it next to the status
    found.receipt_expires_at
    found.slug, found.moved              # the LIVE slug; it differs after a merge
    found.page_url, found.badge_url
```

**Omitting `origin` (and `url` / `keys_url` for the keys) asks the issuer's LIVE
service.** Name a stub in your tests.

**What is sent: the slug. Only the slug.** Never a name, a date of birth, an
email or any other column of your table. The slug is checked
(`^[a-z0-9][a-z0-9-]{0,199}$` after trimming ASCII whitespace and lower-casing
A–Z only — a letter outside ASCII is refused, never folded) before any
request is made. The request carries no cookie and no body; its `User-Agent` is
`pansofica-flag/<version> (+https://pansofica.com/developers)` unless you pass
your own `user_agent` (please do: a product name and a contact).

**Server-side only.** The lookup route answers no
`Access-Control-Allow-Origin: *`; call it from your backend, a job or a
notebook — not from a browser page.

The signed link in the answer is verified offline **before anything is
returned**, and the body must say what the link says (status, slug, subject,
document, review) — otherwise `FlagIntegrityError` is raised and nothing is
returned. Addresses (`page_url`, `badge_url`) are built from the verified link,
never copied from the wire.

**The receipt.** `found.receipt` is the signed link. Stored next to the status
and the time you checked, it lets anybody re-verify — offline, later — that the
issuer said so. A `disputed` in your table *without* a receipt is a statement
about a person that somebody typed by hand.

**What the receipt proves — and what it does not.** The signature covers the
status, the slug, the subject id, `lastReviewed`, the document's sha256, and
`iat` / `exp`. It does **not** cover the document's URL, the words, or any
address: the kit takes the words from its own table, builds `page_url` /
`badge_url` from its own constants, and carries a document URL only when it is
an `https:` address (on the keyed tier: a `/`-rooted relative path) — anything
else is a `FlagIntegrityError`.

**A move is not signed.** The signature proves the status of `found.slug`. It
does **not** prove that the slug you asked for (`found.requested_slug`) became
`found.slug`. A `moved` answer is vouched for only by TLS to the issuer's
origin. So: from the issuer's own origin a moved answer is returned with
`moved=True`; from **any other `origin`** it is refused (`FlagIntegrityError`)
unless you pass `allow_moved=True` — a custom origin is exactly the party the
receipt exists not to trust. When you do get a move, store the status AND
record the move (`requested_slug → slug`) for a person to look at. Never apply
it silently.

Errors — all extend `FlagError`:

| error | when |
|---|---|
| `FlagInvalidInputError` (also a `ValueError`) | refused before any request: not a slug, not a UUID, not an http(s) address |
| `FlagNotFoundError` | 404 |
| `FlagRateLimitedError` (`.retry_after_seconds`) | 429 — read from the `Retry-After` header only |
| `FlagUnavailableError` | 503, a network failure, a timeout, a redirect, an answer that is not JSON, a 200 that is not the issuer's answer at all (no signed link / no record with a flag) |
| `FlagIntegrityError` | the answer HAS a link and it does not verify, or the body disagrees with it, or a move this origin may not vouch for |
| `FlagAuthError` | 401 / 403 on the keyed tier |

Every error carries `http_status` — the status of the answer that caused it,
`None` when there was no answer. Retry later on "unavailable"; look at an
"integrity" failure before you ask again.

### Your own rows, in order — `lookup_many`

```python
from pansofica_flag import lookup_many

for item in lookup_many(slugs_from_my_own_table):
    if not item.ok:
        note(item.slug, item.error)      # ask again on the next run
        continue
    found = item.result
    save(item.slug, found.record_status.status, found.receipt)
    if found.moved:
        # No signature covers a move: keep it for a PERSON to look at; never re-point the row silently.
        record_move_for_review(item.slug, found.requested_slug, found.slug)
```

A generator: one item per distinct slug (and one per distinct spelling that is
not a slug — an item, never a request). **Sequential — never parallel** —
de-duplicated, and paced under the open tier (`OPEN_TIER_PER_MINUTE = 15`; the
route allows 20 a minute per node) by **one pacer per origin per process**,
shared by every `lookup_many` job. A 429 is retried after its `Retry-After`
seconds, at most `max_retries` times — clamped to `0..MAX_RETRIES`: there is no
option to hammer; a wait longer than `MAX_RETRY_AFTER_SLEEP_SECONDS` (120)
fails the item **without sleeping**. A failure is an item, never an exception
mid-run. Bad options are refused when you CALL it, before anything is asked.

`sleep` and `clock` are **test seams**, not tuning knobs. The limit is kept per
address: across processes or machines, run **one job at a time**.

Bound it to **your own rows**. The published terms refuse bulk reading: this is
not a way to enumerate the issuer's records. Cache what you read, re-check on
your own schedule, and send volume to the keyed tier.

### Volume — `lookup_status_keyed`

```python
import os
from pansofica_flag import lookup_status_keyed

answer = lookup_status_keyed(subject_id, api_key=os.environ["PANSOFICA_API_KEY"])
answer.record_status.status
answer.receipt                           # always None this round
answer.slug                              # the answer's own slug — bind it to YOUR row
assert answer.slug == my_row_slug        # a mistyped id is a VALID id of somebody else
```

`GET <origin>/partner/v1/fighters/<subject id>` with
`Authorization: Bearer <key>`. The subject id (a UUID you stored once) is the
only thing sent. The key rides in that header and nowhere else — never in an
address, a log, a `repr()` or an error message; the origin must be `https`
(plain `http` for loopback only), no redirect is followed and proxy variables
are ignored, so the key goes to the origin you named and to nobody else. (It
is, unavoidably, a local variable while the call runs: a crash reporter that
captures frame locals would see it.)

The keyed read carries **no signed link this round** (`receipt` is `None`): a
row you must *prove* gets its link through `lookup_status`. On this tier the
document's `url` is relative; its `sha256` is the join key across every surface.
A merged subject is answered by its survivor (`answer.moved`,
`answer.subject_id`).

A 429 here is **never slept on**: a monthly quota names a wait of *days*
(`error.within_sleep_cap` is `False`). Stop, and come back later.

## 3. Render — `render_badge`, `status_line`

```python
from pansofica_flag import render_badge, status_line

svg = render_badge("disputed")           # one line of SVG, byte-identical to the issuer's badge
svg = render_badge("link expired")       # also: 'link not valid', 'not available'
status_line("subject_corrected")         # "Corrected at the athlete's request"
status_line(flag, when_signed=result.issued_at)
```

`when_signed` is a `datetime`, a `date`, an ISO 8601 string (a moment without
an offset is read as UTC) or `None` (= no date). An epoch **number** is refused:
its unit would be a guess.

`render_badge` typesets **only** the closed list — the five statuses and the
three link states. Anything else raises `ValueError`: nothing from the wire is
ever typeset. A badge you render yourself shows what *you* hold; the hosted
badge (`found.badge_url`) shows what the issuer holds today.

## Options shared by the network calls

`origin` (omitted = the issuer's LIVE service), `opener` (anything with
`open(request, timeout=...)`), `timeout_ms`, `user_agent`, `clock` (seconds
since the epoch — the verifier's clock and `checked_at`); `lookup_status` /
`lookup_many` also take `keys` (pinned — pinned keys never cause a key read) or
`keys_url`, and `allow_moved`; `lookup_many` takes `sleep` and `max_retries`.
Every limit is a named constant in `pansofica_flag.constants`.

- A bad option is **refused before any request** (`FlagInvalidInputError`),
  never silently replaced: an address must be http(s) with no credentials, query
  or fragment; `user_agent` one line of printable ASCII, at most 200 characters;
  `timeout_ms` a finite number above zero.
- The default opener follows **no redirect** and **ignores `HTTP_PROXY` /
  `HTTPS_PROXY`** (as the TypeScript package's `fetch` does); if you need a
  proxy, pass your own `opener`.
- `timeout_ms` bounds connecting, each wait for bytes, and the **whole body
  read** (a body dripped a byte at a time is cut off at the deadline, give or
  take one socket wait). Response headers dripped slowly are bounded per wait,
  not in total. An answer larger than `MAX_RESPONSE_BYTES` (256 KiB) is refused
  while it is read.
- An unknown `kid` forces ONE fresh read of the key set, then not again for
  `KEY_REFRESH_FLOOR_SECONDS`.

## The other package

`@pansofica/flag` (TypeScript) has the same surface, the same verdicts and the
same errors for the same input. What differs is idiom, on purpose:

| | Python (`pansofica-flag`) | TypeScript (`@pansofica/flag`) |
|---|---|---|
| names | `snake_case` (`lookup_status`, `retry_after_seconds`, `http_status`) | `camelCase` (`lookupStatus`, `retryAfterSeconds`, `httpStatus`) |
| instants in results | aware UTC `datetime` (`None` when no `datetime` can hold it) | ISO 8601 strings (`null` likewise) |
| the clock | `clock` — a function returning **seconds** since the epoch, everywhere | `now` on lookups; `clock` in **milliseconds** on `lookupMany` / `fetchKeys` |
| `timeout_ms` / `timeoutMs` | milliseconds in both | milliseconds |
| key cache constant | `KEY_CACHE_SECONDS` | `KEY_CACHE_TTL_MS` |
| outside the closed list (`render_badge`, `status_line`) | `ValueError` | `TypeError` |
| `when_signed` | `datetime`, `date`, ISO string (offset-less = UTC), `None`; never an epoch number | `Date`, ISO string (offset-less = UTC), `null`; never an epoch number |
| version | `__version__` | `KIT_VERSION` |
| verify | synchronous; `can_verify()` is always `True` | `async`; `canVerify()` asks the runtime for Ed25519 |
| network seam | `opener=` (urllib) | `fetch:` |

## Tests

```bash
PYTHONPATH=src python -m unittest discover -s tests -v
```

The tests are driven by `../fixtures/record-status-fixtures.json` — produced by
the issuer's own mint, verify and badge code under an **invented, published**
key — so this kit's verdicts are the server's, case by case (the loop reads
every case in the file; no case name is listed in code). A few rules are also
pinned by links the tests mint themselves from that same published key
material. A loopback stub replays the lookup answers.

**No test leaves the box.** In the test process any connection, datagram or
name lookup that is not to loopback fails the test. The packaging test builds
with `--no-isolation` and installs with `--no-index` (it is skipped, loudly,
when the interpreter has no `build` / `setuptools`), so its subprocesses ask no
index either. The proof for everything at once is a run inside a network
namespace that has loopback only:

```bash
unshare -n sh -c 'ip link set lo up; PYTHONPATH=src python -m unittest discover -s tests'
```

The fixture keys verify nothing real: never add them to a real verifier.

## Licence

Apache-2.0. Copyright 2026 PXL8 Technology, Inc. See `LICENSE` and `NOTICE`.
