# `AshVault.Envelope.V1`
[🔗](https://github.com/jakeschurch/ash_vault/blob/main/lib/ash_vault/envelope/v1.ex#L1)

Version 1 of the AshVault envelope wire format.

This layout is frozen. Stored ciphertext must remain decodable forever, so the bytes
below are a compatibility guarantee, not an implementation detail:

    <<"AV",                              # 2-byte magic
      1          :: 8,                   # envelope version
      cid_len    :: 8,                   # cipher id length
      cipher_id  :: binary-size(cid_len),
      key_ver    :: 32-unsigned-big,
      nonce_len  :: 8,
      nonce      :: binary-size(nonce_len),
      tag_len    :: 8,
      tag        :: binary-size(tag_len),
      ciphertext :: binary>>

The ciphertext is the remainder of the binary, so truncation *within* the ciphertext
cannot be detected structurally — the AEAD tag catches it at decryption time instead.
Truncation anywhere in the header is detected and reported as
`AshVault.Errors.InvalidCiphertext`.

# `decode`

```elixir
@spec decode(binary()) :: {:ok, AshVault.Envelope.decoded()} | {:error, Exception.t()}
```

Parse a v1 envelope.

Total: never raises, and returns `{:error, %AshVault.Errors.InvalidCiphertext{}}` for
any binary that is not a structurally valid v1 envelope.

# `encode`

```elixir
@spec encode(map()) :: binary()
```

Encode an envelope map to its wire representation.

The `:cipher` key may be given as an atom or a binary; it is always stored as a binary.

Every field that does not fit the wire format raises `ArgumentError` naming the field
and the limit. The header encodes the cipher id, nonce and tag lengths in one byte
each and the key version in 32 bits, so the ceilings are 255 bytes and 4294967295
respectively. These used to be guard clauses, which meant an over-long nonce, an
over-long tag or a key version past 2^32-1 raised an opaque `FunctionClauseError`
while an over-long cipher id got a clean message — the same class of mistake
reported two different ways.

# `version`

```elixir
@spec version() :: pos_integer()
```

The version byte written by this implementation, `1`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
