# Middleware: the terminal contract

Version 5, 13-Nov-2026. This count numbers the frames of this page alone. It ends at 5. From
now on, the frames change with a release of the middleware, and that release is not this count.
Read the release in `serverInfo.version` from the sandbox's MCP server, or in `SandboxVersion`
in a conformance report. The release of the middleware a terminal connects to is in that host's
own `GET /v1/health`, in `Version`.

Version 5 adds the refund. An `Instruction` may now carry `TransactionType` `RFND` and an
`OriginalTransaction`, the sale to refund: refund `TotalAmount` against that sale, and report
it in an `Outcome` as a sale's (A refund, below). The middleware sends a refund only to a
terminal that says on its upgrade that it takes refunds, in the header
`Mw-Transaction-Types: CRDP, RFND` (Connect, below). A terminal built to version 4 sends no
such header, so it is never sent a refund: it would ignore the two keys it does not read and
charge the refund as a sale. Declare `RFND` only once the terminal reads `TransactionType`.

Version 4 makes the word a terminal shows while a register links a pair: `LinkWord`'s `Word`
holds two different words of the middleware's list, in order, joined by a dot, such as
`rabbit.lamp`. A terminal built to version 3 that shows `Word` as it comes shows the pair;
one that checks the frame against version 3's pattern refuses it, so build it to this
version (Linking to a register, below).

Version 3 states the outcome in ISO 20022's payment terms: a `TransactionStatus` of `ACSP`
or `RJCT`, a `StatusReasonInformation` whose `Reason` says why no payment was taken, and the
references grouped by the kind of payment, `Card`, `Bank`, `Wallet` and `NPP`. An outcome
built to version 2 holds no `TransactionStatus`, so the middleware refuses it as `missing_field`:
build the outcome to this version (Outcome, below).

Version 2 adds the client certificate a live terminal presents, and the two frames a
terminal is sent while a register links to it, `LinkWord` and `LinkEnded`. A terminal built
to version 1 ignores both frames, as it ignores any frame it does not know, and shows no
word.

This is the contract a payment terminal implements to take payments through the middleware.
The middleware relays a sale, or a refund of one, from a point of sale (POS) to a terminal, and
the terminal's outcome back to the POS. A terminal that needs a session at its fleet's own
payment system can ask the middleware for what that system takes to sign it in, and report
what that system answered in a `LoginResponse` (Signing in, below). You can build a
terminal's side from this document alone. The schema of each frame,
`TerminalInstruction`, `TerminalOutcome`, `TerminalRefusal`, `TerminalLinkWord`,
`TerminalLinkEnded`, `TerminalStatusRequest`, `TerminalAbort`, `TerminalLoginNeeded`,
`TerminalLoginRequest` and `TerminalLoginResponse`, is also in `docs/api/openapi.yaml` beside
it, for a client that validates what it sends and receives.

An instruction is a sale, or with `TransactionType` `RFND` a refund, and only a terminal that
declared `RFND` is sent a refund. Field names are ISO 20022 element names as written, in
PascalCase. Every field below says who sends it: `mw` or `terminal`. Every amount is a
JSON string in decimal major units with a dot and exactly two fraction digits, such as
`"12.50"`. It is never a JSON number and never negative, and one `Currency`, `AUD`, governs
every amount in a sale.

## In short

1. Open a WebSocket to `/v1/terminals/{POIIdentification}/connect`, presenting the
   terminal's credential on the upgrade, and hold it while the terminal is on. Reconnect
   whenever it closes.
2. If the terminal takes refunds, say so on every upgrade, beside the credential:
   `Mw-Transaction-Types: CRDP, RFND`. A terminal that says nothing is sent sales alone. Once
   it answers a `StatusRequest`, say that too: `Mw-Message-Functions: SSMQ`. Once it also
   answers an `Abort`, add `SSAB`: `Mw-Message-Functions: SSAB, SSMQ`. Once it does all that
   Signing in, below, says, add `SASQ`: `Mw-Message-Functions: SASQ, SSAB, SSMQ`.
3. An `Instruction` frame arrives. Store its `TransactionReference`, then charge
   `TotalAmount`, or with `TransactionType` `RFND` refund it (A refund, below).
4. When the payment ends, store the `Outcome` frame, then send it.
5. If the middleware answers with a `Refusal`, read its code. Otherwise the outcome counts as
   taken once any later frame but a Close comes from the middleware on that connection. Taken or
   not, send your most recent outcome again after any reconnect, until a new `Instruction`,
   a `Refusal` for it other than `terminal_not_permitted`, or 23 hours.
6. If a `LinkWord` frame arrives, show its word until a `LinkEnded` comes or its seconds
   pass (Linking to a register, below).
7. If a `StatusRequest` frame arrives, answer it from what the terminal stored
   (StatusRequest, below).
8. If an `Abort` frame arrives, stop the payment its `TransactionReference` names if it has
   not reached the host, and send `RJCT` with `DS02`. Otherwise answer it from what the
   terminal holds (Abort, below).
9. If the terminal declared `SASQ` and holds no session at its fleet's payment system, at
   connect or when an `Instruction` arrives, wake if it sleeps, send one `LoginNeeded` with a
   fresh key, open the `LoginRequest` that answers it, sign in with what it holds, and report
   what its fleet's payment system answered in one `LoginResponse` (Signing in, below).

The sections below say what each step means, and what to do when a step goes wrong.

## Address

A terminal is tested in the middleware's sandbox, which serves this document. The sandbox's start
page, `mw://start` through its MCP server and `/docs/api/sandbox.md` over HTTP, walks a
terminal from a first key to a signed conformance report. `POST /sandbox/v1/keys` needs no
credential, and answers a sandbox key and a world of nine terminals, one of them
`<tester>-yours`, which nothing in the sandbox holds and your terminal connects as.

A terminal connects to the address the sandbox served this document from, its scheme made
WebSocket's: `ws://` where that address is `http://`, and `wss://` where it is `https://`, on the
same host and port. The path is `/v1/terminals/{POIIdentification}/connect`, with the
terminal's own id in it (The id, below), and its credential goes on the upgrade (Connect,
below). Two connections for one id replace each other, because each reconnects when it is
closed, so connect each terminal under its own id.

A `live` middleware is `wss://` on port 443. `/docs/api/environments.md` names the base URL of
each environment open to an integration.

## The id

`POIIdentification` is the terminal's id, and matches `^[A-Za-z0-9_-]{1,64}$`. The middleware
issues it, `poi_` then 32 lowercase hex characters, when the terminal's fleet lists the
device, and the POS names the same id in its sale. Only a seed, which a sandbox reads at
boot, may choose one instead. A listed terminal may connect once it is `paired`: in the
sandbox, a seed pairs it. It must not be a card or account number: the middleware cannot detect one
in it, and the id is logged.

## Connect

`GET /v1/terminals/{POIIdentification}/connect` with a WebSocket upgrade (RFC 6455):
`Connection: Upgrade`, `Upgrade: websocket`, `Sec-WebSocket-Version: 13` and a
`Sec-WebSocket-Key`. Every message either way is a text frame holding one JSON object in
UTF-8, at most 65,536 bytes. The only other frames are WebSocket's own Ping, Pong and
Close.

**The credential.** A live terminal presents its client certificate at the TLS handshake of
the upgrade, with the issuing certificate beside it, as `CertificateChain` gave them, and
sends no `Authorization` header. The middleware's own CA issues it when the terminal enrols:
`POST /v1/enrol` with the `PairingCode` its listing showed, a CSR for a P-256 key the
terminal made in its keystore, its `SerialNumber`, and its Android Key Attestation chain.
A terminal's code is five words of `docs/api/words.txt`, such as
`bronze.farm.loop.prism.tempo`, and `docs/api/onboarding-device.md` walks how an app reads
them. The certificate names the terminal's `POIIdentification`, which must be `paired`, and lasts
30 days. Once a day, `GET /v1/certificates/self` under it answers `RenewNow`. When that is
`true`, ask `POST /v1/certificates/challenge`, make a new key with that challenge, renew
with `POST /v1/certificates/renew`, use the new certificate from the next connection, and
delete the old key once a connection on the new one has succeeded. `docs/api/openapi.yaml`
holds each of these routes.

A sandbox terminal may present its sandbox key on the upgrade instead, as
`Authorization: Bearer sbx_...`: a `pos` key of the terminal's own vendor, on a
`POIIdentification` that is `paired` for that vendor. A `pos` key names a register of its
own vendor, and only a vendor holding `pos` may list one, so in a sandbox the terminal's
fleet vendor must also hold the `pos` role and a register, whose `pos` key the terminal
presents. FUNDiMO issues the key, and it is shown once. A `live` middleware refuses every
sandbox key. One credential a request: a certificate and an `Authorization` header together
are refused. The middleware checks the credential first, then the id, then the upgrade. No frame
changes for it.

**What the terminal takes.** A terminal that takes refunds says so on the upgrade, beside its
credential, in the header `Mw-Transaction-Types`: ISO 20022 codes of `TransactionType`,
separated by commas with optional spaces, such as `Mw-Transaction-Types: CRDP, RFND`. `CRDP` is
a sale and `RFND` a refund. The middleware sends a refund only on a connection whose upgrade
declared `RFND`: a POS that asks for a refund on a terminal connected without it is refused
`409 terminal_cannot_refund`, and the terminal is sent nothing. Absent, empty, over 256 bytes, or
naming no code the middleware knows, the header reads as `CRDP` alone. A code it does not know is
ignored, codes are matched exactly, case and all, and `CRDP` is always in the set, so a terminal
that declares `RFND` alone is still sent sales. Sent more than once, its values are read as one
list. The middleware keeps what a connection declared for that connection alone, and a new one
carries its own, so send the header on every upgrade. It reads the header only once the
credential has passed, and a refused upgrade reads it not at all. ISO 20022 has no element for
it: the name is the middleware's own.

**What the terminal answers, and what it asks.** A terminal says on the upgrade which of the
middleware's requests it answers, and whether it asks to be signed in, in the header
`Mw-Message-Functions`, read as `Mw-Transaction-Types` is: codes
separated by commas with optional spaces, read as one list when the header is sent more than
once, matched exactly, case and all, a code the middleware does not know ignored, and kept for
that connection alone, so send it on every upgrade. Its
codes are ISO 20022's `MessageFunction`, of `Header41`: "Identifies the type of process related
to the message." `SSMQ`, "Request the status of a previous message for which the Sale system
has no response.", says the terminal answers a `StatusRequest` (StatusRequest, below), such as
`Mw-Message-Functions: SSMQ`. `SSAB`, "Abort the current process or the last request.", says the
terminal answers an `Abort` (Abort, below), such as `Mw-Message-Functions: SSAB, SSMQ` for a
terminal that answers both. `SASQ`, "Request the management of a session: login, logout and
diagnosis services. Initiated by the Sale system.", says the terminal asks to be signed in to its
fleet's payment system, and can be woken (Signing in, below), such as
`Mw-Message-Functions: SASQ, SSAB, SSMQ` for a terminal that does all three. The middleware sends
an `Abort` only on a connection whose upgrade declared `SSAB`: a POS that asks to cancel a sale on
a terminal connected without it is refused `409 terminal_cannot_abort`, and the terminal is sent
nothing. The middleware answers a `LoginNeeded` only on a connection whose upgrade declared
`SASQ`: on any other it is refused `unknown_frame_type`. Absent, empty, over 256 bytes, or naming
no code the middleware knows, the header declares none, the terminal is sent no `StatusRequest`
and no `Abort`, and its `LoginNeeded` is refused. Declare `SSMQ` only once the terminal answers a
`StatusRequest`, `SSAB` only once it answers an `Abort`, and `SASQ` only once it does all that
Signing in, below, says. The middleware reads the header only once the credential has passed,
and a refused upgrade reads it not at all. ISO 20022 has no element for the header itself: its
name is the middleware's own.

| Status | `Error.Code` | When | What to do |
|---|---|---|---|
| `101` | | Upgraded. Replaces any current connection for that id | Hold it. Reset the reconnect backoff only once it has stayed open 10 seconds (Reconnect, below) |
| `400` | `invalid_field` | `POIIdentification` fails its pattern, with `Fields: ["POIIdentification"]` | Fix the id. Retrying will not help |
| `400` | `invalid_upgrade` | A bad WebSocket version or key | Fix the client |
| `401` | `certificate_required` | No credential came | Present the certificate, or in the sandbox the key. A terminal with no certificate enrols first |
| `401` | `certificate_expired`, `certificate_invalid` | The certificate is past its `NotAfter`, or is not one the middleware holds; or an `Authorization` header of another scheme, or beside a certificate | The holder's table below: back off an hour, and after three tell the installer |
| `401` | `sandbox_key_invalid` | A key that is malformed, unknown or retired | Check the key. Wait one hour before the next connect, and keep any outcome you hold |
| `401` | `sandbox_key_on_live` | A sandbox key sent to a `live` middleware | A sandbox key works in the sandbox alone. Wait one hour before the next connect, and keep any outcome you hold |
| `403` | `not_permitted` | The credential is good, and may not hold this terminal's connection: it is not this terminal's certificate or a `pos` key of its vendor, or the terminal is not `paired` | Back off to one hour before the next connect, and keep any outcome you hold |
| `403` | `certificate_retired` | The certificate presented is retired: a newer one of this identity is in use | The holder's table below |
| `426` | `upgrade_required` | A `GET` with no `Upgrade` header | Fix the client |
| `503` | `store_unavailable`, `edge_not_trusted` | The middleware's store did not answer while it checked the credential or the terminal, or the upgrade did not come through a trusted edge. It is no verdict on either | Reconnect with the backoff (Reconnect, below) |
| Anything else | | | Reconnect with the backoff |

