# UMIS profile v1

This document specifies the UMIS profile v1 (`PROFILE_ID = "umis-v1"`): the credentials, presentations, frames, status
lists, trust rules and decisions that the SDK produces and accepts. It is the reader's form of the constants and types
in [`packages/core/src/profile.ts`](../packages/core/src/profile.ts), [`types.ts`](../packages/core/src/types.ts) and
[`reasons.ts`](../packages/core/src/reasons.ts); where the two differ, the code and the [test vectors](../test-vectors)
win.

The key words MUST, MUST NOT, SHOULD and MAY are to be read as described in RFC 2119 and RFC 8174 when, and only when,
they appear in capitals.

## 1. Building blocks

| Standard                                   | Use in the profile                                                    |
| ------------------------------------------ | --------------------------------------------------------------------- |
| RFC 7515, RFC 7518                         | compact JWS, ES256 only, signature as 64-byte `r‖s`                   |
| RFC 9901 (SD-JWT)                          | selective disclosure, key-binding JWT                                 |
| SD-JWT VC draft-22 (profile pinned at -19) | credential format `dc+sd-jwt`; no change between the two affects UMIS |
| Token Status List draft-21                 | revocation and suspension (`statuslist+jwt`)                          |
| OpenID4VCI 1.0                             | credential offer and key proof                                        |
| OpenID4VP 1.0                              | login and online presentation, a strict subset (section 10)           |
| RFC 9285 (Base45), RFC 1951 (deflate)      | QR frames                                                             |
| RFC 8785 (JCS)                             | canonical JSON of decision events                                     |
| RFC 7638                                   | JWK thumbprints                                                       |

## 2. Cryptography and JWS

- Every signature MUST be ES256 (P-256 with SHA-256) in compact serialization; the signature MUST be the 64 bytes `r‖s`
  (RFC 7518, section 3.4). Selective-disclosure digests use `_sd_alg = "sha-256"`.
