# Testing the platform stub — manual guide

How to start this module (locally or in a container) and exercise it by hand. **Keep this
file in sync** when endpoints, error codes, env vars, seed data, or the Dockerfile change (see
[Maintenance](#maintenance)).

Wire contracts: [`../../contracts.md`](../../contracts.md) §5. Scenario IDs (A-1, S12, …)
refer to [`../spec.md`](../spec.md) §A6 and contracts §7.

A more visual companion, [`TESTING.html`](TESTING.html), sits next to this file — same
content, sticky TOC, collapsible sections, copy buttons. Self-contained (no external
libraries), open it directly in a browser. Regenerate it by hand if this file changes; there
is no committed conversion script yet.

## Prerequisites

| Need | Version | Note |
|---|---|---|
| Node | 20+ | for the **local** run and `npm test` — nothing else, no Java, no SPA |
| a signing key | — | `../../deploy/gen-keys.sh` (run once from the repo; idempotent; see below) |
| Podman | ≥ 4.4 | only if you run the **container** option instead of local Node |
| the PDS (`/account-link/assert` + `/pds-jwks.json`) | — | only needed for a live `POST /account-link/initiate` — `npm test` fakes it, so this is optional for the stub's own test suite. The real PDS exists (`poc-code/pds/`, build step 3+) if you want a live pairing |

---

## Starting the stub

The stub is **stateless config + one signing key** — no database, no other service required
to boot (only two endpoints, `/discover` and `/account-link/initiate`, need a live PDS to
*succeed*; everything else works standalone). Two ways to run it; pick one.

### 0. Generate the signing key (once, either option)

The stub **fails fast** if this is missing — it never auto-generates one, because a fresh key
would silently drift the JWKS a PDS has cached (deploy/spec.md D-2).

`gen-keys.sh` borrows the `jose` package from the stub's own `node_modules` (it has no
dependencies of its own) — **run `npm install` in the stub first**, then:

```bash
cd poc-code/platform/stub && npm install   # if not already done
cd ../../deploy
./gen-keys.sh
```
The script itself runs from **`poc-code/deploy/`** (it `cd`s there internally too, so it's
safe even if your shell is elsewhere). Writes
`poc-code/deploy/keys/platform-signing.jwk.json` (git-ignored, RSA-2048, `kid
platform-poc-1`, stable across restarts). **Idempotent** — if the file already exists it
prints `already exists — leaving it` and exits `0`; delete `poc-code/deploy/keys/` yourself
to deliberately rotate the key.

### Option A — local Node (fastest, for day-to-day iteration)

```bash
cd poc-code/platform/stub
npm install
npm run dev            # tsx watch — auto-reloads on file edit
```
Run from **`poc-code/platform/stub/`**. Boot log prints `issuer=`, `aud=`, `kid=`,
`fixedProviderId=` on `http://localhost:3000`. `Ctrl-C` to stop.

Equivalent non-watch form (what CI / the container also do):
```bash
cd poc-code/platform/stub
npm install
npm run build && npm start
```

### Option B — container (Podman)

The Dockerfile is a standalone multi-stage build (`poc-code/platform/stub/Dockerfile`) — it
does **not** need `podman compose` or the other services to *build* or *start*. It does need
the signing key mounted in, because the key is deliberately **not** baked into the image (see
the comment at the top of the Dockerfile).

**Build** — run from `poc-code/platform/stub/` (the Dockerfile's own directory):
```bash
cd poc-code/platform/stub
podman build -t veritia/web-platform-stub:poc .
```

**Run** — same directory, so the relative key-mount path resolves; the image expects the key
at `/keys/platform-signing.jwk.json` (matches `SIGNING_KEY_PATH` below):
```bash
cd poc-code/platform/stub
podman run --rm -d \
  --name web-platform-stub \
  -p 3000:3000 \
  -v "$(pwd)/../../deploy/keys:/keys:ro" \
  -e SIGNING_KEY_PATH=/keys/platform-signing.jwk.json \
  -e PLATFORM_ISSUER=https://veritia.eu \
  -e PDS_MCP_URI=http://localhost:8081/mcp \
  -e PDS_DISCOVERY_URI=http://localhost:8081/mcp \
  veritia/web-platform-stub:poc
```

Verify, then stop:
```bash
curl -s http://localhost:3000/health          # {"ok":true}
podman logs -f web-platform-stub              # boot log / request log
podman stop web-platform-stub                 # --rm above means it's removed automatically
```

**Rebuild after a code change** — the image is not live-reloading (unlike `npm run dev`); repeat
the `podman build` command above, then `podman stop web-platform-stub` + re-run `podman run`.

**About `PDS_DISCOVERY_URI` / `PDS_ASSERT_URI` above:** they point at `localhost:8081`, which
from *inside* the container is the container itself, not your host — so `/discover` and
`/account-link/initiate` will fail to reach a host-run PDS this way (same failure you'd see
running the PDS on the host today: there's nothing at `:8081` yet either way, build step 3 is
in progress separately). If you need the containerized stub to reach a PDS running on the host
meanwhile, add `--network=host` to the `podman run` command above (Linux only) instead of
`-p 3000:3000`, and drop the port mapping (host networking exposes it directly).

### The full `podman compose` stack (recommended over Option B alone)

`poc-code/deploy/compose.yaml` (three services: `pds-keycloak`, `pds`, `web-platform-stub`) is
**build step 8** ([`../../contracts.md`](../../contracts.md) §0) — written and live-verified
(see `poc-code/demo/testing-guide.md` §2.3, which also doubles as `run-boot.sh`'s own reference).
Starting everything:
```bash
cd poc-code/deploy
./gen-keys.sh                       # once
podman compose up -d --build        # pds-keycloak → (healthy) → pds ; stub in parallel
podman compose ps                   # confirm all healthy
```
**Always pass `--build`.** Without it, compose reuses whatever image is already cached locally
even after you've rebuilt the stub's `dist/` (or the PDS jar) since the last boot — a plain
`up -d` can silently start a container that predates your code change, with no error. This isn't
hypothetical: it's exactly what caused a 2026-10-14 live-test bug where an end-user
`tool_constraints` limit was present in the source and in the request payload but never
enforced, because the running `web-platform-stub`/`pds` containers were stale. The `CREATED`
column from `podman compose images <service>` is **not** reliable evidence either way for this —
reproducible-build layers get a frozen near-epoch timestamp regardless of actual build time; if
behavior looks stale, just rebuild and retry rather than inspecting timestamps.

In this mode the stub's env changes shape too — containers address each other by **service
name** (`PDS_DISCOVERY_URI=http://pds:8081/mcp`, not `localhost`), only the host-facing pieces
(SPA, Outil Local, your browser) keep using `localhost`. See contracts §6 / deploy/spec.md §3
for the full address matrix. Option A or B above are still useful standalone (fast iteration on
the stub alone, without booting the PDS/Keycloak too).

---

## Automated tests

```bash
cd poc-code/platform/stub
npm install
npm run typecheck     # tsc --noEmit
npm test              # node:test via tsx — offline, spins the app on an ephemeral port
```

`npm test` covers every row below plus discovery against a fake MCP server (JSON + SSE),
malformed JSON, unknown routes, and fail-fast on a missing key. It does **not** need the
signing key generated above, or the stub started separately — it's fully self-contained.

## Endpoint reference

`B=http://localhost:3000`. All bodies are JSON. No auth (localhost only).

| # | Call | Purpose | Success | Failure |
|---|---|---|---|---|
| 1 | `GET $B/health` | liveness | `{"ok":true}` | — |
| 2 | `GET $B/jwks.json` | PDS fetches the verify key | `{keys:[{kty:RSA,kid:platform-poc-1,…}]}` (no `d`) | — |
| 3 | `POST $B/discover` `{"mcp_endpoint":"…"}` | server-side `initialize`+`tools/list` | `{fetched_at,tools:[…]}` | `502 {error:"discovery_failed",detail}` — **expected until the PDS MCP route exists** |
| 4 | `POST $B/providers` `{mcp_endpoint,confirmed_tools:[…]}` | finalize registration | `{provider_id,mandate_link,schema_sha256,confirmed_at}` | `400 invalid_registration` |
| 5 | `GET $B/providers/:id` | SPA provider lookup | stored provider record | `404 unknown_provider` |
| 5b | `POST $B/account-link/initiate` `{provider_id,pds_customer_id}` | fetch + verify the PDS-signed assertion, open a link session | `{link_session_id,provider_account_ref,expires_at}` | `400 unknown_provider` · `502 assertion_fetch_failed` (PDS down / bad dev secret) · `422 {error:"assertion_invalid",detail:"sig\|iss\|aud\|exp\|jti_replay"}` |
| 6 | `POST $B/mandates` (body below) | **sign the mandate JWT**, atomically mint a setup code (needs `link_session_id` from 5b) | `{jti,delegation_token,provider_api_endpoint,ready_to_use_config,setup_code,setup_redeem_url,setup_code_expires_at}` | `400` — see codes below |
| 7 | `GET $B/introspect/:jti` | PDS per-call revocation check | `200 {active:true,sub,aud,iat,exp}` | `200 {active:false,reason:revoked\|expired}` · `404 {active:false,reason:unknown_jti}` |
| 8 | `POST $B/mandates/:jti/revoke` | dashboard revoke | `200 {status:"REVOKED",revoked_at}` | `404 unknown_jti` |
| 9 | `GET $B/mandates?itsme_sub=<sub>` | dashboard list + mandate form's collision check (§9.4) | `{mandates:[{jti,aud,purpose,allowed_tools,iat,exp,status,provider_id,agent_label}]}` | `400 {error:"missing_itsme_sub"}` if the param is absent/blank (SPA shows an empty list + error) |
| 10 | `GET $B/audit/:jti` | Trace Plateforme | `{jti,platform_trace:[{ts,event,detail}]}` | unknown ⇒ `platform_trace:[]` |
| 11 | `POST $B/setup-codes/:code/redeem` | `mcp-server setup` (contracts §9) | `{AGENT_DELEGATION_TOKEN,PROVIDER_API_ENDPOINT,agent_label}`, burns the code | `404 unknown_code` (unknown or already redeemed) · `410 code_expired` |

`POST /discover` uses **`POST`** with a JSON body (`{ "mcp_endpoint": "..." }`) per
contracts §5.2 — not the `GET /discover` shown in the architecture mermaid.

### `POST /mandates` body

```json
{
  "provider_id": "9b7c1e40-2f6a-4c11-9e2a-000000000bqt",
  "link_session_id": "<from POST /account-link/initiate>",
  "itsme_sub": "itsme:be:sofie.maes",
  "agent_jwk": {"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"},
  "agent_label": "claude-desktop-sofie",
  "purpose": "consultation de solde",
  "allowed_tools": ["get_balance"],
  "ttl_seconds": 3600
}
```

`agent_jwk` = any Ed25519 **public** JWK (shape only; not cryptographically checked here).
The value above is the RFC 8037 test vector. Real keys come from `outil-local init`.
`provider_account_ref` (value + `provider_jkt` + raw `assertion`) is taken from the link
session — never from `itsme_sub`.

| 400 code | Trigger |
|---|---|
| `unknown_provider` | `provider_id` not registered |
| `unknown_link_session` | `link_session_id` missing or unknown |
| `link_session_expired` | link session older than `LINK_SESSION_TTL_SECONDS` |
| `link_session_provider_mismatch` | link session was opened for a different `provider_id` |
| `unknown_itsme_sub` | `itsme_sub` not one of the 3 seed identities |
| `empty_allowed_tools` | `allowed_tools` missing or `[]` |
| `invalid_agent_jwk` | not `{kty:"OKP",crv:"Ed25519",x:<string>}` |
| `invalid_json` | body is not parseable JSON |

## Happy path (copy-paste)

Needs the PDS up (for `/account-link/assert` + `/pds-jwks.json`). Without it, stop after
registration — `npm test` covers the rest with a fake PDS.

```bash
B=http://localhost:3000

curl -s $B/providers -XPOST -H 'content-type: application/json' -d '{
  "mcp_endpoint":"http://localhost:8081/mcp",
  "confirmed_tools":[{"name":"get_balance","annotations":{"readOnlyHint":true}}]}'

LS=$(curl -s $B/account-link/initiate -XPOST -H 'content-type: application/json' -d '{
  "provider_id":"9b7c1e40-2f6a-4c11-9e2a-000000000bqt",
  "pds_customer_id":"cust-002"}' | grep -o '"link_session_id":"[^"]*"' | cut -d'"' -f4)

RESP=$(curl -s $B/mandates -XPOST -H 'content-type: application/json' -d '{
  "provider_id":"9b7c1e40-2f6a-4c11-9e2a-000000000bqt",
  "link_session_id":"'"$LS"'",
  "itsme_sub":"itsme:be:sofie.maes",
  "agent_jwk":{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"},
  "agent_label":"claude-desktop-sofie","purpose":"consultation de solde",
  "allowed_tools":["get_balance"],"ttl_seconds":3600}')
JTI=$(echo "$RESP"   | grep -o '"jti":"[^"]*"'              | cut -d'"' -f4)
TOKEN=$(echo "$RESP" | grep -o '"delegation_token":"[^"]*"' | cut -d'"' -f4)
REDEEM_URL=$(echo "$RESP" | grep -o '"setup_redeem_url":"[^"]*"' | cut -d'"' -f4)

echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null; echo   # inspect claims
curl -s -XPOST "$REDEEM_URL"               # AGENT_DELEGATION_TOKEN + agent_label; second call -> 404 unknown_code
curl -s $B/introspect/$JTI                 # active:true
curl -s $B/mandates/$JTI/revoke -XPOST     # REVOKED
curl -s $B/introspect/$JTI                 # active:false, reason:revoked
curl -s $B/audit/$JTI                      # MANDATE_ISSUED → ACCOUNT_LINK_VERIFIED → SETUP_CODE_REDEEMED → INTROSPECT_CALLED ×2 → MANDATE_REVOKED
```

Without a live PDS, stop after the first `curl` (`POST /providers`) — the SPA's own
`discovery_failed` / `assertion_fetch_failed` banners are exactly this same gap, surfaced in
the UI instead of a terminal (see `platform/spa/` for that flow).

### Verify the JWT signature (optional)

```bash
node -e '
const j=require("jose");(async()=>{
  const jwks=await (await fetch("http://localhost:3000/jwks.json")).json();
  const key=await j.importJWK(jwks.keys[0],"RS256");
  const {payload,protectedHeader}=await j.jwtVerify(process.argv[1],key,{
    issuer:"https://veritia.eu",audience:"http://localhost:8081/mcp"});
  console.log(protectedHeader,payload);
})();' "$TOKEN"
```
Expect header `{alg:"RS256",typ:"at+jwt",kid:"platform-poc-1"}`.

## Seed data (contracts §4)

The stub holds **no** `itsme_sub → ref` map anymore. `provider_account_ref` comes from the
PDS assertion; the PDS owns `pds_customer_id → ref`:

| `pds_customer_id` | `provider_account_ref.value` | demo-paired itsme `sub` |
|---|---|---|
| `cust-001` | `pacr_bqt_7f3a91` | `itsme:be:pieter.janssens` |
| `cust-002` | `pacr_bqt_2c8d40` | `itsme:be:sofie.maes` |
| `cust-003` | `pacr_bqt_9b1e05` | `itsme:be:noah.dubois` |

Fixed demo `provider_id`: `9b7c1e40-2f6a-4c11-9e2a-000000000bqt`.

## Config (env)

| Var | Default | Container equivalent |
|---|---|---|
| `PORT` | `3000` | same |
| `PLATFORM_ISSUER` | `https://veritia.eu` | same |
| `PDS_MCP_URI` | `http://localhost:8081/mcp` | **same** in `deploy/compose.yaml` — it is the token `aud` identifier, not a routing address (contracts §6); only `PDS_DISCOVERY_URI` uses the compose name `http://pds:8081/mcp`. *(Corrected 2026-11-30 — this cell used to say the compose value was `http://pds:8081/mcp`.)* |
| `PDS_DISCOVERY_URI` | `http://localhost:8081/mcp` | `http://pds:8081/mcp` in `deploy/compose.yaml` |
| `SIGNING_KEY_PATH` | `../../deploy/keys/platform-signing.jwk.json` | `/keys/platform-signing.jwk.json` — mounted, see Option B above |
| `FIXED_PROVIDER_ID` | the fixed UUID above; set empty ⇒ random per registration | same |
| `MANDATE_LINK_BASE` | `http://localhost:4200/mandate/new` | same (SPA always runs on the host) |
| `PDS_ASSERT_URI` | `http://localhost:8081/account-link/assert` | `http://pds:8081/account-link/assert` in `deploy/compose.yaml` |
| `PDS_ASSERTION_JWKS_URI` | `http://localhost:8081/pds-jwks.json` | `http://pds:8081/pds-jwks.json` in `deploy/compose.yaml` |
| `PDS_ASSERT_DEV_SECRET` | `poc-dev-secret` | same — must match the PDS's own env |
| `LINK_SESSION_TTL_SECONDS` | `600` | same |

## Troubleshooting

| Symptom | Cause / fix |
|---|---|
| `FATAL: signing key not found` | run `../../deploy/gen-keys.sh` (Option A), or check your `-v` mount path (Option B) |
| `/discover` → `502 discovery_failed` | normal — no PDS MCP route yet (step 4) |
| `/account-link/initiate` → `502 assertion_fetch_failed` | PDS not up, or `PDS_ASSERT_DEV_SECRET` mismatch between stub and PDS |
| `/account-link/initiate` → `422 assertion_invalid` | PDS assertion `sig`/`iss`/`aud`/`exp` wrong, or the `jti` was already used (`jti_replay`) |
| JWT `kid` changed after restart | you regenerated the key — delete `../../deploy/keys/` only to rotate on purpose |
| state empty after restart | by design (in-memory) — re-run registration + mandate |
| `invalid_json` on a valid-looking body | missing `-H 'content-type: application/json'` |
| `podman build` succeeds but `podman run` container exits immediately | check `podman logs web-platform-stub` — almost always the missing-key fail-fast above |
| container can't reach a host-run PDS at `:8081` | expected with the default bridge network + `-p 3000:3000`; add `--network=host` (see Option B), or use the full compose stack above, which networks the stub and PDS together |
| edited `src/` but the container still runs old code | the image is a build artifact, not a live mount — re-run `podman build` then restart the container |
| `podman: command not found` | Podman isn't installed here — use Option A (local Node) instead, or see architecture.md §12.0 for the install |

## Maintenance

Update this file in the **same change** that touches:

| Change | Update here |
|---|---|
| add/remove/rename an endpoint | Endpoint reference table + Happy path |
| new/changed error code | the relevant code table |
| new env var or default | Config table (both columns) |
| Dockerfile (base image, build stages, exposed port, entrypoint) | Option B |
| `deploy/compose.yaml` changes (service names, ports, env) | the "full `podman compose` stack" section — keep the address-matrix pointer |
| seed identity / account-ref / fixed IDs | Seed data table |
| new failure mode worth knowing | Troubleshooting |
