# SPEC: scorpiox-scorpioplayer-template-fetch (`sptf`)

Pure C99 client for the server-driven UI bundle: fetch, hash-diff, zlib-inflate, validate keys,
cache to disk, restore on launch, fall back to a packaged offline bundle. It moves bytes and never
interprets a template (that is `scorpiox-scorpioplayer-template-parse`).

Spec source (read-only): `reference/scorpiox-scorpioplayer-template-fetch/csharp-reference/`.
Citations below are `RuntimeService.cs:<line>` (RS), `System.GetStringStableHashCode.slice.cs`
(HASH) and `SettingsUIHelper.GetRuntimeTemplatebundle.slice.cs` (BUNDLE).

Written before the C. Items marked **DIVERGES** are deliberate differences from the C#.

---

## 1. Wire subset

| # | Decision | Source |
|---|---|---|
| W1 | One request: `POST {host}/api/AAA/RuntimeTemplates?zip=true&update=False&userId={uid}`. `update` is rendered `False` because C# interpolates a `bool` (`$"{update}"` gives `False`); ASP.NET binds it case-insensitively. `update=true` is never sent (RS:111 always passes `update: false`). | RS:111, RS:164 |
| W2 | Body: a JSON object `{ "<key>": "<decimal stable hash>" }`, one member per entry held, in insertion order, hash as a **string** (`.ToString()`). `sptf_refresh_full` sends `{}`. | RS:111, RS:167 |
| W3 | `Content-Type: application/json`. **DIVERGES**: `WebClient.UploadData` sets no Content-Type. Pico's live measurement used `application/json` and got 200; `tools/live/measure.sh` also measures the no-header variant. | RS:168 |
| W4 | `userId` is percent-encoded (RFC 3986 unreserved set, `scorpiox_percent_encode`). **DIVERGES**: C# interpolates it raw (RS:164). | RS:164 |
| W5 | Response: `200`, body is a raw **zlib** stream (RFC 1950, header `78 da`), inflating to UTF-8 JSON `{ "<key>": "<content>" }`. Values are strings (JSON documents double-encoded as strings, HTML, and base64 PNG). | RS:171-174, task measurement |
| W6 | `GET` works server-side but is not used: C# always posts. | RS:168 |
| W7 | The packaged bundle (`Assets/package/runtimetemplatebundle.txt`) is the same zlib+JSON format. `sptf_load_bundle(bytes, len)` takes those bytes; the host reads the asset (C never derives a platform path). **Finding**: the two slice files split one method: `GetRuntimeTemplatebundle()` ends with the first two lines of the hash slice, `return null; }`. As shipped it computes `fname` and returns null, so the bundle fallback is dead code in this C#, and if `FromJSONObject` throws on null (not shipped; unknown) `Restore()` throws and `Init` never starts `Refresh` (reproduced in `tools/csharp-oracle`). We implement the intended behaviour. | BUNDLE:9-13, RS:136-137 |

## 2. State and merge rules

