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

Behaviour for envelope formats, and the dispatcher used to decode stored values.

An envelope is the self-describing wrapper written to the database. It carries
everything needed to decrypt a value except the key itself: the format version, the
cipher id, the key version, the nonce, the authentication tag and the ciphertext.

`AshVault.Envelope` is both the behaviour and the dispatcher. `decode/1` peeks at the
version byte and routes to the matching implementation, so values written by older
builds keep decoding after the default envelope version changes.

See `AshVault.Envelope.V1` for the current wire format.

# `decoded`

```elixir
@type decoded() :: %{
  version: pos_integer(),
  cipher: binary(),
  key_version: non_neg_integer(),
  nonce: binary(),
  tag: binary(),
  ciphertext: binary()
}
```

# `decode`

```elixir
@callback decode(binary()) :: {:ok, map()} | {:error, Exception.t()}
```

Parse a binary into a decoded envelope map. Must never raise.

# `encode`

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

Serialize a decoded envelope map to its wire representation.

# `version`

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

The version byte this implementation writes.

# `decode`

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

Decode a stored value by dispatching on its envelope version byte.

This function is total: any binary (or indeed any term) produces a tagged tuple, never
an exception.

Returns `{:error, %AshVault.Errors.UnsupportedEnvelope{}}` for a well-formed magic with
an unknown version, and `{:error, %AshVault.Errors.InvalidCiphertext{}}` for anything
that is not an AshVault envelope at all.

# `magic`

```elixir
@spec magic() :: binary()
```

The magic prefix every AshVault envelope starts with.

# `module_for_version`

```elixir
@spec module_for_version(integer()) :: {:ok, module()} | :error
```

The envelope implementation for a version byte, if this build knows it.

---

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