# Integration guide

How the packages fit into an issuer, a browser checkpoint, an Expo app and an OpenID4VP provider, what each of them must
keep, and the HTTP endpoints a server has to expose. The formats are in the [profile](profile-v1.md), the guarantees and
their limits in the [security model](security-model.md).

Two rules hold everywhere:

- **Time is an input.** Every call that depends on time takes `now` in seconds since 1970; no package reads a clock. The
  integrator supplies it, and the verifier's clock must be right for freshness and lifetimes to mean anything.
- **One replay store per deployment.** All verifications of one deployment share one `ReplayStore`
  ([section 6](#6-one-replay-store-for-the-whole-deployment)).

| Role                        | Packages                                                                | Runtime                                      |
| --------------------------- | ----------------------------------------------------------------------- | -------------------------------------------- |
| Issuer service              | `@umis/issuer`, `@umis/status-list`, `@umis/registry`, `@umis/core`     | Node 22.13 or later                          |
| Checkpoint in a browser     | `@umis/verifier`, `@umis/policy`, `@umis/gateway`, `@umis/core`         | modern browsers                              |
| Holder and verifier app     | `@umis/wallet-rn`, `@umis/wallet`, `@umis/verifier`, `@umis/transports` | Expo SDK 58 (Expo Go or a development build) |
| OpenID4VP provider          | `@umis/verifier/oid4vp`, `@umis/registry`, `@umis/status-list`          | Node or any server runtime with WebCrypto    |
| Relay emulator, demo, bench | `@umis/cli`, `@umis/gateway/node`, `@umis/testkit`                      | Node                                         |

## 1. A Node issuer

1. **Keys.** `generateSigner()` makes a P-256 key in WebCrypto; `importSigner(jwk)` loads one you keep elsewhere. Keep
   private keys outside the repository and refer to them by the names of environment variables or secrets, never by
   value. `umis keygen --out <dir>` writes a key pair for tests and stations.
2. **Credentials.** `issueOrgMember` and `issueRoleAuthority` sign SD-JWT VCs bound to the holder key (`cnfJwk`), with a
   status entry `{uri, idx}`; `randomStatusIndex` picks a free index that says nothing about the holder.
   `issueDelegated` signs a delegated credential, which can never be wider than its parent.
3. **Status lists.** `buildStatusListToken({ signer, uri, bits, values, iat, ttlSeconds })` signs a list with one status
   per entry of `values`; serve the token at its URI and sign a new one at least every Δ. Revoking means setting the
   entry to `STATUS.INVALID` and publishing a newer list; `cascadeRevocation` lists the delegated credentials to revoke
   with their parent.
4. **Trust.** A verifying organisation trusts you only through an entry in its own registry
   `{issuer, name, jwks, vcts, statusLists, status}`, signed by its administrator with `signRegistry` and read by its
   devices with `parseRegistry(snapshot, adminPublicKey)`. Within one organisation, `selfEntry` builds the entry of the
   organisation's own issuer.

**Endpoints of an OpenID4VCI 1.0 issuer** (pre-authorized code flow, the one `@umis/wallet` implements):

| Endpoint                                                                                               | Content                                                                      | From the SDK                                                                   |
| ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| the offer, as a QR code or link                                                                        | `openid-credential-offer://?credential_offer=…` or `…_uri=…`                 | `createCredentialOffer`, `credentialOfferUri`, `credentialOfferUriByReference` |
| `/.well-known/openid-credential-issuer`                                                                | credential issuer metadata                                                   | `credentialIssuerMetadata`                                                     |
| `/.well-known/oauth-authorization-server` of the issuer, or of the first `authorization_servers` entry | `token_endpoint`                                                             | your server                                                                    |
| token endpoint                                                                                         | exchanges the pre-authorized code (and transaction code) for an access token | your server: codes are single use                                              |
| nonce endpoint                                                                                         | a fresh `c_nonce`, used once                                                 | your server                                                                    |
| credential endpoint                                                                                    | checks the key proof, issues the credential                                  | `verifyKeyProof`, then `issueOrgMember` or `issueRoleAuthority`                |
| `/.well-known/jwt-vc-issuer`                                                                           | SD-JWT VC issuer metadata: keys inline, `umis_status_lists`                  | `jwtVcIssuerMetadata`                                                          |
| each status list URI                                                                                   | the `statuslist+jwt` token                                                   | `buildStatusListToken`                                                         |

The wallet side is `resolveOffer(uri)` followed by `redeemOffer(view, txCode, signer, { now })`. Every address must be
`https` (`http` only on the local machine), and the wallet refuses redirects.

## 2. A checkpoint in a browser

A checkpoint decides from what it holds: its registry, the status lists of the issuers it trusts, its policy, a member
cache for one-way tokens, a replay store and, for authority checks, a ledger. Refresh the registry and the status lists
whenever the device is online; the decision stays offline.

```ts
import { createMemoryReplayStore, verifyAtCheckpoint } from '@umis/verifier';

const replay = createMemoryReplayStore(); // one store for every decision of this station
const result = await verifyAtCheckpoint(scannedText, {
  now: Math.floor(Date.now() / 1000), // the station's clock, given as an input
  audiences: [ownIssuer], // the audiences a one-way token may name
  policy, // a CheckpointPolicyV1, for example DEFAULT_POLICIES.door_low from @umis/policy
  trusted, // entries from parseRegistry
  statusLists, // Map of uri -> { token, fetchedAt }
  memberCache, // Map of credential jti -> memberCacheEntryFromCredential(...), for one-way tokens
  replay,
});
// result.decision is 'accept' or 'reject'; result.reasons holds exactly one code; result.trace the nine steps
```

- **QR scanning** is up to the page: any library that returns the text of the code. Every frame of the
  [benchmark run](benchmarks.md) is under 2 000 characters.
- **Saving the context.** `serializeVerifierContext(context)` gives a JSON value without the replay store;
  `deserializeVerifierContext(saved, { replay, now })` restores it.
  [`examples/browser-verify`](../examples/browser-verify) is a Vite page that decides on a pasted frame this way.
- **A door.** `createGateway({ context: () => context, relay, now: () => seconds })` decides on each scanned text and,
  only on accept, asks the relay to open. The relay client is
  `shellyRpcRelay({ url: '<origin>/rpc', relayAud: '<origin>', signer, iss })`, where `signer` is the station's key; the
  relay trusts its public key (`umis relay-emu --trust station.public.jwk.json`). A relay that fails or does not answer
  never changes the decision.
- **Reverse QR** (medium class): `createRequestQr` shows a request, the holder's wallet answers with a response QR code,
  and `verifyResponseQr(answer, pending, context)` decides on it.

## 3. An Expo app

`@umis/wallet-rn` connects the wallet to the phone. Run this once at start-up, at the very top of the entry file and in
this order, before any other call of the SDK:

```ts
import { isRunningInExpoGo } from 'expo';
import * as ExpoCrypto from 'expo-crypto';
import { createKeyStore, installRnPolyfills, setupCrypto } from '@umis/wallet-rn';

installRnPolyfills();
setupCrypto({ getRandomValues: ExpoCrypto.getRandomValues });
export const keys = createKeyStore(isRunningInExpoGo() ? 'expo_go' : 'dev_client', { authenticate });
```

`authenticate(prompt)` shows the biometric prompt and resolves to `true` only when the person was recognised.

|                 | Expo Go                                    | Development build                                          |
| --------------- | ------------------------------------------ | ---------------------------------------------------------- |
| Holder keys     | software keys in the device's secret store | Secure Enclave, StrongBox or TEE where the device has them |
| Biometric check | `authenticate` before every signature      | enforced by the secure hardware                            |
| Native modules  | none beyond Expo Go's                      | the optional `@animo-id/expo-secure-environment`           |

`createCredentialStore()` keeps credentials in the device's secret store. With the credential and the key in hand, the
app presents with `@umis/wallet`: `createOneWayQr` and `createFullQr` for a door, `parseRequestQr` and
`createResponseQr` to answer a request, `respondToVpRequest` for a login. As a verifier, the same app uses
`createRequestQr` and `verifyResponseQr`, and `verifyCounterparty` in a mutual exchange. Over Bluetooth the frames go
through a `PresentationTransport` ([`@umis/transports`](../packages/transports/README.md)).

## 4. OpenID4VP login with your own provider

A relying party signs a person in with a credential through its OpenID provider. The provider exposes two things: a page
that shows the request as a QR code or deep link, and a `direct_post` response endpoint at its `responseUri`. The
sequence of the hero scenario's login (step 4, in [`packages/testkit/src/hero.ts`](../packages/testkit/src/hero.ts)):

1. **The provider builds the request** (`loginRequest`):
   `createVpRequest({ responseUri, nonce, state, dcql, clientName })` with
   `dcql = umisDcqlQuery({ vcts: [VCT.orgMember], claims: policy.requestedClaims })`, which asks for the
   organisation and the role. The request travels by value as `walletUri` (`openid4vp://?…`); its client id is
   `redirect_uri:` followed by `responseUri`. The provider keeps `nonce`, `state` and `requestObject.client_id`.
2. **The wallet reads it** (`answerLogin`): `parseVpRequest(walletUri)` returns what to show the holder. When it carries
   no `clientName` (a name with control characters or above 200 characters is dropped), the app must show the host of
   `responseUri` instead.
3. **The wallet answers** (`answerLogin`, `postedLogin`):
   `respondToVpRequest({ walletUri, sdJwtVc, disclose, signer, now })` posts the form
   `vp_token={"<query id>":["<presentation>"]}&state=…` to `responseUri`, without following redirects.
4. **The provider decides** (`decideLogin`):
   `verifyVpResponse({ body, nonce, state, audience: client_id, trusted, fetchStatusList, now, policy, replay })`. The
   claims named in `policy.requestedClaims` must be disclosed, the key binding must carry the client id and the nonce
   and be at most 120 seconds old, and the nonce is accepted once.
5. **The provider answers the post**: `200` with `{"redirect_uri": "https://…"}` on accept, `400` otherwise. The wallet
   returns `{ status, redirectUri }`; `redirectUri` is set only for a 2xx JSON answer whose address is `https` (or
   `http` on `localhost` or `127.0.0.1`), and the app continues there.

In the hero run (`loginAtIntranet`) the provider is a function in the same process that stands where the HTTPS endpoint
would be: it is the `fetch` the wallet posts to, and nothing leaves the process. Two tests of
[`packages/testkit/test/hero.test.ts`](../packages/testkit/test/hero.test.ts) pin the contract: "accepts an answer once,
only for its own request, and only while it is fresh" (a second answer with the shared store is REPLAY) and "answers the
wallet with 400 and no address to continue at when it rejects the presentation". The wallet-to-provider round trip with
the real functions on both sides is in
[`packages/transports/test/transports.test.ts`](../packages/transports/test/transports.test.ts).

Limits a provider should know: the nonce is 22 to 256 base64url characters (16 random bytes or more), `state` at most
512 characters, `clientName` at most 200 characters without control characters, `responseUri` `https` (or `http` on the
local machine) without a fragment, and a `vp_token` above 65 536 characters is not read. The details are in the
[`@umis/verifier` README](../packages/verifier/README.md#openid4vp) and the
[`@umis/wallet` README](../packages/wallet/README.md#openid4vp).

## 5. A mutual exchange

Two holders show each other their roles (medium class). The initiator calls
`createRequestQr({ …, mutual: { sdJwtVc, disclose, holderSigner } })`; the other side reads it with `parseRequestQr`,
decides on the initiator with `verifyCounterparty(request, context)` and answers with `createResponseQr`; the initiator
decides with `verifyResponseQr(answer, pending, context)`. The opening's nonce is accepted once (`mutual:<nonce>`).

## 6. One replay store for the whole deployment

Single use (invariant [I-2](security-model.md#i-2) and its neighbours) holds only when `verifyAtCheckpoint`,
`verifyResponseQr`, `verifyCounterparty`, `verifyVpResponse` and `verifyRelayCommand` of one deployment all receive the
same `ReplayStore`. Without a `replay` store, `verifyVpResponse` remembers nothing across calls. The store holds these
ids: `ow:` (one-way tokens), `kb:` (full presentations), `req:` (answers to requests), `mutual:` (mutual exchanges),
`vp:<nonce>` (OpenID4VP responses) and `relay:<jti>` (relay commands).

`createMemoryReplayStore()` serves one process. It holds at most 100 000 ids that have not expired and refuses new ids
while it is full; a store created without `now` learns the time from the verification calls that use it. Several
processes or devices that must not accept the same presentation twice need one store they share: any object with
`checkAndRemember(id, expiresAt)` that answers `true` the first time and `false` afterwards.

## 7. The relay emulator

`umis relay-emu` (from `@umis/cli`) stands in for a Shelly Gen3 relay with one switch, so a door can be shown without
hardware:

```sh
pnpm -F cli exec umis keygen --out .tmp/station
pnpm -F cli exec umis relay-emu --trust .tmp/station/key.public.jwk.json --cors http://localhost:5173
```

It serves a status page at `/` and JSON-RPC at `POST /rpc`, opens only for a `Switch.Set` with a valid signed command,
and by default accepts commands for `urn:umis:relay:emu` and its own addresses. The options, exit codes and status
members are in the [`@umis/cli` README](../packages/cli/README.md#relay-emulator); `startShellyEmulator` from
`@umis/gateway/node` runs the same emulator inside a Node program.