A `401` or a `403` is the middleware's verdict on the credential, and a `503` is not. What to do
after each is the holder's table below, and the terminal keeps any outcome it holds, to send
once a connection is accepted. After a `503`, reconnect with the normal backoff.

## What a holder of a dead certificate does

A refusal at the TLS handshake, or on the upgrade, is read by this table. A live terminal
holds a certificate, so it is the holder here.

| What the terminal sees | What it does next |
|---|---|
| A close, a reset, a timeout, or any failure with no TLS alert | The normal backoff (Reconnect, below), which resets only once a connection has stayed open 10 seconds. It says nothing about a certificate, and a terminal reconnects at least hourly on a network anyone in the shop can disturb |
| A TLS alert naming the certificate: `certificate_expired`, `bad_certificate`, `certificate_unknown`, `unknown_ca` or `decrypt_error`. On `direct` alone | Back off an hour. After three, an hour apart, tell the installer the terminal needs a new code, and keep trying hourly |
| `401 certificate_expired` or `401 certificate_invalid` | Back off an hour. After three, an hour apart, tell the installer the terminal needs a new code, and keep trying hourly |
| `401 certificate_required` | A client's own bug, or a route it has no certificate for: enrol first |
| `403 certificate_retired`, holding a newer certificate than the one presented | Drop that connection and retry on the newer one, with the same idempotency key where the request carried one. Ordinary, past an overlap |
| `403 certificate_retired` on its newest certificate | Stop, keep any outcome, and tell a person: something else holds a newer certificate of this identity |
| `403 not_permitted` | Back off to one hour, keeping the outcome. The certificate was good and the row refused it, which is what a removal or a re-pair reads as |
| `403 challenge_not_valid` | Ask for a new challenge, with a new key |
| `429`, `503`, `edge_not_trusted` among them | The normal backoff. `503 edge_not_trusted` is an edge fault, and the terminal's certificate is not in question |

A client certificate from a second CA bearing the middleware's own names is refused at the
handshake with `decrypt_error`, beside `unknown_ca` for a CA the middleware does not know at all, so
a terminal reads either as a TLS alert naming the certificate. A TLS alert comes only where
the middleware ends TLS itself, `direct`: behind a load balancer no handshake fails on the
certificate, and its refusal comes on the upgrade instead.

A holder never deletes its key or its certificate on any of these. A device can recover from
a mistake of the middleware's by a fix on the middleware's side, and a key deleted cannot. A new key is made
only when a person brings a new code. A terminal decides none of this by its own clock.

A non-2xx answer from the middleware has the body
`{ "Error": { "Code": "...", "Message": "...", "Fields": [] } }`.

## Hold

Keep the connection open while the terminal is on. The middleware sends a WebSocket Ping every
`MW_WS_PING_SECS`, 30 seconds by default. Answer each with a Pong, which most WebSocket
libraries do by themselves. The middleware treats 2.5 intervals with no frame of any kind from the
terminal as a dead connection, and closes it. Treat the same silence the same way: assume
the default, and close and reconnect after 75 seconds with no frame from the middleware.

A WebSocket library may answer each Ping itself and never show it, as OkHttp does. On one, the
middleware's Pings cannot be counted, so send your own: set the library's ping,
`pingInterval(30, TimeUnit.SECONDS)` on OkHttp's client, and read the library failing the
socket for want of a Pong as that silence, and reconnect. The middleware answers each Ping with
a Pong, and counts it as a frame from the terminal. Since such a library shows none of the
middleware's Pings, the later frame of Resending is safe, below, is the next text frame from the
middleware: an `Instruction`, a `StatusRequest`, an `Abort`, a `LinkWord`, a `LinkEnded` or a
`LoginRequest`. An `Instruction` that comes is the next payment as well.

## Reconnect

After any close, and after a failed connect the table above does not say to fix, reconnect
with a backoff: wait 1 second, double the wait after each failure up to 30 seconds, and add
a little randomness. A connection that closes within 10 seconds of opening counts as a
failed connect, so the next wait still doubles. Reset the backoff to 1 second only once a
connection has stayed open 10 seconds. This keeps a store outage, where the middleware closes the
connection on each outcome it cannot record, from becoming a reconnect every second. After a
refusal on connect, the holder's table says how long to wait (What a holder of a dead
certificate does, above).

A new connection for the same id takes over from the old one, and the middleware closes the old
one itself: it sends what was already queued for it, then a WebSocket Close, or drops it if
it takes no writes. A frame already queued for the old connection goes out on it or not at
all, never on the new one, so open a second connection only to replace the first.

The middleware keeps reading the old connection until the terminal closes its side, for at most 2.5
times `MW_WS_PING_SECS` after the takeover, 75 seconds by default. An outcome read there
is logged and applied as on any connection, so an outcome sent on the old connection as the
new one opened still settles its sale. Three things differ there:

- A `Refusal` can be lost. The middleware stops queueing frames for the old connection as the new
  one opens, and a `Refusal` it cannot queue gets a `delivery_failed` line in its log and is
  never sent.
- A frame that ends the old connection, a frame or message over 65,536 bytes or a frame
  that breaks the WebSocket protocol, leaves no line of its own: the connection's one
  `terminal_disconnected` line gives the reason `replaced`, not that frame's.
- A frame still unread when that time is up is never read, and leaves no line.

So send nothing more on a connection once a new one is open, and send your most recent
outcome again on the new one, as Resending is safe, below, says.

A drop does not end a sale. An outcome that could not be sent before a drop is sent after
the reconnect. A hosted middleware will close connections of its own accord, so the reconnect
is not optional.

The middleware also closes the connection when its store cannot take an outcome the terminal sent,
because the store is down or slow. Its log's `terminal_disconnected` line then gives the
reason `store_unavailable`, and the outcome may not have been recorded. Send it again after
the reconnect, as Resending is safe, below, says.

The middleware closes a connection whose terminal stops being `paired`, or whose credential is
retired, within `MW_WS_PING_SECS`, and its log's `terminal_disconnected` line gives the
reason `revoked`. While that lasts, the next connect is refused: `403 not_permitted` backs off
to one hour, and a retired credential's refusal is read by the holder's table above. Keep any
outcome you hold.

A hosted middleware may run two instances for a while, and a POS's sale can reach the one your
connection is not on. That instance answers the POS `409 terminal_offline`, and the one your
connection is on closes it within a few seconds; its log's `terminal_disconnected` line gives the
reason `moved`. Reconnect as after any close: your next connection reaches the instance taking
new requests.

## Linking to a register

A register links to a terminal at the counter, by a word the terminal shows. The register
asks the middleware, the middleware gives each unbound `paired` terminal of the store a different word, and
the staff member types the word they see on the terminal in their hand into the register.
The word is a pair: two different words of the middleware's list, in order, joined by a dot, such as
`rabbit.lamp`, and the staff member types the two with the dot or a space between them. The POS
never sees a word: the word is the whole proof that the person at the register holds that
terminal. Two frames reach the terminal, and neither needs anything back.

```json
{ "MessageType": "LinkWord", "Word": "rabbit.lamp", "ExpiresInSeconds": 120 }
{ "MessageType": "LinkEnded", "Linked": true }
```

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `mw` | `LinkWord` or `LinkEnded` |
| `Word` | `mw` | On `LinkWord`: the word to show, two different words of the middleware's list, each 3 to 6 lowercase letters, in order, joined by a dot, `^[a-z]{3,6}\.[a-z]{3,6}$` |
| `ExpiresInSeconds` | `mw` | On `LinkWord`: how long to show it, in whole seconds from when the terminal read the frame, 1 to 300 |
| `Linked` | `mw` | On `LinkEnded`: `true` on the terminal the register linked, and `false` on every other |

**Show the word until a `LinkEnded` comes or `ExpiresInSeconds` pass**, whichever is first,
large enough to read across a counter. Count the seconds from when the terminal read the
frame, so a lost `LinkEnded` leaves nothing on the screen and no clock is compared. On
`LinkEnded`, clear the word, and if `Linked` is `true` show that the terminal linked. A later
`LinkWord` replaces the word shown.

A terminal shows a word only while a register is asking, and the request times out by
itself, so a terminal has no menu to open and nothing to choose. The middleware sends no word to a
terminal in a sale until the sale ends, and to a bound terminal none at all. Never log the
word, and never send it back: the middleware's own log holds it as `<withheld>`.

## Instruction

The middleware to the terminal. One frame starts one payment: a sale, or with
`TransactionType` `RFND` a refund (A refund, below).

```json
{ "MessageType": "Instruction", "TransactionReference": "sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a", "SaleReferenceIdentification": "INV-1001", "TransactionDetails": { "Currency": "AUD", "TotalAmount": "12.50", "SaleItem": [ { "ProductDescription": "Flat white", "ProductQuantity": 2, "UnitPrice": "6.25", "ProductAmount": "12.50" } ] } }
```

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `mw` | `Instruction` |
| `TransactionType` | `mw` | `RFND` on a refund's instruction, and absent on a sale's, which reads as `CRDP`. Read it first. Sent only to a terminal that declared `RFND` (Connect, above) |
| `TransactionReference` | `mw` | The sale, or with `RFND` the refund, `sal_` then 32 lowercase hex characters. Keep it and return it as received |
| `SaleReferenceIdentification` | `mw` | The POS's reference |
| `CashierIdentification` | `mw` | The POS's identifier for the user of the POS who made the sale or the refund, present only if the POS sent one: show, print or pass it on, or ignore it |
| `TransactionDetails` | `mw` | What to charge, or with `RFND` to refund, and the items when there are any |
| `TransactionDetails.Currency` | `mw` | `AUD` |
| `TransactionDetails.TotalAmount` | `mw` | **Charge this amount and show it as the total**, or with `RFND` refund it, adding nothing to it |
| `TransactionDetails.SaleItem` | `mw` | Present only when the sale has items, in the POS's order |
| `SaleItem[].ProductDescription` | `mw` | The name to show |
| `SaleItem[].ProductQuantity` | `mw` | A JSON integer, for display |
| `SaleItem[].UnitPrice` | `mw` | The price of one unit, an amount |
| `SaleItem[].UnitPriceSign` | `mw` | Present only if the POS sent it. A boolean: `false` means show the price as negative, and absent means plus |
| `SaleItem[].ProductAmount` | `mw` | The line's total, an amount |
| `SaleItem[].ProductAmountSign` | `mw` | As `UnitPriceSign`, for `ProductAmount` |
| `OriginalTransaction` | `mw` | With `RFND` alone: the sale to refund, as the middleware holds it. Absent on a sale's |
| `OriginalTransaction.TransactionReference` | `mw` | The sale refunded, `sal_` then 32 lowercase hex characters: the `TransactionReference` its own instruction carried. The outcome returns the refund's `TransactionReference`, never this one |
| `OriginalTransaction.POIIdentification` | `mw` | The terminal that took the sale, which may be another than this one |
| `OriginalTransaction.SaleReferenceIdentification` | `mw` | The POS's reference for the sale |
| `OriginalTransaction.TransactionDateTime` | `mw` | The sale's approving outcome's `TransactionDateTime`, as that terminal stated it, for a host whose original data needs it. Absent when it sent none |
| `OriginalTransaction.PaymentReference` | `mw` | What the sale's approving outcome carried that passed, under the same groups and keys (References by kind, below), less `Card.AcquirerMerchantIdentification`. Absent when nothing is left |

**What to charge.** The terminal charges `TotalAmount` and shows it as the total, whatever
the items say, and takes the payment whether or not it can show the items. It adds nothing to
`TotalAmount`: no surcharge, tip or fee, neither its own nor one its merchant settings would
apply to a payment it starts itself, so switch those settings off for a payment the middleware
instructs. A store's own surcharge on the bill, such as 15% on a public holiday, is already
inside `TotalAmount`: the POS added it before it sent the sale, so never add it again. No card
payment surcharge is taken through the middleware. A refund refunds exactly `TotalAmount`
(A refund, below). The approval states what the host approved, in
`TransactionDetails.AuthorisedAmount` (Outcome, below), and the middleware logs one other than
`TotalAmount` as the terminal breaking this contract.

**The items.** Show the items if the terminal can, and ignore `SaleItem` if it cannot. They
never change what is charged, and a terminal never adds them up. Assume no length or
alphabet for `ProductDescription`, and clip what cannot be shown: the schema gives that
field no pattern, so the bound can widen later. The POS's `ProductCode`, tax, discounts,
product identifiers and the basket's header stay in the middleware.

**What a terminal ignores.** Ignore any key a frame the middleware sends does not name, at any
depth, on an `Instruction`, a `Refusal`, a `LinkWord`, a `LinkEnded`, a `StatusRequest`, an
`Abort` and a `LoginRequest`, and in the `SignedValue` group a `LoginRequest` opens to: a later
version may add some. Ignore a frame of any `MessageType` the terminal does not know.

**The middleware sends each instruction once.** A drop does not bring it back. Instead, the
middleware asks about an instruction lost in a drop on a later connection of the terminal, by
a `StatusRequest`, when that connection declared `SSMQ` (StatusRequest, below). If a
`TransactionReference` the terminal has already started arrives again, do not charge again:
resend its stored outcome if it has one. An instruction the terminal cannot act on, such as a
`Currency` it does not support, gets `RJCT` with `Reason` `AB11`, because no payment was taken.

