# Device claim v1

Factory-fresh devices exchange a short-lived claim code over certificate-validating
HTTPS at `POST /v1/device-claims/exchange`. The request and response are defined by
`device-claim-request.schema.json` and `device-claim-response.schema.json`.

The device generates an ECDSA P-256 key pair, 16-byte random nonce, UUID
`attemptId`, and at least 32 random bytes of URL-safe MQTT credential material.
It persists this pending attempt in encrypted storage **before** the first HTTP
request and reuses it byte-for-byte after a lost response or reset.
`proof.value` is Base64 ASN.1 DER ECDSA/SHA-256 over these exact UTF-8 bytes:

```text
NIVALO-DEVICE-CLAIM-V1\n{attemptId}\n{claimCode}\n{hardwareId}\n{nonce}\n{credentialSha256}\n
```

`credentialSha256` is lowercase SHA-256 of the UTF-8 `mqttCredential`. All fields
are canonical schema values and the final LF is required. On success, the device
promotes the pending private proof key and locally generated MQTT credential with
the returned non-secret identity. This binds
the claimed identity to the key that authorized the request without requiring a
factory-wide reusable secret on generic ESP32 hardware.

## Abuse and replay rules

- Codes contain eight characters from the restricted uppercase alphabet
  `A-Z2-9` (excluding ambiguous `0/1`), expire within ten minutes, are scoped to one organization,
  and are consumed atomically on the first successful exchange.
- A failed request does not consume a code, but attempts are rate-limited by code,
  source IP, and hardware ID. Five failed attempts lock the code.
- The server rejects an expired, locked, already-consumed, differently scoped, or
  concurrently consumed code with the same generic error. It never reveals which
  predicate failed.
- The server atomically keys processing by `(attemptId, hardwareId, publicKey,
  credentialSha256)`. The first valid request consumes the code and hashes the
  supplied MQTT credential for authentication storage. Until the original
  code expiry, an exact retry returns the same non-secret response even if the
  code is now consumed. Expiry closes this bounded idempotency window. A retry that
  changes hardware, public key, nonce, or credential digest is rejected as a
  mismatched replay. Concurrent exact retries converge on one device identity.
- A hardware ID already bound to a different organization requires an
  explicit audited transfer flow; claim exchange cannot move it. Within one
  organization, claim exchange also rejects bound hardware until the owner
  deletes or retires its device (Cloud MQTT v1.1 section 15).
- Claim codes and MQTT credentials are never logged or returned in error bodies.
  The success response contains no MQTT password, claim code, refresh token, or
  reusable claim secret. The server stores only the existing one-way MQTT
  credential verifier; it has no recoverable device secret.
- TLS certificate and hostname validation is mandatory. Redirects to a different
  origin are rejected. Responses are accepted only when their JSON validates,
  `useTls` is exactly `true`, and `port` is either the production TLS port 8883
  or the isolated-staging TLS port 8884.

## Receiver limits

Both sides enforce the schema bounds; every `maxLength` also bounds UTF-8 bytes.

- Request: `attemptId` is a canonical lowercase, nonzero UUID; `hardwareId` is 8–128 and
  `hardwareType` 1–64 bytes, neither with leading or trailing whitespace; `proof.value` is padded
  standard Base64 of 20–256 characters and must verify as a P-256 proof.
- Response: `deviceId` is a canonical lowercase, nonzero UUID; `host` is an ASCII DNS name of at
  most 253 characters in dot-separated labels of 1–63 letters, digits or hyphens, with no hyphen at
  either end of a label, no empty label and no trailing dot. The server applies the same check to its
  configured MQTT host before it issues a response, so a credential is never promoted with an
  unusable host. `clientId` and `username` are the exact issued values (printable ASCII, no
  space, at most 128 bytes); `caCertificatePem` is null or at most 2048 bytes; the whole response
  body is at most 3072 bytes. The device reads the body with that bound and uses `clientId` and
  `username` exactly as returned (see Cloud MQTT v1.1 section 2).
- The claim carries no setup code and no new fields for v1.1. The per-unit setup code protects only
  the local setup access point.

If a response is lost, the device retains the encrypted pending attempt and
retries it exactly within the code's expiry window. A reset between attempts loads the same attempt before
connecting. Only a validated response promotes the final A/B configuration;
the pending record is then removed from encrypted NVS. Expired/locked codes can
be replaced only through the local setup flow, which overwrites the pending
attempt with a newly authorized code and fresh attempt.

The future backend/console implementation must create/display claim codes, enforce
the atomic/rate-limit rules, verify the canonical proof, bind the public key and
hardware identity, provision a device-scoped MQTT credential, and return the
contract response. This protocol document does not define database/API internals.
