# Trap 4. eID sign-in. Read the whole file before the first line of auth code

This is where every application breaks. Not "often" — every one. The reason is that the
wallet's behaviour differs from what the protocol says, and that divergence is **not described
in the official documentation**.

What follows is measured behaviour, not a retelling of the specification.

---

## How sign-in actually works

```
                 ┌──────────────┐
  1. opened      │  The person's │
     the app     │   browser     │
                 └──────┬───────┘
                        │ 2. GET /api/auth/offer
                        ▼
                 ┌──────────────┐   issues a session (a random id)
                 │ Your server  │   and a link w3ds://auth?redirect=…&session=…
                 └──────┬───────┘
                        │ 3. a QR code (on a computer) or a link (on a phone)
                        ▼
                 ┌──────────────┐
                 │  The wallet  │ 4. the person approves
                 │on their phone│ 5. the wallet SIGNS the session string
                 └──────┬───────┘
                        │ 6. posts {w3id|ename, session, signature}
                        ▼            to the address from redirect=
                 ┌──────────────┐
                 │ Your server  │ 7. verifies the signature via registry and eVault
                 │              │ 8. creates a session, issues a token
                 └──────────────┘
```

Item 5 is literal: **what is signed is the bare `session` string**, with no prefix, no JSON, no
wrapper. If you sign or verify anything else the signature will not match, and you will spend a
week looking for a bug in cryptography that is not there.

---

## Four measured facts that break everything

### Fact 1. The wallet returns the person to its own hard-coded path

When the wallet and the browser are on the **same device** (the person opened the application
on their phone), the wallet returns the person to the browser after approval — and opens
**`/deeplink-login`** in your application. Not the address you passed in `redirect=`. Its own
hard-coded path.

**So you must have a page at `/deeplink-login`.** Without it the person lands on "page not
found" and sign-in is dead. This is cause number one of every "it doesn't work on iPhone".

The `redirect=` parameter is still required and must still point at `/api/auth/login` — that is
where the wallet posts the signed data, server to server. Do not conflate the two returns: the
data goes to `redirect=`, the person goes to `/deeplink-login`.

### Fact 2. The wallet arrives sometimes by GET, sometimes by POST

Different wallet builds behave differently. The `/api/auth/login` handler must accept both
methods and read parameters from the body **and** from the query string. Answer `OPTIONS` too,
and send CORS headers on the POST response, not only on the preflight.

Register every known return path, each for GET and POST:

```
/api/auth   /api/auth/callback   /auth/callback   /deeplink-login   /callback
```

A path you do not handle dead-ends into your HTML auth gate, which bounces the person to the
sign-in page — which is exactly how same-device sign-in fails while every service is healthy.

### Fact 3. The field is called `w3id` sometimes and `ename` other times

Accept both:

```ts
const ename = req.body.w3id ?? req.body.ename ?? req.query.w3id ?? req.query.ename;
```

### Fact 4. On a phone, a long-lived connection to the server is severed

On a computer it is convenient to hold an SSE connection open and wait for the server to say
"signed in". On a phone that does not work: while the person is in the wallet the browser
suspends the tab and the connection dies. Coming back, the person sees an eternal "waiting".

So on a phone you need **polling**, not a held connection.

---

## What to build: five parts

None can be dropped. Each closes its own scenario.

### Part 1. Issuing the offer — `GET /api/auth/offer`

```ts
const sessionId = randomUUID();
const baseUrl = process.env.PUBLIC_BASE_URL;          // the public address, see trap 3
const redirectUrl = new URL("/api/auth/login", baseUrl).toString();
const offer = `w3ds://auth?redirect=${redirectUrl}&session=${sessionId}&platform=<name>`;
res.json({ offer, sessionId });
```

Remember the session on the server (in memory is enough) — the result is looked up by it later.

`platform` needs no registration: any string works, the wallet renders it on the consent screen
and validates nothing. It is a label, not a credential — see `traps/01-access-model.md`.

### Part 2. Receiving the signature — `/api/auth/login`, GET and POST

1. Pull out `ename` (or `w3id`), `session`, `signature`.
2. **If a result for this session is already cached, return it and stop.** This is not an
   optimisation: the return page may call here a second time, and without the cache the second
   call fails and the person sees an error *after* a successful sign-in.
3. Verify the signature (below).
4. Create the user if they do not exist yet; issue a token.
5. Put the result in the cache under `session` **and** notify anyone waiting (SSE).

Signature verification, step by step:

```
registry: GET /resolve?w3id=@<ename>       → the person's eVault address
eVault:   GET /whois  (X-ENAME header)     → keyBindingCertificates[]
registry: GET /.well-known/jwks.json       → the keys those certificates verify against
          verify the JWT, take the public key, verify the signature over the session string