**Keep the reference first.** Store the `TransactionReference` before taking the card, so a
crash or a reboot can still report. On restart, find out from the host what happened, then
send the outcome.

## A refund

An `Instruction` with `TransactionType` `RFND` is a refund: a sale running the other way, sent
and settled as a sale is. The POS asks for it against a sale the middleware approved, and the
middleware adds what it kept of that sale, under `OriginalTransaction`:

```json
{ "MessageType": "Instruction", "TransactionType": "RFND", "TransactionReference": "sal_02a8f3c4d5e6f708192a3b4c5d6e7f80", "SaleReferenceIdentification": "CN-1001", "TransactionDetails": { "Currency": "AUD", "TotalAmount": "6.25", "SaleItem": [ { "ProductDescription": "Flat white", "ProductQuantity": 1, "UnitPrice": "6.25", "ProductAmount": "6.25" } ] }, "OriginalTransaction": { "TransactionReference": "sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a", "POIIdentification": "T-APPROVE", "SaleReferenceIdentification": "INV-1001", "TransactionDateTime": "2026-11-06T15:12:40+11:00", "PaymentReference": { "Card": { "RetrievalReferenceNumber": "631012345678", "SystemTraceAuditNumber": "000123", "AuthorisationCode": "A1B2C3", "AcquirerPOIIdentification": "12345678", "RefundReference": "klujhadsc9ph87asd" } } } }
```

`TransactionType` is ISO 20022's `TransactionType` (`TxTp`) of `PaymentTransaction183`: "Type
of transaction being undertaken for the main service." Its codes are ISO's
`CardPaymentServiceType16Code`: `CRDP`, "Card payment.", and `RFND`, "Refund transaction." ISO
names them for cards, and this contract uses them for every rail. `OriginalTransaction` is
ISO's `OriginalTransaction` (`OrgnlTx`): "Identification of the original transaction." Each
definition is ISO's, from M3 (Sources, below).

**Declare it first.** The middleware sends a refund only on a connection whose upgrade said the
terminal takes refunds, `Mw-Transaction-Types: CRDP, RFND` (Connect, above). A terminal that
declares nothing is sent sales alone, so one built to an earlier version, which would ignore
`TransactionType` and charge the amount, is never sent a refund.

**Read `TransactionType` first.** With `RFND`, store the `TransactionReference`, which is the
refund's own, then refund `TotalAmount`, the amount to refund, against the sale
`OriginalTransaction` names. Refund by its references where the host can retrieve the original
transaction, and with the card presented where it cannot, never replaying the sale's
authentication data. A payment over NPP, PayTo included, or through a wallet or payment app, is
refunded through the app or provider that took it, by the ids of its group in
`OriginalTransaction.PaymentReference`. The refund's terminal need not be the sale's:
`OriginalTransaction.POIIdentification` names the one that took it, and a host whose references
do not reach across its own terminals declines. A code the terminal does not take, or a refund
it cannot make for this kind of payment, gets `RJCT` with `Reason` `AB11`, and moves no money.

**The outcome is a sale's.** Report the refund in an `Outcome` under the refund's own
`TransactionReference`, never the sale's: `ACSP` when the whole `TotalAmount` was refunded,
`RJCT` with `AG07` when the host declined the refund, `RJCT` with `DS02` when the terminal
stopped the refund, before it reached the host, in answer to an `Abort` (Abort, below), and
`RJCT` with `AB11` for every other way no refund was made (Which `TransactionStatus` to send,
below). The refund's own references, such as the host's new retrieval reference, go under the
groups and keys of References by kind, below. Store the outcome, send it, and send it again after
any reconnect, as a sale's (Resending is safe, below). A `TransactionReference` the terminal
already started is never refunded twice.

**No total is kept.** The middleware keeps no total of a sale's refunds: it relays every refund,
whole or part, however many the sale has had, and does not compare a refund's amount with the
sale's. A host that caps a sale's refunds declines the one past its cap, and the terminal sends
`RJCT` with `AG07`.

**A refund's `UNKN` is a sale's.** A refund has a sale's deadline and hold: with no outcome by
`MW_SALE_DEADLINE_SECS`, the POS reads `UNKN`, and a late outcome replaces it unless the terminal
contradicted itself. The middleware sends a refund's instruction once and holds no amount for it.
A refund the terminal never received is asked about on a later connection, by a
`StatusRequest`, as a sale's is (StatusRequest, below). Until the terminal answers, the POS reads
`UNKN`, and the cashier checks the terminal before refunding another way. Always send a refund's
outcome, however late.

## One payment at a time

The middleware sends no second instruction while a sale or a refund holds the terminal. If
one arrives anyway, do not start it and do not queue it: store `RJCT` with `AB11` as the
outcome of its `TransactionReference`, and send it. No payment was taken for it, and the POS
reads that as a definite answer. Queueing is how a customer pays twice. A terminal with a
payment it cannot yet resolve is still busy, even after the middleware's hold ends, so the same
applies.

## Deadline

Send the outcome as soon as it is known. If the middleware has heard nothing by
`MW_SALE_DEADLINE_SECS`, 120 seconds by default, it tells the POS `UNKN`. The terminal
stays claimed for `MW_TERMINAL_HOLD_SECS` more, 180 seconds by default, so no new sale
reaches it while it may still be mid-payment.

**Always send the outcome, however late.** A late outcome replaces `UNKN`, and is the only
way the POS learns the truth.

The middleware holds a sale for `MW_SALE_RETENTION_SECS`, 86,400 seconds by default, which is
24 hours, after it settled or went `UNKN`. After that, an outcome for it gets `not_held`.

## StatusRequest

The middleware to the terminal: a question about a sale or a refund the middleware still holds
open for the terminal, made while an earlier connection held it, whose `Instruction` may have
been lost. The terminal answers with an ordinary `Outcome`, or with nothing: no new frame
goes back.

```json
{ "MessageType": "StatusRequest", "TransactionReference": "sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a", "SecondsSinceInstruction": 34 }
```

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `mw` | `StatusRequest` |
| `TransactionReference` | `mw` | The sale or the refund asked about, `sal_` then 32 lowercase hex characters: the `TransactionReference` its `Instruction` carried |
| `SecondsSinceInstruction` | `mw` | A JSON integer from 0: the whole seconds from the sale's creation to this frame, by the middleware's clock, rounded up |

ISO 20022 names the exchange a status request asks about by `ExchangeIdentification`:
"Transaction identification." This frame names it by the key its `Instruction` carried,
`TransactionReference`. `SecondsSinceInstruction` is the middleware's own, since ISO's request
carries no time, and so is the frame's name.

**When it comes.** The middleware sends a `StatusRequest` only on a connection whose upgrade
declared `SSMQ` in `Mw-Message-Functions` (Connect, above). A terminal that declared none is
sent none.

From the connection's first ping, `MW_WS_PING_SECS` after it opened, 30 seconds by default, the
middleware asks about each sale and refund of the terminal that it still holds open, `PDNG` or
`UNKN`, and that was made in the last 23 hours, oldest first.

It asks only about a sale made while an earlier connection held the terminal. A sale made while
this connection held it is never asked about on it, whether or not its `Instruction` went out.

It sends at most 4 at each ping, and asks about a sale at most once a connection, until none is
left. A `StatusRequest` changes no sale and moves no timer: the deadline and the hold run as
they would without it.

**How a terminal answers.** A terminal keeps every `TransactionReference` it received, with its
outcome once it has one, for at least 24 hours, and knows how far back its store of references
reaches. It answers a `StatusRequest` by what it holds for the reference:

| What the terminal holds for the `TransactionReference` | What it does |
|---|---|
| An outcome | Sends that outcome, unless it already sent it on this connection |
| A payment it has not finished | Sends nothing until it knows, then that outcome, once (The paths, step by step, below) |
| No record, and its store of references reaches back further than `SecondsSinceInstruction` | Stores `RJCT` with `AB11` as that reference's outcome, and sends it. An `Instruction` of that reference that comes later is never started, and is answered with that outcome on the terminal's current connection, unless it already sent it on that connection |
| No record, and its store does not reach back that far | Sends nothing: it cannot prove it never received the `Instruction` |

**How far back the store reaches.** A terminal's store of references reaches back to the latest
of three times: when the store began; when it stored the newest reference it dropped, by its
limit on how many it keeps or by age, the oldest first; and when it lost any reference another
way, such as one it received and could not store. A reset that clears the store begins it
again. So does a restart, unless the whole store, with those times, survives it. A terminal
measures how long ago those times were on a clock that never jumps, such as a monotonic clock,
and never by the time of day: a time of day set forward makes the store look older than it is.
So a terminal never answers `RJCT` with `AB11` for a reference it may have received.

The answer is an ordinary `Outcome`, and the middleware applies it as any outcome: a late one
replaces `UNKN`, a repeat changes nothing, and a different result is a contradiction (Resending
is safe, below). So send an outcome at most once on one connection, whether a `StatusRequest`
asked for it or not.

**Why the two times.** `SecondsSinceInstruction` lets a terminal compare the request with how
far back its own store of references reaches, so no two clocks are compared. The middleware asks only about
sales of the last 23 hours, and a terminal keeps 24, so a terminal never takes a reference it
has pruned for one it never received. A store that does not reach back that far, on a new
device, after a re-pair or a reinstall, or once the store was cleared, cannot prove that the
`Instruction` never came. So the terminal sends nothing, and the sale reads `UNKN` until a late
outcome or retention.

**What a conformance run shows.** The sandbox's conformance run stages one case: it takes the
terminal's connection itself while a sale is made, so the sale's `Instruction` never reaches the
terminal, then closes it. It judges that the terminal declared `SSMQ`, was sent a
`StatusRequest` for the sale on its own connection, and answered `RJCT` with `AB11`, once. A
green run does not prove the rest of this contract's recovery:

- that a terminal that does not know whether a payment was taken finds out by an enquiry to its
  host, or by a reversal the host confirmed (The paths, step by step, below);
- that it reports before the hold ends, 300 seconds from the instruction at the default
  settings, where its host answers;
- that it sends nothing for a payment it has not finished, then that outcome once it knows;
- that it sends nothing where its store of references does not reach back past
  `SecondsSinceInstruction`;
- that it answers a second instruction while a payment runs with `RJCT` and `AB11` (One
  payment at a time, above).

## Abort

The middleware to the terminal: stop the payment of a sale or a refund, because its POS asked to
cancel it. The terminal answers with an ordinary `Outcome`, or with nothing: no new frame goes
back.

```json
{ "MessageType": "Abort", "TransactionReference": "sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a" }
```

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `mw` | `Abort` |
| `TransactionReference` | `mw` | The sale or the refund to stop, `sal_` then 32 lowercase hex characters: the `TransactionReference` its `Instruction` carried |

The frame is named after ISO 20022's `SaleToPOIAbort`: "The SaleToPOIAbort message is sent by a
sale system to abort process on POI." ISO names the exchange to abort by `ExchangeIdentification`
of `AbortData7`: "Message identifier." This frame names it by the key its `Instruction` carried,
`TransactionReference`. ISO's abort also requires an `AbortReason`, free text, and this frame
carries no reason, since free text is where card and personal data slip in. Each definition is
ISO's, from M3 (Sources, below).

**When it comes.** The middleware sends an `Abort` only on a connection whose upgrade declared
`SSAB` in `Mw-Message-Functions` (Connect, above). A terminal that declared none is sent none.

It sends one when a POS asks to cancel a sale or a refund, with
`POST /v1/sales/{TransactionReference}/abort`, while the sale still holds the terminal: `PDNG`,
or `UNKN` inside the terminal's hold. It sends one frame for each request it admits, so the same
reference can come more than once, and queues it behind any frame already waiting on the
connection, so an `Abort` never overtakes its own `Instruction` on that connection.

**How a terminal answers.** A terminal answers an `Abort` by what it holds for the reference:

| What the terminal holds for the `TransactionReference` | What it does |
|---|---|
| Its current payment, not yet sent to its host | Stops the payment, shows it cancelled, and sends `RJCT` with `DS02` |
| Its current payment, already with its host | Carries on, and sends the host's outcome, or finds it out from the host, as for any payment whose result it does not know (The paths, step by step, below) |
| An outcome, its payment ended | Sends that outcome, unless it already sent it on this connection: a sale the middleware still holds open has lost it |
| No record | Sends nothing: an `Instruction` lost in a drop is asked about by a `StatusRequest` on a later connection (StatusRequest, above) |

The answer is an ordinary `Outcome`, and the middleware applies it as any outcome: a repeat
changes nothing, and a different result is a contradiction (Resending is safe, below). So send an
outcome at most once on one connection, however many `Abort` frames name its reference.

**Only the payment it names.** An `Abort` acts only on the payment its `TransactionReference`
names, and never stops a payment for any other reference. An outcome can end the sale between
the middleware's check and its sending of the `Abort`, so an `Abort` can arrive after its sale
ended, while the terminal runs another sale's payment: it leaves that payment alone, and the
terminal answers the `Abort` by the table above, from what it holds for the reference.

**`DS02` answers an `Abort` alone.** A terminal sends `DS02` only in answer to an `Abort`, and a
cancel at the terminal, by the customer or the staff, stays `AB11` (Which `TransactionStatus` to
send, below).

