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

The AshVault Plaintext ("AVP") format: the bytes handed to `c:AshVault.Vault.encrypt!/2`.

    <<"AVP", 1::8, :erlang.term_to_binary(dumped)::binary>>

`dumped` is **always** `Ash.Type.dump_to_embedded/3` of the value, for every type —
scalars, arrays, arrays of embedded resources, embedded resources and unions alike.
Ash dispatches `{:array, t}` to its array implementation and recurses, so no
array-specific code is needed here. One code path, one on-disk shape.

Decoding is deliberately paranoid:

  * the `"AVP"` magic and version byte must match, or you get
    `AshVault.Errors.UnsupportedEnvelope` with `layer: :plaintext` in `vars` — the
    *plaintext* format version, which is distinct from the ciphertext envelope version
  * a compressed external term (`<<131, 80, ...>>`) is refused outright with
    `AshVault.Errors.InvalidCiphertext`. AshVault never writes one, and `:safe` does
    not stop a decompression bomb
  * decoding goes through Ash's `non_executable_binary_to_term` helper with `:safe`,
    which blocks atom interning and funs/refs/ports
  * the decoded term is then cast with `Ash.Type.cast_from_embedded/3`

## Storage encoding

The encrypted envelope is handed to the backing `:binary` attribute raw. Since ash
3.26 `Ash.Type.Binary` base64-encodes itself inside embedded resources, so AshVault
adds no conditional base64 of its own — which means **ash >= 3.26 is required for
encrypted attributes on embedded resources**.

# `deserialize`

```elixir
@spec deserialize(binary(), Ash.Type.t(), keyword(), module(), atom()) ::
  {:ok, term()} | {:error, Exception.t()}
```

Deserialize an AVP plaintext binary back into a value.

Returns `{:error, %AshVault.Errors.UnsupportedEnvelope{}}`,
`{:error, %AshVault.Errors.InvalidCiphertext{}}` or
`{:error, %AshVault.Errors.SerializationFailed{}}` rather than raising, so the decrypt
calculation can hand the error straight to Ash.

# `magic`

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

The plaintext format magic, `"AVP"`.

# `serialize!`

```elixir
@spec serialize!(term(), Ash.Type.t(), keyword(), module(), atom()) :: binary()
```

Serialize a value to the AVP plaintext format.

Raises `AshVault.Errors.SerializationFailed` when the type cannot dump the value.

# `version`

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

The plaintext format version, `1`.

---

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