- A verifier MUST accept a signature whose `s` is in either half of the curve order (low-S and high-S). WebCrypto and
  secure hardware produce both, so a JWS signature is malleable: an identifier MUST NOT be derived from signature bytes
  (see [security model, I-15](security-model.md#i-15)).
- A JWS MUST carry exactly the `typ` of its kind (table below) and MUST NOT carry `crit` or a header member the kind
  does not define. Signatures go through a `CryptoProvider` (WebCrypto by default, `@noble/curves` as an opt-in).

| `typ`                  | Signed by                                                               | Payload                                              | Verified with                                            |
| ---------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------- |
| `dc+sd-jwt`            | issuer key (`kid`)                                                      | section 3                                            | `jwks` of the issuer's registry entry                    |
| `kb+jwt`               | holder key                                                              | `{iat, aud, nonce, sd_hash}` (RFC 9901, section 4.3) | `cnf.jwk` of the credential                              |
| `statuslist+jwt`       | issuer key                                                              | `{sub, iat, exp?, ttl?, status_list: {bits, lst}}`   | the entry whose `statusLists` holds `sub`                |
| `openid4vci-proof+jwt` | holder key (`jwk` header)                                               | `{aud, iat, nonce}` (OpenID4VCI 1.0, appendix F.1)   | the embedded `jwk`                                       |
| `umis-ow+jwt`          | holder key (no `kid`)                                                   | `{cred_ref, aud, iat, exp, ctr}`                     | `cnfJwk` of the verifier's member cache entry            |
| `umis-req+jwt`         | verifier device key, or the initiator's holder key in a mutual exchange | `PresentationRequestPayloadV1`                       | the verifier's known keys, or the initiator's credential |
| `umis-policy+jwt`      | administrator key of the owning organisation                            | `{iss, sub, ver, iat, policy}`                       | the owner's keys                                         |
| `umis-registry+jwt`    | administrator key of the owning organisation                            | `RegistrySnapshotV1`                                 | the owner's keys                                         |
| `umis-event+jwt`       | verifier device key                                                     | `DecisionEventV1`                                    | the device key                                           |
| `umis-relay-cmd+jwt`   | station or gateway key                                                  | `{iss?, aud, iat, exp, jti, bh}` (section 8)         | the keys a relay trusts                                  |

## 3. Credentials

A UMIS credential is an SD-JWT VC with the header `{"typ":"dc+sd-jwt","kid":<issuer key id>,"alg":"ES256"}`.

**Plain claims** (always visible, never disclosable): `iss`, `sub` (a pairwise pseudonym of the person), `jti`, `iat`,
`exp` (the lifetime T), optional `nbf`, `vct`, `cnf.jwk` (the holder key), `status.status_list {idx, uri}`, `_sd_alg`
and `_sd`.

**Disclosable claims** (`DISCLOSABLE_CLAIMS`): `org {id, name, lei?}`, `org_unit {id, name}`, `role {code, name}`,
`authority` (a list of items), `delegation {depth, max_depth, parent?}` and `display {name, photo_hash?}`. Each claim
that is present MUST be one object-property disclosure (RFC 9901, section 4.2.1); array-element, recursive and decoy
disclosures MUST NOT be used.

| Type                | `vct` constant (`@umis/core`) | Required claims                                              | Optional claims               |
| ------------------- | ----------------------------- | ------------------------------------------------------------ | ----------------------------- |
| organisation member | `VCT.orgMember`               | `org`                                                        | `org_unit`, `role`, `display` |
| role and authority  | `VCT.roleAuthority`           | `org`, `role`, `authority` (at least one item), `delegation` | `org_unit`, `display`         |

The type metadata of both types is published in [`packages/issuer/type-metadata`](../packages/issuer/type-metadata). An
authority item is `{action, resource, limit: {amount, unit, per?}, object?, valid_until?}`, where `per` is one of
`shift`, `day`, `week`, `month` and `operation`.

## 4. Presentations and channels

A verifier decides on a presentation in nine steps, `parse`, `issuer_trust`, `issuer_signature`, `holder_binding`,
`validity`, `status`, `policy`, `authority` and `decision`, and returns `accept` with the reason `OK` or `reject` with
exactly one reason code (section 11). The channel is part of every result.

| Channel      | What the holder shows                                                           | Risk classes |
| ------------ | ------------------------------------------------------------------------------- | ------------ |
| `qr_oneway`  | a one-way token for a credential the verifier already holds in its member cache | low only     |
| `qr_full`    | the credential with its disclosures and a key-binding JWT, as a QR code         | low          |
| `qr_reverse` | an answer to the verifier's request QR code (and the mutual exchange)           | low to high  |
| `ble`        | the same frames as bytes over the UMIS-BLE v1 service                           | low to high  |
| `oid4vp`     | an OpenID4VP 1.0 response posted to the verifier                                | all          |

**One-way token.** Header `{"alg":"ES256","typ":"umis-ow+jwt"}`, payload `{cred_ref, aud, iat, exp, ctr}`: `cred_ref` is
the `jti` of the credential, `aud` the issuer of the holder's own organisation unless the wallet names another audience,
`exp − iat` MUST NOT exceed 30 seconds and `ctr` counts up from a random start. It is signed by the holder key of the
credential. A verifier MUST accept it only for a credential in its member cache (`MemberCacheEntry`, `credRef = jti`),
only when `aud` is one of its `audiences`, and only once.

**Full presentation.** The credential with the disclosures the holder chose and a key-binding JWT with a fresh 16-byte
nonce of the holder and the audience the wallet names (the issuer of the credential by default). The key-binding JWT
MUST be at most `oneWayTokenMaxAgeSeconds` of the policy old, which is at most 30 seconds.

**Request and response.** A request is an `umis-req+jwt` with `PresentationRequestPayloadV1`:
`{v: 1, nonce, aud, iat, exp, vct, claims, authority?, policy?, verifier?, mutual?}`; `nonce` MUST be at least 16 random
bytes as base64url and `exp − iat` MUST NOT exceed 120 seconds. A request that asks for `authority` MUST also ask for
`delegation`. The response is the holder's SD-JWT with a key-binding JWT
`{iat, aud: request.aud, nonce: request.nonce, sd_hash}`. Each request is good for one answer; asking again means a new
request.

**Mutual exchange.** The opening frame holds a request with `mutual: true`, signed by the initiator's holder key, and
the initiator's own presentation, whose key-binding JWT carries `aud = "umis:mutual"` and the nonce of that request and
is at most 30 seconds old. The reply is a response to that request.

**Disclosure.** A wallet MUST NOT disclose a claim the request does not ask for and MUST NOT present a credential of a
type the request does not accept. A holder who discloses `authority` also discloses `delegation` when the credential has
it and the request asks for it.

## 5. Frames

QR texts and BLE messages carry the same container:

- Text: `FRAME_PREFIX[kind]` + base45(deflate-raw(container), level 9) + `"."`. Only QR alphanumeric characters
  (`0-9 A-Z space $ % * + - . / :`) are allowed, at most 4 296 characters (QR version 40-L). A decoder trims surrounding
  whitespace and then requires the terminator.
- Bytes (BLE): one byte `FRAME_KIND_CODE[kind]` + deflate-raw(container).
- `container = 0x01 ‖ varint n ‖ n × (varint len ‖ packedToken)`, varint being unsigned LEB128 of at most 3 bytes.
- `packedToken` is `1 seg seg seg` for a JWS, or `2 seg seg seg ‖ varint d ‖ d × seg ‖ hasKb ‖ [seg seg seg]` for an
  SD-JWT; `seg = varint len ‖ base64url-decoded bytes`. A producer MUST refuse base64url that is not canonical, so that
  unpacking gives back every token byte for byte.

| Kind           | Prefix    | Code | Tokens                    |
| -------------- | --------- | ---- | ------------------------- |
| `oneway`       | `UMIS1O:` | 1    | `umis-ow+jwt`             |
| `full`         | `UMIS1F:` | 2    | SD-JWT+KB                 |
| `request`      | `UMIS1R:` | 3    | `umis-req+jwt`            |
| `response`     | `UMIS1P:` | 4    | SD-JWT+KB                 |
| `mutual_init`  | `UMIS1M:` | 5    | `umis-req+jwt`, SD-JWT+KB |
| `mutual_reply` | `UMIS1N:` | 6    | SD-JWT+KB                 |

A decoder MUST refuse an inflated container above 16 384 bytes. An unknown prefix is UNSUPPORTED_FORMAT; any other
defect (alphabet, terminator, a base45 value above 65 535, trailing bytes, the number or kind of tokens) is MALFORMED.

**UMIS-BLE v1.** Service `04855e79-ac59-4fd0-b286-dc08d76c0659`; characteristics `request` (`…5e7a…`, read and notify,
verifier to wallet), `response` (`…5e7b…`, write, wallet to verifier) and `control` (`…5e7c…`, write and notify), all in
`UMIS_BLE_V1`. A frame is cut into chunks of at most the MTU, each with the header `[msgId, index, total]`, so a frame
over BLE is at most min(16 384, 255 × (MTU − 3)) bytes.

## 6. Status lists, risk classes, S and Δ

A credential points to an entry of a Token Status List (`statuslist+jwt`, payload
`{sub, iat, exp?, ttl?, status_list: {bits, lst}}`) of its issuer. The values are `0` valid, `1` invalid (revoked) and
`2` suspended. A verifier MUST take a status list only from an address that the issuer's registry entry lists, signed by
a key of that entry, and at most 1 MiB in size.

A verifier MUST accept a status list only while `now − iat ≤ S` (the boundary is accepted) and, when the list has `exp`,
while `now ≤ exp`; otherwise the decision is STATUS_LIST_STALE. S is the policy's `maxStatusAgeSeconds` and MUST NOT
exceed the cap of its risk class. Δ, the refresh interval (`statusRefreshSeconds`, the list's `ttl`), MUST NOT exceed S;
the defaults are 600 seconds online and 3 600 seconds in economy mode.

| Class     | S at most        | Channels                                              | Biometric confirmation |
| --------- | ---------------- | ----------------------------------------------------- | ---------------------- |
| `low`     | 72 h (259 200 s) | `qr_oneway`, `qr_full`, `qr_reverse`, `ble`, `oid4vp` | optional               |
| `medium`  | 24 h (86 400 s)  | `qr_reverse`, `ble`, `oid4vp`                         | required               |
| `high`    | 1 h (3 600 s)    | `qr_reverse`, `ble`, `oid4vp`                         | required               |
| `highest` | 10 min (600 s)   | `oid4vp`                                              | required               |

A one-way token exists in `low` only. A revocation becomes visible to an offline verifier within min(T, S) and to an
online one within Δ.

## 7. Trust, authority and delegation

**Trusted-issuer registry.** A verifier MUST trust an issuer only through its own registry: a `RegistrySnapshotV1`
signed as `umis-registry+jwt` by the owning organisation, whose entries are
`{issuer, name, jwks, vcts, statusLists, validUntil?, status}`. A missing entry is ISSUER_UNTRUSTED, a type the entry
does not list is ISSUER_VCT_NOT_ALLOWED, a suspended, revoked or expired entry is ISSUER_SUSPENDED and an unknown key is
ISSUER_KEY_UNKNOWN. There is no shared platform and no lookup on the network.

**Checkpoint policy.** A `CheckpointPolicyV1` (`schema: "umis.policy.v1"`) names the risk class, the channels, S, Δ, the
age of a holder proof, whether biometric confirmation is required, the accepted types and issuers (`self`, `registry` or
a list), the claims it asks for, an optional authority rule and the seconds a relay stays open. The JSON Schema is
[`checkpoint-policy.v1.schema.json`](../packages/policy/schema/checkpoint-policy.v1.schema.json); a policy MAY be signed
as `umis-policy+jwt`.

**Authority.** A requested `{action, resource, amount, unit, object?}` matches an item when `action`, `resource` and
`unit` are equal as strings (no unit conversion) and the objects do not differ (either side may leave the object out).
No match is AUTHORITY_MISSING; when every match has passed its `valid_until` the decision is AUTHORITY_EXPIRED;
otherwise the matching item with the largest `limit.amount` counts. The request is accepted when
`amount ≤ limit.amount`: 10 t against a limit of 10 t is accepted, 10 t against a delegated limit of 8 t is
AUTHORITY_LIMIT_EXCEEDED.

**Period budget.** With a ledger in the verifier context and `per` other than `operation`, an amount is accepted only
while the amounts already accepted in the period plus the new one stay within the limit (else
AUTHORITY_PERIOD_EXCEEDED). The amount is booked only on a final accept, under `iss|budget|action|resource|unit`, where
the budget is the parent's id for a delegated credential and the credential's own `jti` otherwise, so a delegate and its
parent draw on one budget at one verifier. The ledger belongs to that verifier: totals across several offline verifiers
are not enforced.

**Delegation.** A delegated credential embeds `delegation.parent = {id, status, authority, exp}`, is signed by the same
issuer and has `depth = parent depth + 1 ≤ max_depth`. It MUST NOT be wider than its parent: every item has a parent
item with the same action, resource, unit and period, an amount that is not larger, the parent's object restriction and
a `valid_until` that is not later, and `exp` is not later than the parent's. A verifier checks all of this and the
parent's status (PARENT_REVOKED, DELEGATION_WIDER_THAN_PARENT, DELEGATION_DEPTH_EXCEEDED, DELEGATION_OUTLIVES_PARENT);
an issuer revokes the descendants of a revoked credential (`cascadeRevocation`). A presentation that discloses
`authority` without the `delegation` it holds is DELEGATION_UNDISCLOSED.

## 8. Relay commands

A relay opens only for an `umis-relay-cmd+jwt` sent in the `X-Umis-Command` header next to the exact HTTP body it
authorises. Payload: `iss?` (the station or device), `aud` (the relay), `iat`, `exp` (at most 30 seconds after `iat`, 10
by default), `jti` (16 random bytes as base64url) and `bh`, the base64url SHA-256 of the UTF-8 body. The body is Shelly
Gen3 JSON-RPC text, for example
`{"id":1,"src":"station-7","method":"Switch.Set","params":{"id":0,"on":true,"toggle_after":3}}`. A relay MUST accept a
command once (replay id `relay:<jti>`), only for an `aud` it lists and only with the body whose hash it carries.

## 9. Decision events

A `DecisionEventV1` records one decision: `iss` (verifier), `seq`, `iat`, `chk` (checkpoint), `ch` (channel), `dec`,
`rsn` (reasons), `vct?`, `ciss?` (credential issuer), `cref?` (credential `jti`), `lat` (milliseconds), `sla?` (status
list age in seconds) and `pv?` (policy version). A journal chains the events: `h₀` is 32 zero bytes and
`hₙ = SHA-256(hₙ₋₁ ‖ UTF-8(JCS(eventₙ)))`; hashes are stored as lowercase hexadecimal. An event MAY be signed as
`umis-event+jwt`.

## 10. OpenID4VCI and OpenID4VP

**Issuance (OpenID4VCI 1.0).** Credential offers use `openid-credential-offer://` with the pre-authorized code grant (an
optional transaction code); the key proof is an `openid4vci-proof+jwt` `{aud, iat, nonce}` with the holder key in the
`jwk` header. The SD-JWT VC issuer metadata (`/.well-known/jwt-vc-issuer`) carries the issuer's keys inline and its
status lists in `umis_status_lists`, and MAY carry `umis_verifier_jwks` and `umis_registry_uri`.

**Presentation (OpenID4VP 1.0, strict subset).** A verifier sends an unsigned request by value as an `openid4vp://?…`
(or `openid4vp://authorize?…`) link of at most 16 384 characters:

- `response_type=vp_token` and `response_mode=direct_post`;
- `client_id = "redirect_uri:" + response_uri`, where `response_uri` is `https` (or `http` on `localhost` or
  `127.0.0.1`) and has no fragment;
- a `nonce` (16 random bytes or more as base64url), an optional `state`, and optional `client_metadata` whose
  `client_name` is the verifier's own, unverified word;
- `dcql_query` with 1 to 8 credential queries, each with a unique `id`, `format: "dc+sd-jwt"`, `meta.vct_values` with 1
  to 8 types and claims whose `path` names one UMIS claim.

A wallet MUST refuse a request by reference (`request_uri`), a signed request (`request`), `transaction_data`, any other
response type or mode (including `direct_post.jwt`), any other kind of client identifier, a `client_id` that differs
from `response_uri`, a repeated parameter and any query feature beyond the above. It posts the answer as a form:
`vp_token={"<query id>":["<presentation>"]}` and the `state` of the request, with a key-binding JWT for
`aud = client_id` (prefix included) and the request's nonce. The verifier MUST refuse a key-binding JWT older than 120
seconds and MUST accept each nonce once (replay id `vp:<nonce>`); its endpoint answers `200` with
`{"redirect_uri": "…"}` on accept and `400` otherwise.

## 11. Reason codes and errors

Reasons of a decision (`REASON_CODES`): `OK`, `MALFORMED`, `UNSUPPORTED_FORMAT`, `ISSUER_UNTRUSTED`,
`ISSUER_VCT_NOT_ALLOWED`, `ISSUER_KEY_UNKNOWN`, `ISSUER_SUSPENDED`, `SIGNATURE_INVALID`, `HOLDER_BINDING_INVALID`,
`NONCE_MISMATCH`, `AUDIENCE_MISMATCH`, `PRESENTATION_EXPIRED`, `PRESENTATION_TOO_LONG_LIVED`, `REPLAY`, `CLOCK_SKEW`,
`UNKNOWN_CREDENTIAL_REF`, `CREDENTIAL_EXPIRED`, `CREDENTIAL_NOT_YET_VALID`, `STATUS_REVOKED`, `STATUS_SUSPENDED`,
`STATUS_LIST_STALE`, `STATUS_LIST_MISSING`, `STATUS_LIST_INVALID`, `VCT_NOT_ALLOWED`, `CHANNEL_NOT_ALLOWED`,
`CLAIM_MISSING`, `DELEGATION_UNDISCLOSED`, `AUTHORITY_MISSING`, `AUTHORITY_EXPIRED`, `AUTHORITY_LIMIT_EXCEEDED`,
`AUTHORITY_PERIOD_EXCEEDED`, `DELEGATION_WIDER_THAN_PARENT`, `DELEGATION_DEPTH_EXCEEDED`, `DELEGATION_OUTLIVES_PARENT`
and `PARENT_REVOKED`.

Errors that are not decisions (`UmisError.code`): `INVALID_ARGUMENT` (a mistake of the caller), `CRYPTO_UNAVAILABLE`,
`KEY_NOT_FOUND`, `USER_CANCELLED`, `NETWORK` and `PROTOCOL`. A verification function never throws; builders and parsers
throw `UmisError`.

## 12. Limits

| Constant (`LIMITS`)  | Value     | Meaning                                               |
| -------------------- | --------- | ----------------------------------------------------- |
| `oneWayMaxTtlS`      | 30        | longest life of a one-way token and of a holder proof |
| `requestMaxTtlS`     | 120       | longest life of a request; oldest OpenID4VP answer    |
| `defaultSkewS`       | 10        | clock skew a verifier allows unless told otherwise    |
| `nonceBytes`         | 16        | random bytes of a nonce                               |
| `saltBytes`          | 16        | random bytes of a disclosure salt                     |
| `qrMaxChars`         | 4 296     | longest QR text, before anything is decoded           |
| `frameMaxBytes`      | 16 384    | largest inflated frame container                      |
| `statusListMaxBytes` | 1 048 576 | largest status list                                   |