**The deadline does not move.** An `Abort` moves no timer: the deadline and the hold run as they
would without it. A `DS02` after the deadline is a late outcome, and replaces the `UNKN` the POS
reads, as any late outcome does. The terminal stays claimed until its outcome or the hold's end,
so send the `DS02` as soon as the payment stops.

**A refund.** A refund is aborted as a sale is, by its own `TransactionReference`. Its `DS02`
means no refund was made. A refund already with its host carries on, and the host's answer
stands.

**What a conformance run shows.** The sandbox's conformance run stages one case, `cancel`: it
sends the terminal a sale, whose payment the tester holds with no card presented, and asks to
cancel it 3 seconds after the `Instruction`. It judges that the terminal declared `SSAB`, and
answered the `Abort` with `RJCT` and `DS02`, once, with no `Refusal`. A green run does not prove
the rest of this contract's abort:

- that a terminal whose payment is already with its host carries on and sends the host's
  outcome, never `DS02`;
- that it sends `DS02` only in answer to an `Abort`, and `AB11` for a cancel at the terminal;
- that an `Abort` never stops a payment for another reference;
- that, for a reference whose payment ended, it sends that outcome, unless it already sent it on
  this connection;
- that, for a reference it holds no record of, it sends nothing.

## Signing in

A terminal may need a session at its fleet's own payment system before it can take a payment,
and may hold none: after its process starts, or once that system ended the session. A terminal
that declared `SASQ` (Connect, above) asks the middleware for what that system takes for a
sign-in, with a `LoginNeeded`. The middleware answers on the same connection with a
`LoginRequest`, made from the credential the fleet set for the terminal's store and sealed to a
key the terminal made for that one asking, or with a `Refusal` saying why not. The terminal opens
the answer, takes it to its fleet's payment system itself, and reports what that system answered
in a `LoginResponse`. The middleware never sees the session and cannot end it: ending one is the
fleet's. A POS changes nothing for it: it sends no new field and reads no new code, and a sale to
a terminal that signs in reads as any sale.

`SASQ` is ISO 20022's `RetailerMessage1Code` `SASQ`: "Request the management of a session:
login, logout and diagnosis services. Initiated by the Sale system." ISO 20022 has no message by
which a terminal asks for a login: `LoginNeeded` is the middleware's own name. `LoginRequest` is
named after ISO 20022's `LoginRequest`, of `SessionManagementRequest9`, "Content of the Login
Request message.", and carries none of its elements. `LoginResponse` is named after ISO 20022's
`LoginResponse`, the block a POI sends to answer a login, of `SessionManagementResponse9`,
"Content of the Login Response message.", and carries none of its elements either. Each
definition is ISO's, from M3 (Sources, below).

### When to ask

**Declare it.** Send `SASQ` in `Mw-Message-Functions` on every upgrade, once the terminal does
all this section says. Declaring `SASQ` declares that the terminal can be woken.

**Wake.** Given an `Instruction` while it is asleep, its screen off or its application not in
front, a terminal that declared `SASQ` turns the screen on and brings its payment screen to the
front over the lock screen, then asks if it holds no session. The middleware cannot see the
screen, and neither can a conformance run, so this is the contract's rule alone.

**Ask.** A terminal asks only while it holds no session at its fleet's payment system: on an
`Instruction`, or at connect where it knows it holds none, which takes the round trip off the
sale's path. It asks at most once a connection, unless its fleet's payment system refused what it
was sent. For each asking it makes a fresh P-256 key pair in memory, not in its keystore, and
sends one `LoginNeeded` holding the public key, then reads the answer before its next frame, as
Refusal, below, asks of every frame.

### The ask: `LoginNeeded`

The terminal to the middleware, on a connection whose upgrade declared `SASQ`:

```json
{ "MessageType": "LoginNeeded", "RecipientKey": { "PublicKey": "BP6MGc4JBRkevCmKkkV5JTHybwzs4kYGOei8Oct_cGqCanebTPlpuKDlOcf2L7PTCtaqj4DjDx0Siq_WiiznLqA", "Signature": "MEQCIBERERERERERERERERERERERERERERERERERERERERERAiAiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIg" } }
```

Its `PublicKey` is the worked vector's (The worked vector, below), and its `Signature` is filler
of a signature's shape, made by no key.

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `terminal` | `LoginNeeded` |
| `RecipientKey` | `terminal` | The key the answer is sealed to: the public part of a fresh P-256 key pair the terminal made for this one asking, in memory and not in its keystore. Absent, or not an object, and the ask is refused `recipient_key_invalid` |
| `RecipientKey.PublicKey` | `terminal` | The key's 65 bytes as RFC 9180 § 7.1.1 serialises a P-256 key, uncompressed: `0x04`, then X and Y, which are the last 65 bytes of the key's SubjectPublicKeyInfo. In base64url with no padding, 87 characters |
| `RecipientKey.Signature` | `terminal` | A DER ECDSA P-256 SHA-256 signature by the key of the certificate the connection presented, over the bytes below, in base64url with no padding. Required on a connection made with a certificate. Absent on a sandbox key's connection |

**The key and its signature.** The fresh key's public part is its 65 bytes, uncompressed, in
base64url with no padding: 87 characters. On a connection made with a certificate, the terminal
signs the fresh public key with the key of the certificate the connection presented: the keystore
key it signs the connection's TLS with, which needs no person to unlock it, so it signs while the
device sleeps. During a renewal's overlap, that is the certificate the connection presented, and
not the newer one. The signature is DER ECDSA P-256 SHA-256, as a keystore's `SHA256withECDSA`
makes it, in base64url with no padding, over `mw-signin-recipient-v1`, a zero byte, the
`POIIdentification`'s bytes, a zero byte and the 65 bytes of the public key. On a sandbox key's
connection, which has no enrolled key, send no signature: one sent there is ignored, unchecked.

A `PublicKey` that is not 65 bytes in base64url, does not start `0x04` or is not a point on P-256,
and on a certificate's connection a `Signature` that is absent, malformed or does not verify, are
refused `recipient_key_invalid`, and nothing is counted. A key's shape is checked before anything
is read; its `Signature` is checked after the connection's standing, so a terminal that may no
longer hold its connection is answered `terminal_not_permitted` first. Any other key of an ask is
dropped by its path and named in the middleware's log, its value unread. The log holds
`PublicKey` and `Signature` as `<withheld>`.

### The answer: `LoginRequest`

The middleware to the terminal, on the connection that asked, once for each ask it answers. The
terminal reports what it did with it in one `LoginResponse` (The report, below):

```json
{ "MessageType": "LoginRequest", "Sealed": { "Suite": { "Kem": "0x0010", "Kdf": "0x0001", "Aead": "0x0001" }, "EncapsulatedKey": "BKknGcYZXVCFEE9GmouYFNWDj_crYFAeLERm5eZ7MlrJhTbXthoa9LeOW3-VHAkAvoY8QDzmXJv8uTgmVyItGMQ", "Ciphertext": "lBCfkZ_DE_rUYr4T8YvnPkwWL-HGT2pnyH-9m9966nZyzqH9DDcJvw8t5m2Axq_0jy7Rpl0Ikp1eSwtuyjMilpbQHFbebpvOk_WCMtWZVtgzXxVKbQP_5aZwD-ClLG-3cfl2CiUm_QYJWIJ93O3aII6uQKYYTKY3SFZZPccdgJdiD0clDN4ET8Q8S6S5UfDaYMJUenbeiXxsFTnDRIsUzpfRPyguEBLpb9vrnNkf2NFvMwRZTb6rfnB84Z0kITHiiIDpSAAgSDaE5f3VSPPakIIR_9-b2_ruJJAprjwvKhBKg2CSeZKkV_3L16mbFpGn3F-VyaHcBQ" } }
```

It is the worked vector's (The worked vector, below), a vector of the seal, whose plaintext
holds the group's first four keys alone. An answer's `Ciphertext`, opened, gives the
`SignedValue` group: its four keys, `Adapter`, `KeyIdentification`, `Challenge` and `Signature`,
then `LoginReference`, then each of `AcceptorIdentification`, `UserName` and
`ApplicationIdentification` the terminal's store holds, in that order. A key absent is a value
the store does not hold. Here, the group of a store that holds all three:

```json
{ "Adapter": "signed_value", "KeyIdentification": "key-example-1", "Challenge": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "Signature": "WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlo=", "LoginReference": "lgn_0123456789abcdef0123456789abcdef", "AcceptorIdentification": "merchant-example-1", "UserName": "user-example-1", "ApplicationIdentification": "app-example-1" }
```

Its `Challenge` is the worked vector's, its `Signature` is filler of a signature's shape, made by
no key, and its other values are made up, no fleet's. A store that holds none of the three is
sent the four keys and `LoginReference` alone.

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `mw` | `LoginRequest` |
| `Sealed` | `mw` | The answer, sealed to the ask's `RecipientKey` (Opening the answer, below). ISO 20022 has no element for it: the name is the middleware's own |
| `Sealed.Suite` | `mw` | RFC 9180's ids, as the RFC writes them, `0x` and four hex digits in upper case: `Kem` `0x0010`, `Kdf` `0x0001` and `Aead` `0x0001` in this version. A later suite is another value, and a terminal refuses a suite it does not take |
| `Sealed.EncapsulatedKey` | `mw` | RFC 9180's `enc`, the sender's ephemeral public key, fresh for each answer, in base64url with no padding: under KEM `0x0010`, 65 bytes, 87 characters. A public key: the middleware's log holds it as it is |
| `Sealed.Ciphertext` | `mw` | RFC 9180's single-shot seal of the group's JSON, the AEAD's 16-byte tag last, in base64url with no padding. The middleware's log holds it as `<withheld>` |
| `SignedValue` | `mw` | Sealed: the group the plaintext is the JSON of. ISO 20022 has no element for it: the name is the middleware's own |
| `SignedValue.Adapter` | `mw` | Sealed: what made the group, `signed_value`, or `sandbox_signed_value` in the sandbox. A later kind seals a group of its own, told apart by its `Adapter` |
| `SignedValue.KeyIdentification` | `mw` | Sealed: ISO 20022's `KeyIdentification`, "Identification of the cryptographic key.", here the id of the fleet's key at its payment system, as the fleet set it |
| `SignedValue.Challenge` | `mw` | Sealed: the random value signed, as text: lowercase hex, base64url with no padding, or a version 4 UUID's 36 characters in lowercase, as the fleet's credential says. ISO 20022 has no element for it: the name is the middleware's own |
| `SignedValue.Signature` | `mw` | Sealed: the MAC over `Challenge`'s ASCII bytes, written as the fleet's credential says. ISO 20022 has no element for it: the name is the middleware's own |
| `SignedValue.LoginReference` | `mw` | Sealed: the middleware's name for this one answer, `lgn_` then 32 lowercase hex characters, drawn for each answer, so every group holds one. Name it in the `LoginResponse` that reports the answer (The report, below). Not a secret. ISO 20022 has no element for it: the name is the middleware's own |
| `SignedValue.AcceptorIdentification` | `mw` | Sealed: ISO 20022's `AcceptorIdentification`, "Identification of the card acceptor performing the transaction.", here the store's own number at its fleet's payment system: which of the fleet's merchants the terminal signs in for. Absent where the store holds none |
| `SignedValue.UserName` | `mw` | Sealed: ISO 20022's `UserName`, "User name identifying the client.", here the merchant user the fleet named for the store at its payment system. It names an account, never a person or an e-mail address. Absent where the store holds none |
| `SignedValue.ApplicationIdentification` | `mw` | Sealed: ISO 20022's `ApplicationIdentification`, "Identification of the payment application, user of the acquirer protocol.", here the fleet's payment application, as the credential the fleet set for the store names it. Absent where the store holds none |

Ignore any key not named here, at any depth: a later version may add some.

### Opening the answer

1. Check `Sealed.Suite`, and open only a suite the terminal takes: in this version, `Kem`
   `0x0010`, `Kdf` `0x0001` and `Aead` `0x0001`.
2. Under KEM `0x0010`, check `Sealed.EncapsulatedKey` is a point on P-256 before the key
   agreement, as RFC 9180 § 7.1.4 asks of a recipient.
3. Open `Sealed.Ciphertext` by RFC 9180's base mode, `mode_base`, single-shot, with the fresh
   key's private part, under the suite KEM `0x0010`, DHKEM(P-256, HKDF-SHA256), KDF `0x0001`,
   HKDF-SHA256, and AEAD `0x0001`, AES-128-GCM. `info` is 58 bytes: `mw-signin-v1`, a zero
   byte, `LoginRequest`, a zero byte, and the SHA-256 of the `POIIdentification`'s bytes, a zero
   byte and the 32 bytes of the connection's credential id. The credential id is the SHA-256 of
   the DER of the certificate the connection presented, as the middleware's log gives it in
   `credential_id`, or on a sandbox key's connection the SHA-256 of the whole key's text, `sbx_`
   included. `aad` is empty: zero bytes. An answer moved to another terminal or another
   connection does not open.
4. Drop the private key once the answer is opened, or fails to open.
5. Treat the opened group as input, not proof of its sender: base mode keeps the answer secret to
   the terminal, and does not prove who sealed it.

| Part of `info` | Bytes |
|---|---|
| `mw-signin-v1`, in ASCII | 12 |
| A zero byte | 1 |
| `LoginRequest`, in ASCII | 12 |
| A zero byte | 1 |
| The SHA-256 of the `POIIdentification`'s bytes, a zero byte and the 32 bytes of the credential id | 32 |

### What to do with it