```

Four things people trip over:

- **An empty `keyBindingCertificates` array is a refusal, not "we'll check later".** An empty
  list means the identity has no bound key, so nothing can be verified and the only sound
  answer is no. The reference implementation returns `valid: true` in that case, which means
  **any string at all signs in as any eName whose vault has no bound key**. Check this line in
  your own code before anything else in this file.
- The public key arrives in different shapes: `0x`-prefixed hex (65 bytes, starting `0x04`, an
  uncompressed SEC1 point) or SPKI DER (starting `0x30`). Decode by content, support both.
- The signature arrives either raw 64 bytes (r‖s), or base64, or multibase base58 (`z…`), or
  DER. Support them all.
- A key-binding certificate **expires in about an hour**. Honour `exp`, and match
  `payload.ename` against the eName being authenticated — a valid certificate for a different
  subject proves nothing about this sign-in.

A working, tested implementation: `api/src/lib/signature-validator.ts` in the `w3ds_casco`
template — copy it whole, do not rewrite it.

### Part 3. Session state — `GET /api/auth/status?session=<id>`

Three possible answers: `pending`, `success` (here is the token and the user), `expired` (no
such session). This is what the phone polls, about every 1.5 seconds for roughly a minute.

### Part 4. The sign-in screen

On a computer: a QR code containing the `offer`, plus an SSE subscription.

On a phone: a **tappable link** straight to the `offer` — not a QR, since there is nothing to
scan with; the wallet is on this same device.

And the thing everyone forgets: **before handing control to the wallet, save the `sessionId`
in `localStorage`.** When the person comes back, the return page may receive no parameters at
all, and then the only way to know which session to ask about is what you saved in advance.

Plus a check when focus returns, in case the wallet brought the person back to the same tab
rather than to `/deeplink-login`:

```js
document.addEventListener('visibilitychange', onVisible);
window.addEventListener('focus', onVisible);
// onVisible: if a sessionId exists, ask /api/auth/status once
```

### Part 5. The return page — `/deeplink-login`

The one the wallet brings the person to. Its logic:

1. **If the address carries `ename`/`w3id`, `session` and `signature`** — relay them to
   `/api/auth/login` yourself and sign the person in.
2. **If there are no parameters** — take `sessionId` from `localStorage` and **poll
   `/api/auth/status`** every 1.5 seconds for about a minute.
3. If nothing after a minute — show a comprehensible error and a "back to sign-in" link.

Look for parameters both in `?query` and after `#` — both were observed:

```js
let search = window.location.search;
if (!search && window.location.hash.includes('?')) {
  search = window.location.hash.slice(window.location.hash.indexOf('?'));
}
```

In the GET flow, **serve HTML rather than a 303**: in-app webviews handle a rendered page with
an explicit navigation far more reliably than a redirect chain.

A working implementation: `app/src/views/DeeplinkLogin.jsx` in the `w3ds_casco` template.

---

## What the wallet counts as success, and how to fail safely

**The HTTP status, and nothing else.** No particular JSON shape is required.

The status on failure matters too:

- **4xx** → the wallet gives up and shows *Authentication failed. Please try again.*
- **503** → the wallet retries by itself.

So: the registry and eVault answer 429/502/503 under load, and real backoffs reach tens of
seconds. **A transient upstream failure must not close the session.** Leave it `pending` and
answer **503**, so the wallet retries. Rejecting on a 429 blames the owner's signature for
someone else's traffic and sends them back to rescan the QR.

---

## Common symptoms and what they mean

| What the person sees | Almost certainly |
|---|---|
| "Page not found" on the phone after the wallet | there is no `/deeplink-login` page |
| Eternal "waiting for confirmation" on the phone | no status polling; SSE died while they were in the wallet |
| Eternal "waiting" on a computer too | the wallet could not reach the server: a `localhost` address, or the tunnel went down |
| "Invalid signature" | you are verifying something other than the bare `session` string, or you did not support the encoding |
| "No key certificates" | the identity has no bound key; this is a correct refusal, not your bug |
| Signed in, then an error | the return page called `/api/auth/login` a second time and there is no result cache |
| Worked yesterday, not today | the tunnel restarted and got a new address |
| *Authentication failed* with everything healthy | the session expired while you were reading code — they are short-lived |

---

## The check that closes this gate

Both scenarios, by a live person's own hands, not by your description:

**Scenario A — from a computer.** Opened the application on a computer → saw the QR → scanned
it with the phone → approved in the wallet → **ended up inside the application on the
computer**.

**Scenario B — from a phone.** Opened the application **in the phone's browser** → tapped the
sign-in button → the wallet opened → approved → **came back to the browser and ended up inside
the application**.

Scenario B is the one that works for nobody first time. If it passed on the first attempt,
check again: close the tab, open it fresh, repeat. It has to work every time, not one in three.

Only after two green scenarios do you start building what all of this was for.
