# SPEC: scorpiox-scorpioplayer-spfs-http-file-client (RuntimeType `SPFS`)

A read-only client for ScorpioMediaServer HTTP file servers (Windows 2.0.0.0, Linux CLI 3.0.0.0,
the row 32 C server): validate the server, list its shared folders, browse them, and give #20
(`remote-seek-stream`) a range-readable URL per file. Behind `sprch_handler` (sprch.h, v1) and a
flat stateful `spfsc_*` face for #26. Spec sources:
`reference/scorpiox-scorpioplayer-spfs-http-file-client/csharp-reference/`
(`SPFSRuntimeConfigHandler.cs`, `SPFSPlaylistFolder.cs`, the categorizer slice) and the task.
"C#" means that reference; "we" means this engine. Section 7 lists the legacy defects, measured by
compiling the reference unmodified (`tools/csharp-legacy`).

`SPFSService` (Lookup.cs:30), which does the HTML scraping and the id, is **not in reference/**:
the reference SKILL.md lists `SPFSService.slice.cs`, the dispatch commit does not carry it.
`tools/csharp-legacy/SPFSService.Reconstructed.cs` rebuilds it from the task text; findings that
depend on its unknown parts (the three date formats) are marked ASSUMED.

## 1. Wire subset

| Operation | Requests | Notes |
|---|---|---|
| `validate` | `GET {FullUrl}/api/Version`, then `GET {FullUrl}/api/Folders` | D2, D3 |
| `list("")` | `GET {FullUrl}/api/Folders` | only the keys are read (D12) |
| `list("/Key/a/b")` | `GET {FullUrl}/Key/a/b/?format=json&limit=1000[&cursor=C]` | one request decides JSON vs HTML (D7) |
| `stream_url` | none | pure (D9) |
| `download` | none | `SPRCH_E_NOTSUPPORTED` (C#: `DownloadAsync` returns null) |

Paths keep the C# casing (`/api/Version`, `/api/Folders`): every field server answers it, since
every field client sends it. Headers (scorpiox_http extension only): `Accept`,
`User-Agent: scorpiox-spfs/1.0.0`, `Authorization: Bearer <ServerKey>` when one is configured.
GET only. No writes of any kind.

## 2. Decisions

**D1. ServerUrl + ServerPort + UseHttps -> FullUrl** (`spfsc_full_url`, `SPFSRuntimeConfigHandler.cs:71-80`).
The result is always `{http|https}://{host}:{port}` like C#. `UseHttps` is .NET `bool.TryParse`
(`true` any case, blanks allowed; a JSON `true` too); anything else is http, like C#. The host:

| ServerUrl shape | host | port when ServerPort is empty | C# |
|---|---|---|---|
| bare `nas`, `NAS.Local`, ` nas ` | lowercased, trimmed | 80 (https: 443) | same, except blanks: `http:// nas :80` |
| `host:port` (`192.168.1.5:3323`, `localhost:3323`) | host | the given port | `http://192.168.1.5:3323:80`; `localhost:3323` parses as scheme `localhost` -> `http://:80` |
| full URL (`http://nas:3323/Hosted/x`) | its host (userinfo, path, query dropped) | the URL's port | only the host: port 80 |
| bare IPv6 `::1`, `fe80::1`; `[::1]`, `[::1]:3323` | bracketed | the given port / 80 | `http://::1:3323` (unusable) |
| `nas/share`, `nas\share`, `user@nas` | host only | 80 | `http://nas/share:3323`; `user@` kept |

A non-empty ServerPort always wins (C#). The scheme of a full URL is ignored (C#: `UseHttps`
decides). https with no port anywhere is 443 (C#: `https://host:80`, which cannot work).
Refused (`SPRCH_E_CONFIG`, a reason in `last_error`): empty, control bytes, a space or other
character outside `[A-Za-z0-9.-_~]` in a name, a leading `.` / `-`, non-ASCII (IDN: enter the
punycode form), an IPv6 literal with other than hex / `:` / `.`, a port outside 1..65535.
Measured against the C# (`tools/oracle/results/fullurl.md`).

**D2. Validation = `GET /api/Version` parses as a .NET `Version` >= 1.1.0.0** (C# `IsServerValidAsync`).
The body is trimmed; 2 to 4 dot-separated decimal components; missing components are -1 and the
comparison is .NET's, so `1.1` and `1.1.0` are *older* than `1.1.0.0` (measured in .NET 8, kept:
no field server answers that). One addition: a JSON string body (`"3.0.0.0"`) is unquoted first, so
row 32 may answer JSON. Not a version -> `SPRCH_E_PROTOCOL` "not an SPFS server (the body "..." is
not a version)" (a 40-byte printable excerpt); 404 -> `SPRCH_E_NOTFOUND` "(not an SPFS server)".
The version is exposed (`result_json.version`, `spfsc_server_json`).

**D3. validate also asks `/api/Folders`, and writes a delta.** A 401 / 403 there fails validate
with `SPRCH_E_AUTH` ("the server wants a ServerKey" / "refused the ServerKey"): a row 32 server that
enforces the key is caught at the connection test, not at the first browse. Any other folders
failure is reported (`result_json.folders_error`) and validate stays OK, as the C# test (version
only) would. The delta (the registry merges it, C# `c.RuntimeSettings[k] = v`): `FullUrl`,
`RuntimeType: "SPFS"`, `ID` (a new v4 GUID only when absent). Unknown keys are never echoed. On
failure C# also clears `FullUrl`; the sprch contract carries no delta on an error, so the host
keeps the old one. validate builds FullUrl from `ServerUrl` when present (C# rebuilds it);
`list` / `stream_url` read `FullUrl` first (C# `CreateRootFolder`) and fall back to ServerUrl.

**D4. ServerKey is sent as `Authorization: Bearer <key>`.** C# reads `ServerKey` and then calls
`IsServerValidAsync(serverUrl, string.Empty, ...)`: the key never leaves the phone and no field
server checks one (harmless to send). We send it on every request so row 32 can enforce it. The key
is trimmed, must be printable ASCII (it is an HTTP header: CR / LF are refused, `SPRCH_E_CONFIG`) and
<= 4096 bytes. It goes only to the FullUrl origin or its https upgrade; a redirect to another origin
drops it (`result_json.key_sent`). It never appears in `result_json`, `last_error`, error JSON or
list metadata, and every error message is scrubbed of it: transport messages, and anything a server echoes back (a version body excerpt, a page title). fuzz_json found the echo case; test_handler pins it. Item names a server returns are data and are not rewritten. The one output that carries it is
`stream_url`'s `headers` (the player needs it; the conformance suite exempts pure URL builders).

**D5. Transport: scorpiox_io v1 plus an optional scorpiox_http extension** (the fleet proposal in
`include/scorpiox-http.h`, verbatim; shared with webdav-client and aspnet-directory-listing-client).
`sprch_handler` receives only a `scorpiox_io *`. The engine looks up a bound `scorpiox_http` for it,
keyed by `(http_get, ctx)`; the libcurl and fake transports are pre-bound, `spfsc_bind_http()` binds a
platform backend (URLSession, WinHTTP).

| | scorpiox_http | scorpiox_io v1 |
|---|---|---|
| ServerKey | sent (Bearer) | cannot be sent (no headers); `key_sent: false` |
| redirects | the engine: <= 5, no https -> http, key stays on its origin | the backend's (libcurl: <= 5) |
| item URL base | the final URL | the requested URL |
| body bound | enforced while streaming (the transfer is cut) | enforced after the backend returns it |

**D6. Dates and sizes are culture-free** (`src/listing_parse.{h,c}`, vendored verbatim from
aspnet-directory-listing-client, row 62). Size: a grouped integer whatever the separator
(`1,234` `1.234` `1 234` U+202F `12,34,567`); `1.5`, `1,23`, `-1` -> unknown. Date: read by shape
(4-digit year position, separators, `am`/`pm` any case, U+202F / U+00A0 as spaces, `+HH:MM`); the
measured live format `1/12/2023 4:35:33 am +00:00` is read. A numeric day/month pair with the year
last is decided **per page**: a first number > 12 or a `.` / `-` separator means d/M, a second > 12
means M/d, a contradicting page stays ambiguous. A page whose every date has day <= 12 cannot decide:
those mtimes are -1 (never a guess), unless the settings carry `DateOrder: "dmy" | "mdy"` (a new
optional key, same as ASPNET's). `result_json.date_order` says what the page decided.
`spfsc_parse_mtime` on one string returns -2 for that case; `spfsc_parse_mtime_order` decides it.

**D7. JSON when the server has it, HTML otherwise, in one request.** A folder is fetched as
`{dir}/?format=json&limit=1000`. ASP.NET `UseDirectoryBrowser` (every field server) ignores the query
and answers its HTML page; row 32 answers JSON. The body decides (`{` first, or a JSON Content-Type):
no probe request, no second request for legacy servers. The JSON contract (a proposal for row 32,
implemented by `tools/oracle/spfs-server` in `json` mode):

```
GET /<folder>/<rel>/?format=json&limit=<n>[&cursor=<c>]
200 {"items":[{"name":"a.mkv","kind":"file","size":123,"mtime_unix":1700000000},
              {"name":"Sub","kind":"dir","mtime_unix":1700000000}],
     "next":"<opaque cursor>" | <number> | null}
```

`kind`: `file`, or `dir` / `directory` / `folder`; `size` >= 0 for files; `mtime_unix` 0..9999-12-31
(absent = unknown). Pages continue while `next` is a non-empty string or a number (sent back
percent-encoded as `cursor`). A repeated cursor is a loop (`SPRCH_E_PROTOCOL`); an HTML page after a
JSON page is a protocol break; an error on any page fails the whole list (never a short list). Items
without a usable name or with an unknown kind, and duplicate names (the first wins), are counted in
`rejected`, not returned. The server may return fewer than `limit`; ours caps at 500.

**D8. Ids.** C# keys an item by `GetStringStableHashCode(new Uri(downloadUrl).PathAndQuery)`: it
changes whenever the host or port changes (a NAS gets a new IP, a port moves) and collides at 31
bits. We give `id` = 64-bit FNV-1a of `"spfs\0<folder key>\0<relative path>"` as 16 hex digits
(host-independent; `relpath` is `a/b/name`, `""` for a folder key). `legacy_id` is the C# value for
migration: `spfsc_legacy_pq` rebuilds the PathAndQuery the legacy chain produced (AngleSharp Href of
`./<name>` -> System.Uri: RFC 3986 unreserved + sub-delims + `:@/[]` kept, `%XX` kept except escaped
unreserved characters decoded (`%41` -> `A`), `#` ends it, the rest `%XX`), hashed over UTF-16 code
units (the template-fetch port). Measured equal on all 15,255 rows the .NET chain produced
(`results.json: ids`). `/api/Folders` keys have no legacy item: `legacy_id: null`.

**D9. stream_url is pure.** `url = FullUrl + each path segment percent-encoded`
(`scorpiox_percent_encode`: RFC 3986 unreserved kept). With a ServerKey:
`headers: {"Authorization": "Bearer <key>"}`. A folder entry, a folder key alone (`/Media`) or a
`.` / `..` segment -> `SPRCH_E_NOTFOUND`; no `path` -> `SPRCH_E_CONFIG`. The URL is range-readable
(ASP.NET StaticFiles: 206 + `Content-Range`), proven by SHA-256 through consecutive range reads.

**D10. Names and kinds.** HTML: the anchor text, HTML-decoded, one trailing `/` dropped for folders;
the href (`./` + HtmlEncoded name, not URL-encoded) is never resolved (C# resolved it: `#` and `%41`
break, section 7). The kind comes from the row class (`tr.file` / `tr.directory`), so a 0-byte file
is a file of size 0 (C#: `size < 1` = folder). JSON: `name` and `kind`. A name is refused (counted)
when empty, `.`, `..`, containing `/`, a C0 byte or DEL, invalid UTF-8, over 1024 bytes, or a repeat.

**D11. Paths.** `folder_id` = `"/<folder key>/<rel>"` (leading / repeated `/` ignored; `""` or `"/"` =
the shared folders). Item `path` has the same form and is what `list` / `stream_url` take back.
URLs are rebuilt from the decoded path (never from a server href), so paths survive a host move.

**D12. `/api/Folders`: keys only, values never.** The body is parsed, the keys are copied, the
values (host paths such as `D:\Media`) are never copied, logged, returned or put in an error; the
body buffer is zeroed before it is freed. The oracle scans every CLI output for the tree's host path
(`results.json: leaks`). Keys follow D10; order is the server's.

**D13. Errors are errors.** 401/403/407 -> `SPRCH_E_AUTH`; 404/410 -> `SPRCH_E_NOTFOUND`;
429 -> `SPRCH_E_RATE`; 408, 5xx, transport failure, timeout -> `SPRCH_E_NETWORK`; a 2xx that is
neither a JSON listing nor a directory index, an unfollowed 3xx, a body over its limit, a JSON
loop -> `SPRCH_E_PROTOCOL`; unusable settings -> `SPRCH_E_CONFIG`. No failure returns `SPRCH_OK`
with an empty list. An empty folder / no shared folder (`{}`) is `SPRCH_OK` with no items.

**D14. The page must be the folder that was asked for.** DirectoryBrowser titles a page
`Index of /<folder>/<rel>/`; it must end with the requested path, else `SPRCH_E_PROTOCOL` "the
server answered with the listing of another folder" (a lossy redirect or proxy). No title = no
evidence = accepted. The `/api/Folders` listing has no page.

**D15. Output and threads.** `list`: `{"items":[{"name","path","folder","kind","size","mtime_ms",
"mtime_unix","url","id","legacy_id"}]}`: the spffa item fields (`folder`, `mtime_ms`) and the
task's (`kind`, `mtime_unix`); `size` / `mtime` -1 = unknown. `result_json` (complete, also after
`E_BUFFER`) puts `op`, `code`, `source` (`api` / `json` / `html`), `folder`, `rel`, `final_url`
(redacted), `pages`, `count`, `rejected`, `skipped`, `redirects`, `key_sent` (+ `dialect`,
`date_order`, `date_hinted` for HTML) before the items. `E_BUFFER`: `out[0] = 0`, nothing written past
`cap`. The handler is stateless and thread-safe (the io binding table, the fake routes and the
result strings are each behind a lock). The `spfsc_*` stateful face keeps one current listing and is
single-threaded, like spffa; its `result_json` is metadata only (items via `spfsc_item_json`).

## 3. State machine (one `list`)

```
settings --parse--> E_CONFIG (no ServerUrl/FullUrl, bad port, bad key)
   | FullUrl (D1) ; folder_id -> key + rel (D11) --bad--> E_NOTFOUND
   v
key == "" : GET /api/Folders --> keys (D12) --> items
key != "" : GET /key/rel/?format=json&limit=1000
              transport failure -> E_NETWORK ; redirect failure -> E_PROTOCOL ; status map (D13)
              body '{' ?
                yes: JSON page -> items, next? --> GET ...&cursor=next (<= 10000 pages, 8 MiB each)
                no : HTML (<= 64 MiB) -> listing_parse (D6, D10) -> "Index of" check (D14) -> items
   v
ids (D8), URLs from the final directory URL (D5) --> {"items":[...]}
```

## 4. Auth

`ServerKey` only (D4). No userinfo (dropped from ServerUrl / FullUrl), no cookies, no tokens.

## 5. Parser

`src/listing_parse.{h,c}` is row 62's standalone parser, copied verbatim (same bytes as
`reference/.../vendored-listing-parser/`): a bounded single pass, no DOM, libc only. It also reads
nginx / Apache indexes (an SPFS folder behind such a proxy still lists). Limits passed here:
64 MiB page, 1,000,000 rows. On the measured Hosted shape (15,243 rows, 4.2 MB, the live en-NZ
format) the parse takes ~50 ms and the page + parser peak is ~8 MB (`test_perf`; budget 200 ms /
16 MB). The generator in `test_perf` is proven equal to the rows the ASP.NET oracle serves.

## 6. Limits

| Limit | Value | Past it |
|---|---|---|
| HTML page | 64 MiB | `SPRCH_E_PROTOCOL` "larger than 64 MiB" (the transfer is cut) |
| JSON page | 8 MiB | `SPRCH_E_PROTOCOL` |
| `/api/Version`, `/api/Folders` body | 1 MiB | `SPRCH_E_PROTOCOL` |
| entries per folder (all pages) | 1,000,000 | `SPRCH_E_PROTOCOL` |
| JSON pages per folder | 10,000 | `SPRCH_E_PROTOCOL` |
| shared folders | 4096 | `SPRCH_E_PROTOCOL` |
| name | 1024 bytes UTF-8 | that entry rejected |
| cursor | 1024 bytes | `SPRCH_E_PROTOCOL` |
| ServerKey | 4096 bytes printable ASCII | `SPRCH_E_CONFIG` |
| URL | 8192 bytes | `SPRCH_E_CONFIG` |
| redirects | 5 | `SPRCH_E_PROTOCOL` (extension) / backend error (v1) |
| timeouts | validate 5 s (C#: 5000), list 120 s; libcurl connect 15 s, stall 60 s | `SPRCH_E_NETWORK` |

## 7. Legacy defects (the reference compiled unmodified, `tools/csharp-legacy`)

Measured against the loopback oracles (`tools/oracle/results/`). P = priority for a user.

| # | P | C# | Defect | Measured | Us |
|---|---|---|---|---|---|
| S1 | P0 | SPFSService (reconstructed: `long.Parse(AllowThousands)` in the client culture, stated by the task) | The size cell is written in the server's culture and parsed in the phone's. A mismatch throws, SPFSService returns null, and `SPFSPlaylistFolder.GetFilesAsync` then **throws** `ArgumentNullException` on `files.Where` (nothing catches it). | **10 of 20** server x client pairs lose the whole folder (en-US server + de-DE / fr-FR phone; de-DE server + any non-de phone; ...), `legacy.md`. | D6 |
| S2 | P1 | `SPFSRuntimeConfigHandler.cs:71-80` | FullUrl from ServerUrl: `host:port` -> `http://h:p:80`; `localhost:3323` -> `http://:80`; a full URL loses its port (80); blanks kept; bare IPv6 unbracketed; https defaults to port 80. | Each shape run through TestSPFSConnection against a live server: `fullurl.md` (6 shapes that name a reachable server fail in C#, all validate here). | D1 |
| S3 | P1 | `SPFSPlaylistFolder.cs:92, 106` | `size > 0` = file, `size < 1` = folder: a 0-byte file is a phantom folder (opening it lists nothing) and never plays. | `100% & <more>.mp4` shows as a folder in every working pair. | D10 |
| S4 | P1 | SPFSService (anchor `Href`) | The href is `./` + HtmlEncoded name, not URL-encoded; resolving it cuts `#` (a fragment) and decodes `%41` to `A`. | `My Film #1 (2019).mkv` -> `/Media/My%20Film%20`; `%41 literal.txt` -> `/Media/A%20literal.txt` (another file): the recorded PathAndQuery, `legacy_ids.tsv`. | D10, D11 |
| S5 | P2 | `SPFSRuntimeConfigHandler.cs:51, 82` | ServerKey is read and never sent (`IsServerValidAsync(serverUrl, string.Empty, 5000)`). | by reading; the key cannot be enforced by any server | D4 |
| S6 | P2 | SPFSService id | The id hashes PathAndQuery of the URL: a server moving host / port changes every id (library, resume points, watched state). 31-bit. | by construction; `legacy_id` reproduced on 15,255 rows | D8 |
| S7 | P2 | `SPFSPlaylistFolder.cs:95-97`; SPFSService | Failures look like data: a dead server lists an **empty** folder (AngleSharp swallows the error); `/api/Folders` failing makes `GetFoldersAsync` throw `ArgumentNullException` (`null.FromJSONObject`). | both run against 127.0.0.1:1 and a 404 | D13 |
| S8 | P3 | `SPFSRuntimeConfigHandler.cs:34` | `timeout = 5000` is accepted and never used. | by reading | D2 (5 s) |
| S9 | ASSUMED | SPFSService (3 ParseExact formats, not shipped) | Under the reconstruction's formats, en-NZ pages (day <= 12) parse **swapped** (M/d) and zh-CN phones read no date. Whatever the real three formats are, the task states the live format matches none: every live date is lost. | `legacy.md` date column (ASSUMED) | D6 |

## 8. Deliberate divergences from the reference

D1 (FullUrl shapes, https port), D2 (a JSON version string), D3 (validate asks `/api/Folders`;
401 fails it), D4 (the key is sent), D6 (culture-free; ambiguous dates -1), D7 (JSON listing), D8
(host-independent ids), D10 (row class decides the kind), D13 (errors), D14 (wrong-folder check).
The indexer walk (`DelegateMediaCategorizer.slice.cs`: `/api/Folders` keys, then each key as a
directory root) maps to `list("")` then `list("/<key>")` recursively; `spfsc walk` does exactly that.

## 9. Not covered

- The field servers themselves (Windows 2.0.0.0, Linux CLI 3.0.0.0) were not reachable from the
  build sandbox; `tools/oracle/spfs-server` reproduces their surface with ASP.NET Core 8
  (`UseDirectoryBrowser` + `UseStaticFiles`, what the task and the live measurements describe).
- `SPFSService.slice.cs` (see the top): S1 / S4 / S6 follow from the task text; S9 is assumed.
- ICU (Linux .NET) writes en-NZ as `01/12/2023 4:35:33\u202fam`; the live server writes
  `1/12/2023 4:35:33 am` (Windows NLS). Both are fixtures (`en-NZ-*.html`, `en-NZ-live-*.html`).
- A WinHTTP / URLSession `scorpiox_http` backend: the Windows DLL builds (`make win`, no transport);
  the host installs one with `spfsc_set_io` + `spfsc_bind_http`.
- Row 32's real JSON contract: D7 is a proposal until row 32 lands.