The terminal takes the opened `SignedValue` to its fleet's payment system itself, in its own
sign-in request, with whatever else that system needs that the terminal holds, such as its
serial. With the signed value, it sends that system `AcceptorIdentification`, `UserName` and
`ApplicationIdentification` as it needs them. A key absent is a value the store does not hold,
so it sends that system's own default for it, or none. It keeps the session while its process
lives, and starts the sale on the path its application takes for a sale it starts itself. It
does not sign out when its screen leaves the front. It asks again only when its fleet's payment
system refuses the session. Never log, store or send back `Challenge`, `Signature` or the fresh
private key, and never log the session. Then report what that system answered (The report,
below).

### The report: `LoginResponse`

The terminal to the middleware, on the connection that asked, once it has tried its fleet's
payment system with an opened answer: one `LoginResponse` naming the group's `LoginReference`,
before its next frame of sign-in. Send `SUCC` if that system opened a session with what it was
sent, or `FAIL` with the code that fits. Put nothing that system said in the report.

```json
{ "MessageType": "LoginResponse", "LoginReference": "lgn_0123456789abcdef0123456789abcdef", "Response": "SUCC" }
{ "MessageType": "LoginResponse", "LoginReference": "lgn_0123456789abcdef0123456789abcdef", "Response": "FAIL", "ResponseReason": "not_covered" }
```

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `terminal` | `LoginResponse` |
| `LoginReference` | `terminal` | The opened group's `LoginReference`, as the group held it: `lgn_` then 32 lowercase hex characters. ISO 20022 has no element for it: the name is the middleware's own. The middleware's log holds it as `<withheld>` in the report's `in` line, and names it in the line of a report taken |
| `Response` | `terminal` | `SUCC`, ISO's "Processing OK. [...]": its fleet's system opened a session with what it was sent. `FAIL`, ISO's "Processing of the request fails for various reasons. [...]": it did not. ISO 20022's `Response11Code`, of which the middleware takes these two: `WARN` is not taken |
| `ResponseReason` | `terminal` | With `FAIL`, and required with it; never with `SUCC`. One of the three codes below, the middleware's own: ISO 20022 has the name and not these codes |

| `ResponseReason` | What the fleet's payment system did |
|---|---|
| `not_covered` | The fleet's system answered that the key does not cover the merchant it was sent for |
| `not_accepted` | It refused the sign-in for any other reason |
| `no_answer` | It did not answer, or could not be reached |

Send no other key: any other key of a report is dropped by its path and named in the
middleware's log, its value unread.

**What the middleware does with it.** A report the middleware takes gets no frame back, and nor
does one naming no answer the middleware holds as the terminal's last one not yet reported: a
second report of one answer, a report of an answer before the last, or a `LoginReference` no
answer had. A report naming no such answer changes nothing: its `in` line, and a `fields_dropped`
line for any key it may not hold, are the only lines it gets. A `Refusal` of a report is a bug in
the terminal, apart from two: after `terminal_not_permitted`, close the connection and reconnect
with the backoff Reconnect, above, gives; after `sign_in_unavailable`, go on as the report's
`Response` says, without sending the report again, and ask again no sooner than 60 seconds
later. A report holding two faults is refused for the first of `missing_field`,
`invalid_result` and `invalid_reference`, in that order. None of these refusals closes the
connection (Refusal, below).

**After the report.** After a `FAIL` other than `not_covered` that follows a `SUCC`, or is the
terminal's first, ask again at once, once: the middleware answers that one ask inside its
interval. If that ask is refused `sign_in_limited`, the middleware counted a failure the
terminal did not see, so wait 60 seconds. After any other `FAIL`, `not_covered` among them, ask
again no sooner than 60 seconds later. After `not_covered`, also tell someone: the store's
credential does not cover the merchant it was sent for, and asking again does not change that.

### The two cases, and the other refusals

**No credential at the store.** The ask is refused `sign_in_not_available`, and a terminal signed
out is normal: answer the sale `RJCT` with `AB11`, unless a person signs in at the terminal by its
fleet's own means, and ask no more on that connection.

**A credential attached.** The terminal is woken, signs in with what it is sent, reports what
its fleet's payment system answered, and takes the sale.

Answer a sale the terminal cannot start for want of a session `RJCT` with `AB11` (Which
`TransactionStatus` to send, below). After the other refusals of an ask, and after an answer
that does not open:

- `recipient_key_invalid`: a bug in the terminal, in its key or its signature, so alert someone.
- After `sign_in_limited` or `sign_in_unavailable`, or no answer in 20 seconds, answer the sale
  `RJCT` with `AB11`, and ask again no sooner than 60 seconds later.
- After `terminal_not_permitted` on an ask, close the connection, reconnect with the backoff
  Reconnect, above, gives, and ask again once a connection is accepted.
- A `LoginRequest` that does not open, or that names a suite the terminal does not take, is
  treated as `sign_in_unavailable`: answer the sale `RJCT` with `AB11`, and ask again no sooner
  than 60 seconds later. Nothing is reported for it: no group was opened, so there is no
  `LoginReference` to name.

At the day's cap of `sign_in_limited`, `MW_SIGNIN_PER_DAY` answers, the middleware writes an
`ERROR` line.

None of these refusals closes the connection (Refusal, below).

### The worked vector

Check an implementation against these numbers. Each is a published test value, no fleet's: the
sender's seed and the recipient's key pair are RFC 9180 § A.3.1's, and the group is the sandbox's
stand-in, signed under the sandbox's published secret. The middleware draws a fresh seed for each
answer it seals.

| Input | Value |
|---|---|
| The sender's seed, RFC 9180's `ikmE`, 32 bytes in hex | `4270e54ffd08d79d5928020af4686d8f6b7d35dbe470265f1f5aa22816ce860e` |
| The recipient's public key, RFC 9180's `pkRm`, 65 bytes in hex | `04fe8c19ce0905191ebc298a9245792531f26f0cece2460639e8bc39cb7f706a826a779b4cf969b8a0e539c7f62fb3d30ad6aa8f80e30f1d128aafd68a2ce72ea0` |
| The same as `RecipientKey.PublicKey`, base64url, 87 characters | `BP6MGc4JBRkevCmKkkV5JTHybwzs4kYGOei8Oct_cGqCanebTPlpuKDlOcf2L7PTCtaqj4DjDx0Siq_WiiznLqA` |
| The recipient's private key, RFC 9180's `skRm`, 32 bytes in hex | `f3ce7fdae57e1a310d87f1ebbde6f328be0a99cdbcadf4d6589cf29de4b8ffd2` |
| `POIIdentification` | `poi_00000000000000000000000000000001` |
| The connection's credential id, 32 bytes in hex | `1111111111111111111111111111111111111111111111111111111111111111` |
| `aad` | Empty |

| Part of `info` | Bytes | Hex |
|---|---|---|
| `mw-signin-v1` | 12 | `6d772d7369676e696e2d7631` |
| A zero byte | 1 | `00` |
| `LoginRequest` | 12 | `4c6f67696e52657175657374` |
| A zero byte | 1 | `00` |
| The SHA-256 of `poi_00000000000000000000000000000001`, a zero byte and the 32 bytes `0x11` | 32 | `8164e98764b8b73b59d9c5fccf93d51bc4e0c1de89f439782c900f2bff0122f9` |

`info` whole, 58 bytes in hex: `6d772d7369676e696e2d7631004c6f67696e52657175657374008164e98764b8b73b59d9c5fccf93d51bc4e0c1de89f439782c900f2bff0122f9`

The group: `Challenge` is `000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f`, the bytes `0x00` to `0x1f` as lowercase hex, and
`Signature` is `508243bbe4b0b05d1c6cb8d87375136553b5d64eef666c55fe7b66c370e97c4a`, the HMAC-SHA256 of that challenge's 64 ASCII characters keyed with
the bytes of the sandbox's published secret, `mw-sandbox-signin-secret-published-not-secret`, as lowercase hex. The plaintext is
the group's JSON, 231 bytes of UTF-8 with no whitespace:

```json
{"Adapter":"sandbox_signed_value","KeyIdentification":"sandbox-signin-1","Challenge":"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f","Signature":"508243bbe4b0b05d1c6cb8d87375136553b5d64eef666c55fe7b66c370e97c4a"}
```

| Output | Value |
|---|---|
| `Sealed.EncapsulatedKey`, RFC 9180's `enc`, 65 bytes in hex, RFC 9180 § A.3.1's `pkEm` | `04a92719c6195d5085104f469a8b9814d5838ff72b60501e2c4466e5e67b325ac98536d7b61a1af4b78e5b7f951c0900be863c403ce65c9bfcb9382657222d18c4` |
| The same in base64url, 87 characters | `BKknGcYZXVCFEE9GmouYFNWDj_crYFAeLERm5eZ7MlrJhTbXthoa9LeOW3-VHAkAvoY8QDzmXJv8uTgmVyItGMQ` |
| `Sealed.Ciphertext`, 247 bytes in hex: the plaintext's 231 and the tag's 16 | `94109f919fc313fad462be13f18be73e4c162fe1c64f6a67c87fbd9bdf7aea7672cea1fd0c3709bf0f2de66d80c6aff48f2ed1a65d08929d5e4b0b6eca33229696d01c56de6e9bce93f58232d59956d8335f154a6d03ffe5a6700fe0a52c6fb771f9760a2526fd060958827ddcedda208eae40a6184ca6374856593dc71d8097620f47250cde044fc43c4ba4b951f0da60c2547a76de897c6c1539c3448b14ce97d13f282e1012e96fdbeb9cd91fd8d16f3304594dbeab7e707ce19d242131e28880e9480020483684e5fdd548f3da908211ffdf9bdbfaee249029ae3c2f2a104a8360927992a457fdcbd7a99b1691a7dc5f95c9a1dc05` |
| The same in base64url, 330 characters | `lBCfkZ_DE_rUYr4T8YvnPkwWL-HGT2pnyH-9m9966nZyzqH9DDcJvw8t5m2Axq_0jy7Rpl0Ikp1eSwtuyjMilpbQHFbebpvOk_WCMtWZVtgzXxVKbQP_5aZwD-ClLG-3cfl2CiUm_QYJWIJ93O3aII6uQKYYTKY3SFZZPccdgJdiD0clDN4ET8Q8S6S5UfDaYMJUenbeiXxsFTnDRIsUzpfRPyguEBLpb9vrnNkf2NFvMwRZTb6rfnB84Z0kITHiiIDpSAAgSDaE5f3VSPPakIIR_9-b2_ruJJAprjwvKhBKg2CSeZKkV_3L16mbFpGn3F-VyaHcBQ` |

Opened with the private key above, `enc`, this `info` and an empty `aad`, the ciphertext gives the
plaintext above. The answer, above, shows the `LoginRequest` that carries it. This plaintext is a
vector of the seal: an answer's group also carries `LoginReference` after `Signature`, and then
each of `AcceptorIdentification`, `UserName` and `ApplicationIdentification` the store holds, as
the group the answer, above, shows does, and its ciphertext opens the same way.

## Which `TransactionStatus` to send

| What happened | Send |
|---|---|
| The host approved the whole `TotalAmount` | `ACSP` |
| The host or the card declined | `RJCT`, `Reason` `AG07` |
| The customer cancelled at the terminal, or the terminal gave up, before anything reached the host | `RJCT`, `Reason` `AB11` |
| An `Abort` for the payment came before the payment reached the host, and the terminal stopped it (Abort, above) | `RJCT`, `Reason` `DS02` |
| An `Abort` for the payment came once the payment was with the host | What the host answers, by the other rows. Never `DS02` |
| The host did not answer, and a reversal confirmed no charge | `RJCT`, `Reason` `AB11` |
| The host approved, then the terminal reversed it, or the host approved only part of the amount and the terminal reversed that | `RJCT`, `Reason` `AB11`. `ACSP` always means the whole `TotalAmount` |
| The terminal does not know whether a payment was taken | **Nothing yet.** Find out: ask the host for the payment by its stored reference, or reverse it and wait for the host to confirm the reversal. Then send the answer as soon as it comes (The paths, step by step, below). Until then it is still busy |
| A refund: the host refunded the whole `TotalAmount` | `ACSP` |
| A refund: the host declined the refund, its own cap on the sale's refunds among its reasons | `RJCT`, `Reason` `AG07` |
| A refund: no refund was made any other way, such as a cancel at the terminal, a host that did not answer where a reversal confirmed none, or a kind of payment the terminal cannot refund | `RJCT`, `Reason` `AB11` |
| A refund: an `Abort` for it came before it reached the host, and the terminal stopped it | `RJCT`, `Reason` `DS02`: no refund was made |

A refund's other ends are a sale's: a terminal that does not know whether a refund was made
sends nothing yet, and stays busy until it finds out, and `ACSP` always means the whole
`TotalAmount` was refunded.

`ACSP` means the whole `TotalAmount` was approved, and nothing more. This contract has no
partial approval, and a terminal adds no surcharge, tip or fee to `TotalAmount` (What to
charge, in Instruction, above): a terminal that approves less, or charges more, is outside it,
and the `TransactionDetails.AuthorisedAmount` its approval states shows the difference
(Outcome, below).
Send `RJCT` only when no payment was taken, and always with its `Reason` in
`StatusReasonInformation`: `AG07` when the host or the card declined, `DS02` when the terminal
stopped the payment in answer to an `Abort`, and `AB11` for every other way no payment was taken,
a cancel at the terminal among them. Send `DS02` only in answer to an `Abort`. `PDNG` and `UNKN`
are what a POS reads, and a terminal never sends either: `UNKN` is the middleware's own code.