| # | Decision | Source |
|---|---|---|
| S1 | One in-memory map `key -> (bytes, len, origin, hash)`, insertion ordered. `origin` is `SERVER`, `DISK` or `BUNDLE`. | RS:68 |
| S2 | Precedence `SERVER > DISK > BUNDLE`: an incoming value replaces the held one iff its origin ranks the same or higher. This makes `sptf_restore` and `sptf_load_bundle` order-independent and reproduces RS exactly for the C# call order (disk overwrites, RS:132; bundle fills only missing keys, RS:142; server overwrites, RS:116). | RS:126-149, RS:116 |
| S3 | **Disk wins over the bundle** (decision 2 of the task). Staleness verdict: a cached file older than a newer packaged bundle wins until the next successful refresh; an offline user who updates the app keeps the stale cached copy indefinitely. Kept as spec; `sptf_origin()` makes it observable. Proposed fix for the shell (not done in C): stamp the bundle version into the cache folder and drop `DISK` entries when it changes. | RS:142 |
| S4 | Refresh never deletes an entry (full or diffed). Entries absent from the server response keep their current value and origin. Same as C#. | RS:114-117 |
| S5 | The hash sent for an entry is computed over what is held for it, including `BUNDLE` entries (C# hashes `RuntimeConfigs`, which contains bundle entries). | RS:111 |
| S6 | A value is stored byte-for-byte as delivered, length-counted (`sptf_content_len`), also NUL-terminated for convenience. A PNG entry is a base64 **string** on the wire; it is stored and cached as that base64 text, never decoded, exactly like `File.WriteAllText` does (RS:157). Embedded `\u0000` survives (length-counted). | RS:157, task |
| S7 | Not thread-safe. Returned pointers (`sptf_key`, `sptf_content`, `sptf_result_json`, `sptf_last_error`, `sptf_warning`) stay valid until the next call that mutates state (`restore`, `load_bundle`, `refresh*`, `clear`, setters). The shell runs refresh on one worker and copies strings out (P/Invoke marshalling copies). C# runs Refresh on a background task while the UI reads the same `Dictionary` unsynchronised (RS:95), which is a data race; we do not reproduce it. | RS:95 |
| S8 | A server entry whose bytes equal what is held **and** already on disk is not rewritten (the unchanged `strings.json` resend would otherwise rewrite ~2.2 MB on every launch). Everything else the server returns is written, like `Save()`. | RS:150-160 |

## 3. Cache layout and file IO

| # | Decision | Source |
|---|---|---|
| C1 | Folder = `<cache_dir>/<userId>/runtimetemplates` when `userId` is non-empty, else `<cache_dir>/runtimetemplates`. `cache_dir` is a parameter (`sptf_set_cache_dir`); C never calls a platform path API. | RS:72-89 |
| C2 | `cache_dir` must already exist; the two sub-levels are created (`0700`). **DIVERGES**: C# `CreateDirectory` creates the whole chain. A typo in the root fails loudly instead of creating a stray tree. | RS:82-85 |
| C3 | `userId` is a path component, so it goes through the key validator (K1). **DIVERGES**: C# does not check it; a `userId` of `../x` escapes the cache root exactly like a bad key. | RS:79 |
| C4 | Writes are atomic: `.sptf-tmp-<pid>-<n>` in the folder, `O_CREAT|O_EXCL|O_NOFOLLOW`, mode `0600`, then `rename` over the final name (Windows: `MoveFileExW(REPLACE_EXISTING)`). A planted symlink at the final name is replaced, never followed. Temp names start with `.`, which no valid key can, so they never collide. **DIVERGES**: `File.WriteAllText` truncates in place (a crash leaves a partial file) and follows symlinks. | RS:156-157 |
| C5 | Restore reads every regular file directly in the folder. Skipped with a warning: names that fail K1, symlinks, directories, files over `SPTF_MAX_INFLATED`; leftover temp files are deleted silently. A leading UTF-8 BOM is stripped (`File.ReadAllText` strips it). **DIVERGES**: C# follows symlinks and would load any name. | RS:128-133 |
| C6 | Content is written as bytes (UTF-8, no BOM), matching `WriteAllText`'s default encoding. | RS:157 |
| C7 | A failed write does not abort the refresh: every remaining entry is still processed, memory is updated, and `sptf_refresh` returns `SPTF_ERR_CACHE_IO` with a warning per failed key. **DIVERGES**: in C# the first `IOException` escapes `GetRuntimeConfigs` (only `WebException` is caught, RS:180) into `Refresh`'s `catch (Exception)` (RS:120): later entries are not written and memory is not updated at all. | RS:150-160 |

## 4. Key validation (the P0)

`Save()` does `Path.Combine(_folder, item.Key)` with a server-controlled key and no check (RS:156).
`Path.Combine("C:\\cache\\runtimetemplates", "../../x")` resolves outside the folder, and
`Path.Combine(folder, "C:\\x")` or `"/x"` **returns the second argument unchanged** (a rooted second
argument discards the first). **Verdict: exploitable as written** -- any response the client accepts
can write any file the app can write. Reproduced against the unmodified C# in
`tools/csharp-oracle` (see the report).

| # | Rule: a key is refused if it | Why |
|---|---|---|
| K1a | is empty, or longer than 255 bytes | empty name, NAME_MAX |
| K1b | contains `/` or `\` | separators on every platform |
| K1c | contains `..` anywhere, or is `.`, or starts with `.` | traversal; hidden files; reserves `.` for our temp names |
| K1d | starts with `~` | home expansion in shells and some APIs |
| K1e | contains `:` | drive letters (`C:`), NTFS alternate data streams (`a.json:evil`) |
| K1f | contains a byte `< 0x20` (NUL, CR, LF, ...) or `0x7F` | NUL truncation, log injection |
| K1g | contains `< > " | ? *` | invalid on Windows, wildcard on some APIs |
| K1h | ends with `.` or space | Windows silently strips them, aliasing another key |
| K1i | is a Windows device name (`CON PRN AUX NUL COM1-9 LPT1-9`, any case, with or without an extension) | `CON.json` opens the console on Windows |

Refused entries are dropped from memory **and** disk, raise a `SECURITY:` warning each, and are
listed in `result_json.last_refresh.refused_keys`. The rest of the response is applied and
written, and then the call returns `SPTF_ERR_UNSAFE_KEY` (it outranks `SPTF_ERR_CACHE_IO`), so the
security event is visible in the return code without losing the safe entries. **DIVERGES**: C#
stores the bad key in memory too, and writes it wherever it points.

Not covered by K1: case-insensitive collisions (`Settings.json` vs `settings.json` on NTFS/APFS
overwrite each other). Detected and warned, not refused. `nul.json`, `con.json` etc. ARE refused
(K1i): on Windows they open a device, whatever the extension.

## 5. Inflate limits (zip-bomb guard)

| # | Decision |
|---|---|
| Z1 | zlib container required (RFC 1950 header check and Adler-32, via vendored **miniz 3.0.2** `mz_inflate`). gzip or raw deflate is `SPTF_ERR_ZLIB`. |
| Z2 | `SPTF_MAX_COMPRESSED` = 32 MiB: a larger body is refused by the libcurl backend while downloading. |
| Z3 | `SPTF_MAX_INFLATED` = 64 MiB absolute (live full bundle: 9,256,319 B, so 7x headroom). |
| Z4 | Ratio limit 100:1 once the output passes 4 MiB (live bundle: 5.28:1; diffed: 3.37:1). A 200 MB zero bomb stops after ~4 MiB of output. |
| Z5 | Trailing bytes after the zlib end-of-stream: accepted with a warning (the C# `Zip.Uncompress` implementation is not in the reference; we do not know that it rejects them). Truncated stream (no end-of-stream) is `SPTF_ERR_ZLIB`. |
| Z6 | Zero-byte 200 body: OK, 0 entries, warning. (C# treats it as "nothing", RS:169.) |

Why miniz and not system zlib: one vendored C file, no link dependency on Windows (the mingw DLL
has no zlib), identical code on Linux/Windows/iOS/Android. iOS implication: none. iOS ships
`libz` too, but using it would mean a second code path with different limits; with miniz the
inflate the fuzzer drives is the one iOS runs. Symbols are hidden (`-fvisibility=hidden`,
`MINIZ_NO_ZLIB_COMPATIBLE_NAMES`), so no clash with the zlib that libcurl links.

## 6. JSON

| # | Decision | Source |
|---|---|---|
| J1 | Vendored yyjson 0.10.0 for all JSON (parse, the hash body, `result_json`). | task |
| J2 | Top level must be an object, else `SPTF_ERR_JSON`. Invalid UTF-8 is `SPTF_ERR_JSON` (yyjson strict). **DIVERGES**: C#'s decoder would substitute U+FFFD. | RS:174 |
| J3 | A member whose value is not a string (number, bool, null, object, array) is refused with a warning; the rest is kept. **DIVERGES**: Newtonsoft would coerce scalars to strings and throw on an object/array, losing the whole response. | RS:174 |
| J4 | Duplicate keys: last wins (Newtonsoft `Dictionary` indexer semantics), warning. | RS:174 |
| J5 | Entry limit `SPTF_MAX_ENTRIES` = 100,000 per response (live: 301). | -- |

## 7. The stable hash

`GetStringStableHashCode` (HASH:14-38), ported exactly over **UTF-16 code units** (default):
`h1 = h2 = 5381`, pairs `(s[i], s[i+1])`, stop at a NUL code unit, `abs(h1 + h2*1566083941)` in
wrapping int32. Content bytes are decoded UTF-8 -> UTF-16 on the fly (supplementary characters
become surrogate pairs). Ill-formed UTF-8 (only possible from a disk file) decodes to U+FFFD per
maximal subpart, as .NET's `UTF8Encoding` does.

`int.MinValue`: `Math.Abs(int.MinValue)` throws `OverflowException`, which the method's own
`catch (Exception)` turns into `return 0` (HASH:34-36). We return 0 for that input. A test vector
that hits it (`"j8b@+/"`, found by a meet-in-the-middle search over printable ASCII) is in the unit tests and was checked
against the C# method compiled unmodified.

The UTF-8-bytes and code-point readings exist only as internal variants for the live experiment
(`sptf probe`) and for the report. Reimplemented, not linked from `media-hash` (tracker rule 3).

## 8. Transport and the `scorpiox_io` binary problem

`scorpiox-io.h` is copied verbatim. Its `http_post` returns `char **out_body`, NUL-terminated,
**no length**. A zlib body contains `0x00` (the live one does, at many offsets), so the public
vtable **cannot carry this response**. Contract fix proposed (not applied to the header):
`http_post_bin(ctx, url, body, body_len, content_type, unsigned char **out, size_t *out_len,
long *code, char **err)`, or the fleet `scorpiox_http` proposal from the WebDAV engine (SPEC D1
there), which already carries a length-counted body.

Until then:

| # | Decision |
|---|---|
| T1 | The library's own backends (`sptf_io_curl()`, `sptf_io_fake()`) carry a private length-counted POST. `sptf_set_io` recognises them by pointer identity and uses the binary path with `zip=true`. |
| T2 | Any other `scorpiox_io` (for example the Swift `URLSession` one) gets `zip=false`: the server then answers plain UTF-8 JSON, which cannot contain a raw NUL, so a NUL-terminated body is lossless. Cost: no compression (the diffed response is ~3.4x bigger). A warning says so on every refresh. |
| T3 | libcurl backend: TLS verified, no redirects followed (a POST redirect is an error: `SPTF_ERR_HTTP`), 32 MiB body cap, 60 s timeout, `Accept-Encoding` off (the body is already zlib). |
| T4 | Fake backend: `(method, url) -> (code, bytes)` routes or a transport failure; records the last request body. Never touches the network. `make test` and the console `--test` use only it. |

## 9. Error map

| Code | Value | When | C# |
|---|---|---|---|
| `SPTF_OK` | 0 | | |
| `SPTF_ERR_TRANSPORT` | -1 | backend returned -1 | swallowed (RS:180) |
| `SPTF_ERR_HTTP` | -2 | status not 2xx | swallowed (WebException) |
| `SPTF_ERR_ZLIB` | -3 | bad/truncated zlib, or a limit of section 5 | swallowed (RS:120) |
| `SPTF_ERR_JSON` | -4 | not JSON, not an object, invalid UTF-8 | swallowed (RS:120) |
| `SPTF_ERR_CACHE_IO` | -5 | a cache read/write/mkdir failed | swallowed |
| `SPTF_ERR_UNSAFE_KEY` | -6 | every applicable entry was refused by K1; also `set_user_id` with an unsafe id | not detected |
| `SPTF_ERR_NO_IO` | -7 | refresh without `sptf_set_io` | n/a |
| `SPTF_ERR_INVALID_ARG` | -8 | NULL/empty args, no cache dir, bad host | n/a |
| `SPTF_ERR_OOM` | -9 | allocation failed | n/a |

A failed refresh leaves the in-memory map untouched (all-or-nothing up to the write stage),
so a transport error is never an empty map. `last_error` never contains the query string
(the `userId`).

## 10. Counters (per refresh, reset at its start)

`sent` = request body bytes; `received` = response body bytes (compressed); `inflated` = JSON
bytes; `changed` = entries whose bytes differ from what was held (or were new); `unchanged` =
entries the server sent back **byte-identical** to what we already held -- wasted bandwidth,
the `strings.json` anomaly. `result_json.last_refresh` adds `unchanged_bytes`, `unchanged_keys`,
`new`, `refused`, `write_failed`, `mode` and `zip`. The unchanged count is also raised as a
warning per key, so a successful return never hides wasted bytes.

## 11. Exports

Documented contract (task) plus the backend/fake helpers the CLI and the C# console need.
Exactly these symbols are exported (`sptf.map`, `exports.json`, checked by `make exports-check`).

```
sptf_version  sptf_set_io  sptf_io_curl  sptf_io_fake
sptf_fake_reset  sptf_fake_set  sptf_fake_fail  sptf_fake_calls  sptf_fake_last_body
sptf_set_host  sptf_set_cache_dir  sptf_set_user_id
sptf_restore  sptf_load_bundle  sptf_refresh  sptf_refresh_full
sptf_count  sptf_key  sptf_content  sptf_content_len  sptf_hash  sptf_origin
sptf_last_refresh_sent  sptf_last_refresh_received  sptf_last_refresh_inflated
sptf_last_refresh_changed  sptf_last_refresh_unchanged  sptf_last_http_code
sptf_clear  sptf_result_json  sptf_last_error  sptf_warning_count  sptf_warning
```

`sptf_hash` returns the int32 stable hash (>= 0), or -1 for an unknown key.
`sptf_origin` returns `SPTF_ORIGIN_SERVER`=1, `DISK`=2, `BUNDLE`=3, or 0 for unknown.
`sptf_content_len` returns -1 for an unknown key (so an empty entry is distinguishable).

## 12. Not in this engine

Template parsing, the `ffsp.json` flag lookup (`GetGlobalFeatureFlagStringValue`, RS:55-67:
`template-parse` gets the raw text through `sptf_content("ffsp.json")`), background threading
(RS:95), platform cache paths (RS:81).