A terminal that does not know whether a payment was taken must find out, and never ends with
nothing: it asks its host, or reverses the payment, until it has an answer, and sends it as soon
as it knows (The paths, step by step, below). `RJCT` tells the POS that no payment was taken and
to take another tender, so send it after a reversal only once the host has confirmed the
reversal. A reversal only queued is not a confirmed one: it may never land, and the customer
would pay twice.

## The codes, as ISO 20022 defines them

`TransactionStatus` is ISO 20022's `TransactionStatus` (`TxSts`) of a payment's status
report, `pacs.002.001.16` and `pain.002.001.15` (M5), and its codes are ISO's
`ExternalPaymentTransactionStatus1Code`. `Reason` is ISO's
`StatusReasonInformation/Reason/Code` (`StsRsnInf/Rsn/Cd`) of the same messages, and its
codes are ISO's `ExternalStatusReason1Code`. These are the messages a bank and NPP report a
payment's status in: NPP's answer to a payment, and its notice of a timeout, are each a
`pacs.002` (N1), and a rejection's reason is a code (N2). So a terminal on another rail
reports in the same fields.
Each definition below is ISO's, ISO's spelling kept, with `<br>` as ISO's line break: the
definitions from M1 and the names from M2 (Sources, below).

| Code | ISO's name | ISO's definition | What it means here |
|---|---|---|---|
| `ACSP` | AcceptedSettlementInProcess | "All preceding checks such as technical validation and customer profile were successful and therefore the payment instruction has been accepted for execution." | The host approved the whole `TotalAmount` |
| `RJCT` | Rejected | "Payment instruction has been rejected." | No payment was taken, and `Reason` says why |
| `AG07` | UnsuccesfulDirectDebit | "Debtor account cannot be debited for a generic reason.<br>Code value may be used in general purposes and as a replacement for AM04 if debtor bank does not reveal its customer's insufficient funds for privacy reasons" | The host or the card declined. The host's own reason travels in `ResponseCode` |
| `AB11` | TimeoutDebtorAgent | "Transaction stopped due to timeout at the Debtor Agent." | No payment was taken otherwise: a cancel at the terminal, a host that did not answer where a reversal confirmed no charge, an approval the terminal reversed, or an instruction the terminal never received or did not start |
| `DS02` | OrderCancelled | "An authorized user has cancelled the order" | The terminal stopped the payment, before it reached its host, in answer to an `Abort` (Abort, above). Sent only in answer to an `Abort`. On a refund, no refund was made |
| `PDNG` | Pending | "Payment instruction is pending. Further checks and status update will be performed." | What a POS reads while the sale waits for the outcome. A terminal never sends it |
| `UNKN` | | ISO's code set has no code for unknown or in doubt, so this one is the middleware's own | What a POS reads when the middleware does not know. A terminal never sends it |

## Resending is safe

Resending is safe, and the only safe change is none. The middleware does not acknowledge an
outcome, so a terminal cannot be sure one arrived.

- Store the frame before sending it.
- Treat an outcome as taken once any later frame but a Close has come from the middleware on the
  same connection, such as a Ping or an `Instruction`, with no `Refusal` for it. On a library
  that never shows a Ping, it is the next text frame (Hold, above). That
  frame shows the connection was still alive after the outcome went. A `Refusal` that
  comes later is still about it while it is the last frame sent (Refusal, below). This
  decides when the terminal goes on to its next payment, and does not end the resend below.
- After any reconnect, send your most recent outcome again, unchanged, whether or not you
  think it arrived, and judge it there the same way. That covers a drop, a restart of the
  terminal, a close after 75 seconds of silence (Hold, above), a newer connection
  replacing this one, where the middleware sends what was queued for it and then a Close, and a
  `Refusal` on it can be lost (Reconnect, above), and the middleware closing the connection
  because its store could not take the outcome.
- Stop sending it again when a new `Instruction` arrives, when the middleware answers it with any
  `Refusal` but `terminal_not_permitted`, or 23 hours after you first sent it. After a
  `Refusal`, do not resend that frame (Refusal, below), with one exception: after
  `terminal_not_permitted`, keep the outcome, close the connection, reconnect, and send it
  again. 23 hours stays inside the middleware's default retention of 24 hours (Deadline, above),
  so a terminal left idle does not end on a `not_held` an operator would have to read.
- This resend is the only recovery for an outcome the middleware closed the connection on and
  could not record, because the middleware sends no acknowledgement. It replaces any judgement of
  how soon a close must follow a send: the middleware may take several seconds to close when its
  store is slow.
- A repeat of what the middleware holds changes no sale and gets no reply, so sending again after a
  reconnect is always safe. On one connection, send a sale's outcome at most once, and
  never again on a timer: each repeat is another line in the middleware's log. The sandbox's
  conformance run fails a terminal it sees repeating an outcome on one connection, and a
  green run does not prove a terminal never does.
- A different `TransactionStatus` or `Reason`, or a different value under one path of
  `PaymentReference`, its group and key, is a contradiction: the sale reads `UNKN` for
  good. An outcome that only adds a key is a repeat, and so is one whose `ResponseCode`,
  `AdditionalInformation` or `TransactionDetails.AuthorisedAmount` alone differs: the amount
  first applied stands. A key of the same name in two groups is two keys.
- The middleware queues a refused frame's `Refusal` on the frame's own connection as soon as it has
  read and judged the frame. On a connection that stays open, it is lost only where the middleware
  cannot queue it: on a connection a newer one has replaced, and on one where 8 frames
  already wait because the terminal is not reading them. A connection that ends, by a drop,
  a write that fails, the end of a takeover's drain, the middleware closing it on a store failure,
  or the middleware stopping, can take a queued `Refusal` with it. The connection closing is the
  sign: send the outcome again after the reconnect, as above.

## Outcome

The terminal to the middleware. An approval, then a decline:

```json
{ "MessageType": "Outcome", "TransactionReference": "sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a", "TransactionDateTime": "2026-11-06T15:12:40+11:00", "TransactionStatus": "ACSP", "StatusReasonInformation": { "ResponseCode": "00", "AdditionalInformation": "APPROVED" }, "TransactionDetails": { "AuthorisedAmount": "12.50" }, "PaymentReference": { "Card": { "RetrievalReferenceNumber": "631012345678", "SystemTraceAuditNumber": "000123", "AuthorisationCode": "A1B2C3", "AcquirerPOIIdentification": "12345678", "AcquirerMerchantIdentification": "987654321", "RefundReference": "klujhadsc9ph87asd" } } }
{ "MessageType": "Outcome", "TransactionReference": "sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a", "TransactionStatus": "RJCT", "StatusReasonInformation": { "Reason": "AG07", "ResponseCode": "05", "AdditionalInformation": "DECLINED" } }
```

| Field | Sent by | Required | Rule | On a receipt? |
|---|---|---|---|---|
| `MessageType` | `terminal` | Yes | `Outcome` | |
| `TransactionReference` | `terminal` | Yes | The instruction's, returned as received. The matching key | |
| `TransactionStatus` | `terminal` | Yes | `ACSP` or `RJCT`, in upper case, as Which `TransactionStatus` to send, above, says. Absent is `missing_field`, and anything else, a value that is not a string included, is `invalid_result` | Yes, as the result |
| `StatusReasonInformation` | `terminal` | With `RJCT` | An object holding the three fields below. Anything else is dropped whole | |
| `StatusReasonInformation.Reason` | `terminal` | With `RJCT` | `AG07`, `AB11` or `DS02`, `DS02` only in answer to an `Abort`. With `RJCT`, absent is `missing_field` and anything else `invalid_result`. With `ACSP` it is dropped alone | |
| `StatusReasonInformation.ResponseCode` | `terminal` | No | `^[A-Za-z0-9]{1,3}$`, the card host's code, on a card payment only | Yes |
| `StatusReasonInformation.AdditionalInformation` | `terminal` | No | The host's text: `^[A-Za-z0-9.,'&()/+%#-]([A-Za-z0-9 .,'&()/+%#-]{0,33}[A-Za-z0-9.,'&()/+%#-])?$`, with at most 8 digits in total | Yes |
| `TransactionDetails` | `terminal` | No | An object holding `AuthorisedAmount` alone, with `ACSP`. ISO also has `TotalAmount` here: leave it out, since the total is the middleware's to state. Anything else is dropped whole, and another key in it is dropped by its path | |
| `TransactionDetails.AuthorisedAmount` | `terminal` | No: send it with every `ACSP` | The amount the host approved, an amount such as `12.50`: what the customer was charged, or on a refund what was refunded. Send it with `ACSP`, equal to the instruction's `TotalAmount`. With `RJCT` it is dropped alone, since no payment was taken. Absent, the outcome still applies, and states no amount | |
| `TransactionDateTime` | `terminal` | No | The terminal clock, as it states it, at most 35 characters: `^[0-9]{4}-(0[1-9]\|1[0-2])-(0[1-9]\|[12][0-9]\|3[01])T([01][0-9]\|2[0-3]):[0-5][0-9]:([0-5][0-9]\|60)(\.[0-9]{1,9})?(Z\|[+-]([01][0-9]\|2[0-3]):[0-5][0-9])$` | Yes |
| `PaymentReference` | `terminal` | No | An object of up to four groups, `Card`, `Bank`, `Wallet` and `NPP`, each holding its own keys (References by kind, below) | |

`TransactionReference` is the matching key: the middleware finds the sale by it, among the sales it
holds for this terminal. The middleware passes to the POS, unchanged, what passed of
`StatusReasonInformation` and of `PaymentReference`, each reference under the same group and
key, for its receipt, a refund and matching settlement, and the amount the host approved.
`TransactionDateTime` is checked for shape and never for truth: the middleware logs it
unchanged, uses it for no ordering, deadline or decision, and does not pass it to the POS, so
a terminal clock set wrong changes nothing.

**The amount the host approved.** With every `ACSP`, send `TransactionDetails.AuthorisedAmount`,
alone in that group: what the customer was charged, or on a refund what was refunded, equal to
the instruction's `TotalAmount`, since a terminal adds nothing to it (What to charge, in
Instruction, above). `AuthorisedAmount` is ISO 20022's `AuthorisedAmount` (`AuthrsdAmt`) of
`CardPaymentTransactionDetails54`: "Amount authorised for the payment transaction." (M3). ISO
nests it in `TransactionDetails` beside a required `TotalAmount`: leave `TotalAmount` out of
`TransactionDetails`, since the total is the middleware's to state, and one sent is dropped by
its path. With `RJCT` no payment was taken, so none was approved, and an `AuthorisedAmount` sent
with it is dropped alone. An approval without it still applies, and states no amount, as a
terminal built before it sends. The middleware passes it to the POS, and an approval that
states an amount other than `TotalAmount` is logged as `amount_differs`: the POS records the
amount charged, or on a refund refunded, and the terminal has broken this contract.

**Send nothing else, and never a card number, an expiry, track data, a cardholder name or a
bank account.** A receipt printed from these fields has no masked card number and no card
scheme: a printed card line stays on the terminal's own receipt. As a safety net, the middleware
drops any other field and logs its name, never its value. The schema in
`docs/api/openapi.yaml` is strict on this frame, because it states what a terminal must
send.

## References by kind

`PaymentReference` holds the payment's references, grouped by the kind of payment that gave
them: one group for each kind, below. Send the group of the kind the payment was, holding the
keys its issuer gave and no others. Every key is optional. A group or a key not listed here
is dropped by its path, its value unread, and a value that fails its pattern is dropped
alone (A value that fails is dropped alone, below). The last column of each table says what
a POS does with the key: prints it on a receipt, keeps it to refund against, or matches the
payment on a statement or settlement report by it.

**The reference text rule.** Six keys hold free text whose issuer sets its format:
`Card.RefundReference`, `Bank.AccountServicerReference`,
`Wallet.RecipientTransactionIdentification`, and the three `NPP` keys. Each holds 1 to 35
ASCII letters, digits and `. _ : / # -`, 64 on `Wallet.RecipientTransactionIdentification`,
with at most 12 digits in total, and `Wallet.RecipientTransactionIdentification` also holds a
UUID. So none holds `@`, `+` or a space, or a card number of 13 to 19 digits however it is
written, with one exception: a card number padded into a UUID's shape fits
`Wallet.RecipientTransactionIdentification`, which holds a UUID. That takes intent. A numeric
id of more than 12 digits is dropped alone until a provider that issues one is integrated.

### `Card`: a card payment

A card payment, through a card terminal and its card host. A card terminal sends it on an
outcome its card host answered, holding the host's references and never card data.

| Key | Pattern | What a POS does with it |
|---|---|---|
| `RetrievalReferenceNumber` | `^[A-Za-z0-9]{1,12}$` | Prints it on a receipt, and matches settlement by it |
| `SystemTraceAuditNumber` | `^[0-9]{6}$`, zero filled | Prints it on a receipt, and matches settlement by it |
| `AuthorisationCode` | `^[A-Za-z0-9]{1,6}$` | Prints it on a receipt, and matches settlement by it |
| `AcquirerPOIIdentification` | `^[A-Za-z0-9]{1,8}$`, the acquirer's terminal id | Prints it on a receipt, and matches settlement by it |
| `AcquirerMerchantIdentification` | `^[A-Za-z0-9]{1,15}$`, the acquirer's merchant id. A card number of 13 to 15 digits fits this pattern: the middleware forbids it here and cannot detect it | Prints it on a receipt, and matches settlement by it |
| `RefundReference` | The host's reference for a later refund, by the reference text rule: `^[A-Za-z0-9._:/#-]{1,35}$`, with at most 12 digits in total | Keeps it to refund against. Not on a receipt |

### `Bank`: a payment by the account's own bank

A payment from a bank account by the account's own bank, outside a card scheme and NPP. A
terminal sends it when that bank gave a reference.

| Key | Pattern | What a POS does with it |
|---|---|---|
| `AccountServicerReference` | The reference the account's own bank gave the payment, never the account, by the reference text rule: `^[A-Za-z0-9._:/#-]{1,35}$`, with at most 12 digits in total | Prints it on a receipt, and matches settlement by it |

### `Wallet`: a payment through a wallet or payment app

A payment through a wallet or payment app. A terminal that took the payment that way sends
it, naming the provider, and with the provider's id for the payment when it gave one.

| Key | Pattern | What a POS does with it |
|---|---|---|
| `ProviderIdentification` | The wallet's or payment app's provider, by name: `^[A-Za-z][A-Za-z0-9._-]{0,34}$`, with at most 4 digits in total | Prints it on a receipt |
| `RecipientTransactionIdentification` | The provider's id for the payment, by the reference text rule at 64 characters: `^[A-Za-z0-9._:/#-]{1,64}$`, with at most 12 digits in total, or a UUID such as `3fa85f64-5717-4562-b3fc-2c963f66afa6` | Prints it on a receipt, keeps it to refund against, and matches settlement by it |

### `NPP`: a payment over the New Payments Platform

A payment over Australia's New Payments Platform, PayTo included: a PayTo payment is an NPP
payment under a mandate, so its references are NPP's and the mandate's id. A terminal whose
payment went over NPP sends it.

| Key | Pattern | What a POS does with it |
|---|---|---|
| `EndToEndIdentification` | The payer's reference, passed on unchanged end to end, and `NOTPROVIDED` when the payer gave none (N2). By the reference text rule: `^[A-Za-z0-9._:/#-]{1,35}$`, with at most 12 digits in total | Prints it on a receipt, keeps it to refund against, and matches settlement by it |
| `TransactionIdentification` | The payer's bank's id for the payment, which every later NPP message about it carries, its 35th character marking a retry (N1). By the reference text rule: `^[A-Za-z0-9._:/#-]{1,35}$`, with at most 12 digits in total until NPP's layout for it is known | Keeps it to refund against, and matches settlement by it |
| `MandateIdentification` | On a PayTo payment, the mandate's id, which NPP's Mandate Management Service generates, not the creditor (N1). By the reference text rule: `^[A-Za-z0-9._:/#-]{1,35}$`, with at most 12 digits in total until its format is known | Prints it on a receipt, and matches settlement by it |

NPP has not published the layout of its Transaction ID or the format of a Mandate ID, so
both keys hold the reference text rule until it does. A value outside it is dropped alone,
and the outcome stands.

### What these values can still carry

The middleware forbids card, bank and personal data in every field of the outcome, but its patterns
cannot keep all of it out, and the middleware cannot detect a value like these where it fits. A key
of the reference text rule is one of the six keys that rule names, above.

| Value | Fits |
|---|---|
| A card number of 13 to 19 digits, plain, spaced, dashed, among letters or between marks, or joined to its expiry or to track data | No key of `Bank` or `NPP`, no `Wallet` key but `RecipientTransactionIdentification`, which a card number padded into a UUID's shape fits (below), and no `Card` key but `AcquirerMerchantIdentification`, which a card number of 13 to 15 digits fits |
| A card number of 13 to 15 digits | `Card.AcquirerMerchantIdentification` |
| A 12 digit card number, or the first 12 digits of a longer one | `Card.RetrievalReferenceNumber`, `Card.AcquirerMerchantIdentification`, and every key of the reference text rule |
| An expiry as `12/29` | `StatusReasonInformation.AdditionalInformation`, and every key of the reference text rule |
| An expiry as `1229`, a card verification value (CVV) | Every key of the reference text rule, `Card.RetrievalReferenceNumber`, `Card.AcquirerMerchantIdentification`, `StatusReasonInformation.AdditionalInformation`, and some of the others |
| A phone number written without `+`, such as `0412345678`, an 11 digit ABN, a BSB, an account number, or a BSB and an account number together, up to 12 digits in all (`062000-123456` fits, `062-000-12345678` does not) | Every key of the reference text rule. Written as digits alone, each also fits `Card.RetrievalReferenceNumber`, `Card.AcquirerMerchantIdentification`, and some of the others |
| A name with no space, such as `JSMITH`, or a URL such as `https://pay.example/u/jsmith` | Every key of the reference text rule. The name also fits `Wallet.ProviderIdentification`, `Card.RetrievalReferenceNumber`, `Card.AcquirerMerchantIdentification`, `StatusReasonInformation.AdditionalInformation`, and some of the others |
| An email address, a phone number written `+61…`, a name with a space | No reference key, since none holds `@`, `+` or a space. A name with a space, such as `J SMITH`, still fits `StatusReasonInformation.AdditionalInformation` |
| A card number padded into a UUID's shape | `Wallet.RecipientTransactionIdentification`, which holds a UUID. That takes intent |
| Digits written in a date's shape, such as `4111-11-11T11:11:11.11Z` | `TransactionDateTime` |

So a card number of 13 to 15 digits fits `AcquirerMerchantIdentification`, and a 12 digit
one fits `RetrievalReferenceNumber`, `AcquirerMerchantIdentification` and every key of the
reference text rule. The contract forbids each of these values in every field: a terminal
that put one in a reference would have it logged, sent to the POS and stored with the sale
until retention, undetected. A real retrieval reference is often 12 digits and a real
merchant id up to 15, so the middleware cannot narrow those patterns without refusing real values.

## A value that fails is dropped alone

A value that fails its pattern is dropped alone, and the outcome still applies. The middleware's
log names it in a `fields_dropped` line by its full path, as `TransactionDateTime` or
`PaymentReference.Card.RetrievalReferenceNumber`, and its value is written nowhere. The POS
gets the rest, and does not get that value.

- A key sent as `null`, an empty object, and an object emptied by drops read as absent.
- A `StatusReasonInformation`, a `PaymentReference` or a group that is not an object is
  dropped whole. A `ResponseCode` or `AdditionalInformation` that is not a string is
  dropped alone.
- A `Reason` sent with `ACSP` is dropped alone and named in `fields_dropped`: it decides
  nothing there, so it never refuses the outcome.
- `TransactionStatus` is different, because the outcome cannot stand without it: absent is
  `missing_field`, and anything else wrong is `invalid_result`. So is `Reason` with `RJCT`:
  absent, or in a `StatusReasonInformation` that is not an object, is `missing_field`, and
  anything but `AG07`, `AB11` or `DS02` is `invalid_result`.
- A key in another case, such as `RRN` or `responsecode`, is an unknown field, and dropped.
  So is a group or a key that References by kind does not list, such as a card key sent at
  `PaymentReference`'s top level, by its path, its value unread.
- The middleware does not trim, so a padded `AuthorisationCode` such as `"AB12  "` is dropped.
  Strip padding, and zero fill `SystemTraceAuditNumber`.
- If a key is repeated in a frame, the last value wins, and it is held to the same rules.
- Three things are never dropped alone, because the middleware cannot parse a frame that holds
  one, in any field: a `\u` escape of half a surrogate pair with no other half, such as
  `\ud83d` alone; a number beyond the range of an IEEE 754 double, such as `1e400`; and
  arrays and objects nested 128 deep, the frame's own object counting as one. A frame
  holding one is refused whole as `unparseable_frame`, and its outcome does not apply.
  Never send them: cut a string between whole characters, never inside a surrogate pair.

## Refusal

The middleware to the terminal: the middleware could not take a frame. A dropped field is not refused, so
it gets no frame: read the log, in Testing below.

```json
{ "MessageType": "Refusal", "ResponseReason": "invalid_result" }
```

| Field | Sent by | Rule |
|---|---|---|
| `MessageType` | `mw` | `Refusal` |
| `ResponseReason` | `mw` | One code from the table below. It never holds anything the frame held |
| `TransactionReference` | `mw` | Never sent in this version. The schema allows it for a later one, so ignore it |

A `Refusal` names no frame, so it is about the last frame the terminal sent on that
connection. The middleware reads a connection's frames in the order they were sent, queues a
refused frame's `Refusal` as soon as it has read and judged the frame, and sends what it
queued for a connection in that order. So send one frame at a time, and read any `Refusal`
for it before sending the next.

A `Refusal` the middleware cannot queue is lost, and the middleware's log holds a `delivery_failed` line
for it: on a connection a newer one has replaced (Reconnect, above), and on one where 8
frames already wait because the terminal is not reading them. A frame the middleware reads but
does not apply gets no `Refusal` and no `delivery_failed` line, though its `in` line is
logged: one read while 8 frames before it still wait to be applied, which closes the
connection, and one still waiting when the connection closes.

| `ResponseReason` | When | What to do |
|---|---|---|
| `unparseable_frame` | Valid UTF-8 that is not JSON, or JSON that is not an object, or a frame the middleware cannot parse: one holding half a surrogate pair as an escape, a number beyond the range of an IEEE 754 double, or nesting 128 deep (A value that fails is dropped alone, above) | A bug: alert someone |
| `binary_frame` | A binary frame | A bug: alert someone |
| `unknown_frame_type` | `MessageType` is absent or is not `Outcome`. A `LoginNeeded` is answered instead only on a connection that declared `SASQ` in `Mw-Message-Functions`, and on any other it gets this. A `LoginResponse` too is read instead only on a connection that declared `SASQ`, and on any other it gets this | A bug: alert someone |
| `missing_field` | `TransactionStatus` or `TransactionReference` is absent, or `StatusReasonInformation.Reason` is absent with `RJCT`. In a `LoginResponse`, `LoginReference` or `Response` is absent, or `ResponseReason` is absent with `FAIL` | A bug: alert someone |
| `invalid_result` | `TransactionStatus` is not `ACSP` or `RJCT`, or is not a string, or with `RJCT` `StatusReasonInformation.Reason` is not `AG07`, `AB11` or `DS02`. In a `LoginResponse`, `Response` is not `SUCC` or `FAIL`, or is not a string, or with `FAIL` `ResponseReason` is not one of `not_covered`, `not_accepted` and `no_answer`, or with `SUCC` a `ResponseReason` is sent | A bug: alert someone |
| `invalid_reference` | `TransactionReference` is not a string. In a `LoginResponse`, `LoginReference` is not `lgn_` then 32 lowercase hex characters | A bug: alert someone |
| `not_held` | A well-formed outcome naming no sale the middleware holds | Stop. Keep your own record. The sale passed retention, the log holds what you sent, and an operator reconciles it. An outcome already taken for a sale still held gets no `Refusal` |
| `other_terminal` | It names a sale held for another terminal | A bug: alert someone |
| `terminal_not_permitted` | A well-formed outcome on a connection that may no longer hold its terminal: the terminal is not `paired`, or the credential it connected with is retired. The middleware did not take it, and its log keeps what the terminal said. A `LoginNeeded`, or a well-formed `LoginResponse`, on such a connection gets it too, and nothing is counted or written | Keep the outcome, close the connection, reconnect, and send it again. After a `LoginNeeded` or a `LoginResponse`, close the connection and reconnect with the backoff all the same (Reconnect, above), and after an ask, ask again once a connection is accepted |
| `recipient_key_invalid` | A `LoginNeeded`'s `RecipientKey` cannot be used: it is absent or not an object, its `PublicKey` is not 65 bytes in base64url of a point on P-256, `0x04` first, or on a connection made with a certificate its `Signature` is absent, malformed or does not verify under the key of the certificate the connection presented. Nothing was counted (Signing in, above) | A bug: alert someone. Answer the sale `RJCT` with `AB11` |
| `sign_in_not_available` | The middleware holds no sign-in credential it can use for the terminal's store: none is attached, the credential is removed, the store or its owner is not in a state to act, or sign-in is off on this middleware. A terminal signed out is normal. Nothing was counted | Answer the sale `RJCT` with `AB11`, unless a person signs in at the terminal by its fleet's own means, and ask no more on this connection |
| `sign_in_limited` | The terminal was answered a sign-in less than `MW_SIGNIN_INTERVAL_SECS` ago, 60 seconds at the middleware's default settings, or has been answered `MW_SIGNIN_PER_DAY` times, 24 by default, in the day counted from that day's first answer. Nothing was counted | Answer the sale `RJCT` with `AB11`, and ask again no sooner than 60 seconds later |
| `sign_in_unavailable` | The middleware could not answer the ask: its store did not answer or did not read as it should, the key service did not open the credential's secret, or the answer could not be signed or sealed. Nothing was sent in clear. An ask whose secret could not be opened still counts toward the terminal's limit. On a well-formed `LoginResponse`, its store did not answer or did not read as it should, and nothing of the report was written | Answer the sale `RJCT` with `AB11`, and ask again no sooner than 60 seconds later. After a `LoginResponse`, go on as its `Response` says, without sending it again, and ask again no sooner than 60 seconds later |

A refused frame changes nothing, so the sale waits for a good one, and the terminal goes on
to its next payment. Apart from `not_held`, `terminal_not_permitted`, `sign_in_not_available`,
`sign_in_limited` and `sign_in_unavailable`, a `Refusal` means a bug in the terminal's code,
which a running app cannot fix, so do not resend that frame.
Keep an outcome it refused, so the outcome can be sent once the code is fixed. A refused
`LoginNeeded` is never kept or resent: its fresh key is dropped (Signing in). Nor is a refused
`LoginResponse`: the terminal goes on as Signing in, above, says. `terminal_not_permitted` is the
one exception to do not resend: it is no bug, so keep the outcome, close the connection,
reconnect, and send it again. A suspension that lifts then loses nothing.

An outcome that was taken gets no reply: there is no acknowledgement. Nor does a `LoginResponse`
that was taken. A frame or message over 65,536 bytes closes the connection instead of getting a
`Refusal`, and so does a frame that breaks the WebSocket protocol, such as invalid UTF-8 in a
text frame. Either way the frame is lost, so resend its outcome after the reconnect.

## The paths, step by step

**The normal path.**

1. Connect, and hold the connection.
2. An `Instruction` arrives. Store its `TransactionReference`, then show `TotalAmount` as
   the total, and the items if the terminal can.
3. Take the payment for `TotalAmount`, or with `TransactionType` `RFND` make the refund of it
   (A refund, above).
4. Build the `Outcome` with the instruction's `TransactionReference`, and the
   `TransactionStatus`, with its `Reason` on `RJCT`, that Which `TransactionStatus` to send,
   above, gives. Store it, then send it.
5. No `Refusal` arrives, and a later frame from the middleware does, such as its next Ping, or
   on a library that never shows one its next text frame (Hold, above): the outcome was taken,
   and the terminal is free for its next payment. Taken or not, it is
   still the most recent outcome, so after any reconnect take the resend path below.

**The resend path.** The connection drops or the middleware closes it, or the terminal restarts,
after the terminal sent an outcome, and before a new `Instruction`, a `Refusal` for it other
than `terminal_not_permitted`, or 23 hours after it was first sent.

1. Reconnect with the backoff.
2. Send the stored frame again, unchanged.
3. The middleware applies it if it had not arrived, and ignores it if it had. Either way no reply
   comes, and the sale reads the result that frame carries. The one exception is a sale
   the middleware no longer holds, past retention: that outcome gets `not_held`, below.
4. Do the same after every later reconnect, until one of those three ends.

If the same `TransactionReference` arrives again in an `Instruction`, do not charge again:
send the stored outcome.

**The unknown-result path.** The terminal does not know whether a payment was taken, for
example because the host did not answer.

1. Send nothing for that sale yet. The terminal is still busy: start no other payment.
2. Ask the host for the payment by the reference stored before the card, its
   `TransactionReference` (Instruction, above). An answer gives the outcome: approved is
   `ACSP`, and declined is `RJCT` with `AG07`. A host's "never received" is `RJCT` with `AB11`
   only where the host documents that answer as final. Otherwise go to step 3.
3. If the host cannot answer the enquiry, offers none, or gives a "not found" it does not
   document as final, reverse the payment. Send `RJCT` with `AB11` once the host has confirmed
   the reversal, and not before (Which `TransactionStatus` to send, above).
4. Keep trying steps 2 and 3 until one gives an answer, and send it as soon as it comes,
   however late: a late outcome replaces the `UNKN` the POS reads after the deadline. With the
   default settings, a host that answers lets the terminal report before the hold ends, 300
   seconds from the instruction (Deadline, above). A host that does not answer leaves the POS
   reading `UNKN` until it does, and the outcome is then resent for 23 hours, as any outcome is
   (Resending is safe, above). A terminal that was off sends it on its first connection after.
5. Never give up with nothing.

A refund is the same: a terminal that does not know whether a refund was made finds out by
these steps, and sends `RJCT` with `AB11` after a reversal only once the host has confirmed it.

**A `not_held` outcome.** The sale passed retention. Stop sending that outcome, keep it in
the terminal's own record, and leave reconciling it to an operator: the log holds what was
sent.

**A `terminal_not_permitted` outcome.** The terminal is not `paired`, or its credential is
retired, so the middleware kept what it said and did not take it. Keep the outcome, close the
connection, and reconnect with the backoff: a connect refused `403 not_permitted` backs off
to one hour, and any other refusal is read by the holder's table (What a holder of a dead
certificate does, above). Once a connection is accepted, send the outcome again, as the
resend path says.

**The sign-in path.** A terminal that declared `SASQ` holds no session at its fleet's payment
system when an `Instruction` arrives.

1. Wake: turn the screen on, and bring the payment screen to the front over the lock screen.
2. Make a fresh P-256 key pair in memory, sign its public key on a certificate's connection, and
   send one `LoginNeeded`. Read its answer before sending another frame.
3. On the `LoginRequest`, check its suite, open it and drop the private key. The terminal signs
   in at its fleet's payment system with the opened `SignedValue`, and keeps the session.
4. Send one `LoginResponse` naming the group's `LoginReference`: `SUCC`, or `FAIL` with the
   code that fits. On a `FAIL`, ask again as Signing in, above, says.
5. Take the payment, as the normal path does.
6. On a `Refusal` of the ask, a `LoginRequest` that does not open, or no answer in 20 seconds,
   answer the sale `RJCT` with `AB11`, and ask again as Signing in, above, says for each.

## Testing

In the middleware's sandbox, whose start page is `mw://start`, also served as
`/docs/api/sandbox.md`, with the sandbox's address in `$SANDBOX`:

1. Take a key with `POST /sandbox/v1/keys`, which needs no credential. Its `201` holds the
   key, shown once, your `TesterIdentification`, your world's `MerchantIdentification`, and
   its nine terminals. Your terminal's id is `<tester>-yours`, `paired` for your world's
   vendor, and the key is a `pos` key of that vendor's register, bound to the terminal.
2. Connect your terminal under that id to `$SANDBOX` with its scheme made WebSocket's, `ws://`
   for `http://` and `wss://` for `https://`, then `/v1/terminals/{POIIdentification}/connect`,
   presenting the key on the upgrade as `Authorization: Bearer sbx_...` (Connect, above).
3. Send it a sale as a POS would, naming that id, under the same key, with a new
   `IdempotencyKey` each time:

   ```sh
   curl -s -X POST "$SANDBOX/v1/sales" \
     -H 'Authorization: Bearer sbx_...' \
     -H 'Content-Type: application/json' \
     -d '{"MerchantIdentification":"sbx-3f9a1c2e7b10-M1","POIIdentification":"sbx-3f9a1c2e7b10-yours","SaleReferenceIdentification":"INV-1001","IdempotencyKey":"test-sale-0001","TransactionDetails":{"Currency":"AUD","TotalAmount":"12.50","SaleItem":[{"ProductDescription":"Flat white","ProductQuantity":2,"UnitPrice":"6.25","ProductAmount":"12.50"}]}}'
   ```

   with your key in place of `sbx_...`, and your `TesterIdentification` in place of
   `sbx-3f9a1c2e7b10`. The answer is `202`, holding the sale's `TransactionReference`. The
   terminal receives the instruction.
4. Read the sale as the POS does, under the same key, until it settles:

   ```sh
   curl -s -H 'Authorization: Bearer sbx_...' \
     "$SANDBOX/v1/sales/sal_01970f6e7c3a7d3e8a4f2b1c9d0e1f2a?wait_seconds=25"
   ```

   with the `TransactionReference` from step 3. A read under another register's key answers
   `404`, as if the middleware never held the sale.
5. Read the sale's log with the `read_log` tool of the sandbox's MCP server, given the
   `TransactionReference`. It answers every message of the sale both ways, with a
   `fields_dropped` line naming anything the middleware dropped from an outcome, so a terminal vendor
   can check it sends nothing extra. A sale to `<tester>-approve`, a simulated terminal, is a
   whole sale to compare against.
6. To test signing in, connect as in step 2 with `SASQ` in `Mw-Message-Functions`, then send a
   `LoginNeeded` with a fresh key and no `Signature`, since a sandbox key's connection has
   none (Signing in, above). Your world's store holds the sandbox's stand-in credential,
   `sandbox_signed_value`, `KeyIdentification` `sandbox-signin-1`, so the answer is a
   `LoginRequest`. Open it, and check the group's `Signature`: the HMAC-SHA256 of
   `Challenge`'s ASCII bytes, keyed with the bytes of the sandbox's published secret, in
   lowercase hex. `mw://world` and the start page give the secret, and the worked vector, in
   Signing in, above, checks your opening. Your world's store holds none of
   `AcceptorIdentification`, `UserName` and `ApplicationIdentification`, so the group holds its
   four keys and its `LoginReference` alone. Then report it in a `LoginResponse` naming that
   `LoginReference`, as Signing in, above, says: the sandbox takes it as any middleware does.

A conformance run tests sign-in only on a terminal that declared `SASQ` when the step opened, in
two steps: `sign_in`, with a credential attached, which starts the terminal asleep, its screen
off and its application not in front, holding no session; and `sign_in_none`, for which the run
ends the world's attachment and restores it after, so the ask is refused `sign_in_not_available`.
A terminal that did not declare `SASQ` is not tested on sign-in: each of those steps is not
applicable, and its report row says so. A terminal that needs the middleware to sign it in must
declare `SASQ` and run again. A run judges frames alone and sees no screen, so a green run does
not prove that a terminal wakes.

## Sources

The ISO 20022 texts quoted here and in `docs/api/fields.json` for the outcome's status, its
reason and the references of `Bank`, `Wallet` and `NPP` were read on 09-Nov-2026 from
mirrors of ISO's published files, because iso20022.org answered every request with HTTP 403.
What NPP does was read the same day from NPP Australia's and Australian Payments Plus's
published documents. The texts of `TransactionType`, its codes `CRDP` and `RFND`, and
`OriginalTransaction`, quoted in A refund, above, were read on 11-Nov-2026 from M3, and the text
of `AuthorisedAmount`, quoted in Outcome, above, on 16-Nov-2026. The texts of `SaleToPOIAbort`
and of `ExchangeIdentification`, quoted in Abort, above, were read on 16-Nov-2026 from M3, the
definition of `DS02` the same day from M1, and its name, OrderCancelled, on 17-Nov-2026 from M2.
The texts of `RetailerMessage1Code`'s `SASQ`, of `SessionManagementRequest9`'s `LoginRequest`
and of `KEKIdentifier7`'s `KeyIdentification`, quoted in Connect and Signing in, above, were read
on 16-Nov-2026 from M3. The texts of `LoginResponse`, of `Response11Code`'s `SUCC` and `FAIL`, and
of `AcceptorIdentification`, `UserName` and `ApplicationIdentification`, quoted in Signing in,
above, were read on 17-Nov-2026 from M3. RFC 9180, R1, gives the sealing of Signing in, above, and its worked vector's inputs.

| Id | Source | Version | What it gave |
|---|---|---|---|
| M1 | Beneficial Strategies `iso-20022-external-codesets`, `source/ExternalCodeSets.json`, ISO's file as downloaded | Commit `ffdad80`: External Code Sets release 2Q2026 v3, ISO Last-Modified 03-Sep-2026 | Each code's definition |
| M2 | The Internet Archive's copy of ISO's `ExternalCodeSets_XLSX.zip` | Release 1Q2026 v1, captured 18-Jun-2026. Every definition quoted is the same in 1Q2026 v1 and 2Q2026 v3 | Each code's name, which ISO's JSON lacks |
| M3 | Beneficial Strategies `Iso20022Library`, `snapshot-sync/2026-09-04/spec-snapshot.tsv` | Commit `e754326`, ISO's repository snapshot of 04-Sep-2026 | Each element's definition, the codes of `CardPaymentServiceType16Code`, and the definition of `SaleToPOIAbort` |
| M4 | Beneficial Strategies `iso-20022-text` | Commit `b91ac1a` | The same element definitions as M3 |
| M5 | ISO's XSDs `pacs.002.001.16.xsd` and `pain.002.001.15.xsd` | Generated 02-Mar-2026 | Where `TransactionStatus` and `StatusReasonInformation` sit |
| N1 | Regulations for New Payments Platform, `auspayplus.com.au/wp-content/uploads/2024/11/NPP-Regulations-v22.0.pdf` | Version 22.0, 20-Nov-2024 | A payment's answer and its timeout notice are each a `pacs.002`; the payer's bank assigns the Transaction ID, every later message carries it, and its 35th character marks a retry; the Mandate Management Service generates a mandate's id |
| N2 | NPP Payment Initiation Messages: Technical guidance for corporates, government and third parties, `auspayplus.com.au/wp-content/uploads/2026/03/NPP-payment-initiation-V4.0.pdf` | Version 4.0, 20-Nov-2025 | `NOTPROVIDED` as the end-to-end id when the payer gave none; a PayTo payment carries its mandate's id; a rejection's reason is a code |
| N3 | New Payments Platform API Framework, `auspayplus.com.au/wp-content/uploads/2025/05/NPP-API-Framework-v5.0-1.pdf` | Version 5.0, 07-May-2021 | Read, and quoted nowhere here |
| N4 | PayTo Service Overview, `auspayplus.com.au/wp-content/uploads/2025/07/PayTo-Service-Overview-Nov-2021-2.0.pdf` | Version 2.0 | Read, and quoted nowhere here |
| R1 | RFC 9180, Hybrid Public Key Encryption, `rfc-editor.org/rfc/rfc9180` | February 2022 | Base mode, the suite's ids, a P-256 key's serialised form and the check of `enc`, and § A.3.1's test vector |
