# `AttestoClient.Token`
[🔗](https://github.com/XukuLLC/attesto_client/blob/v2.26.0/lib/attesto_client/token.ex#L1)

Obtain, refresh, and revoke OAuth tokens.

Connections are retried up to three times, within the request deadline, only
before any HTTP request can have been sent. Each connect has a three-second
cap (overridden by `:req_options`' `:connect_options` `:timeout`). No transport
failure after the request starts triggers a retry.

`{:error, :not_sent}` means no state-changing request was written during the
call (excluding a refused authentication attempt that is retried), including a deadline ending
during connect. `{:error, :transport_error}` and `{:error, :timeout}` mean the
remote outcome may be unknown; do not blindly retry a token operation. Refresh-token rotation is available
through `refresh/4`, which uses `AttestoClient.RefreshCoordinator` to prevent
concurrent reuse for the same application record.

Returned tokens are not persisted by this library. Applications must perform
any compare-and-swap update and choose their own token/session retention
policy.

# `client_credentials`

```elixir
@spec client_credentials(keyword()) ::
  {:ok, AttestoClient.TokenSet.t()} | {:error, term()}
```

Obtain a token with the OAuth client-credentials grant.

Required options: `:token_endpoint`, `:client_id`, and `:client_auth`.
Authentication uses the same methods as `refresh/4`; `:none` is refused
with `:invalid_client_auth` because this grant requires an authenticated
confidential client. For private-key JWT, supply the trusted `:issuer`
(or an explicit assertion audience), as with the other token operations.

`:scopes` is a list of scope tokens (default `[]`); `:resource` is an
absolute resource URI or list of URIs. Invalid values return
`:invalid_scopes` or `:invalid_target`. `:dpop`, `:dpop_nonce`, `:alg`,
`:kid`, `:now`, `:outbound`, `:req_options`, and
`:timeout` have the same meanings as for the other token requests. A
`:profile` applies its client-authentication and DPoP requirements too.
Response bodies have the same fixed 2,000,000-byte limit as other grants.

Returns `{:ok, token_set}`, with unknown response members in
`AttestoClient.TokenSet`'s `:extra`. Any ID Token is returned unverified:
this grant establishes no end-user identity. A DPoP response without a key
returns `:missing_dpop_key`; a Bearer response with a key returns
`:invalid_token_type`. Access-token contents are never inspected.

Connect failures may retry before a request is written. A transport failure
after writing never retries; see the module's `:not_sent` contract.

# `exchange_pre_authorized_code`

```elixir
@spec exchange_pre_authorized_code(
  String.t(),
  keyword()
) :: {:ok, AttestoClient.TokenSet.t()} | {:error, term()}
```

Exchange an OID4VCI pre-authorized code for an access token
(`urn:ietf:params:oauth:grant-type:pre-authorized_code`,
`OpenID4VCI 1.0 Final` §6.1/§6.2) - the wallet-holder token step
ahead of `AttestoClient.Wallet.request_credential/3`.

Required option: `:token_endpoint`. Private-key JWT authentication also
requires `:issuer` from trusted discovery: it is the assertion's audience
(RFC 10070 §4), and without it the call returns
`{:error, {:client_assertion, :invalid_audience}}`. `:client_id` may
be omitted only with `client_auth: :none`, as permitted for anonymous
pre-authorized-code flows; authenticated methods still require it.
`:client_auth` and `:req_options` otherwise behave as for `refresh/4`.
`:alg`, `:kid`, and `:now` configure DPoP proofs when `:dpop` is supplied. Pass
`:tx_code` when the offer's grant carried a `tx_code` object, i.e. the end
user must key in the transaction code the issuer displayed out of band.

`:outbound` applies to the token request; see `AttestoClient.Outbound`. A
malformed value is `{:error, :invalid_outbound}`.

Returns `{:ok, token_set}`; the ID Token, if any, is returned unverified
since OID4VCI defines no binding claims for it here.

# `refresh`

```elixir
@spec refresh(GenServer.server(), term(), AttestoClient.TokenSet.t(), keyword()) ::
  {:ok, AttestoClient.RefreshResult.t()} | {:error, term()}
```

Refresh a token set through a single-flight coordinator.

Required options are `:token_endpoint`, `:issuer`, and `:client_id`.
With the default `protocol: :oidc`, the `:subject` from the previously
verified ID Token is required too; `protocol: :oauth` omits ID Token and
JWKS processing for a plain OAuth grant. `:client_auth` and
`:req_options` match
`AttestoClient.AuthorizationCode.callback/3`. The issuer is validated before
the request so an ID Token returned with a rotated refresh token can always
be verified rather than losing the rotation result after the response.

`:resource` names the protected resource(s) the new access token is for
(RFC 8707 §2.2): one absolute URI without a fragment, or a list of them.
Each is sent as a `resource` parameter on the refresh request. Omitted, the
locally retained `tokens.resources` are repeated. An explicit value must be
a subset of that grant when it is known. A malformed or out-of-grant value
returns `{:error, :invalid_resource}` before any request. A token set
persisted before resources were retained has `resources: nil`; omission
sends none, while an explicit valid value is accepted and checked by the
authorization server.

`:scopes` optionally narrows the new access token to a list of RFC 6749 scope
tokens. Omitted or empty, no `scope` parameter is sent and the authorization
server treats the request as the original grant's scope. An invalid list
returns `{:error, :invalid_scopes}` before any request. When the response
omits `scope`, the token set retains the explicitly requested value.

One refresh request serves every concurrent caller for a key, and that
request names one set of resources and scopes. A caller that joins a refresh
running with different request parameters gets
`{:error, :refresh_request_mismatch}` and no tokens: its own request was not
sent, and the shared access token has another audience or permission set.
Where the server rotates refresh tokens the stored token set has been
replaced by then, so read it again before refreshing.

`:client_auth` also accepts
`{:private_key_jwt, jwk, assertion_opts}` for an explicitly registered
assertion algorithm, key id, audience, lifetime, time, or JWT id.

`:issuer` is the issuer identifier, or `{AttestoClient.Issuer, name}` to
take the identifier and the ID Token verification keys from a running cache.

`:issuer_aliases`, `:clock_skew_seconds`, `:expiry_leeway_seconds`,
`:max_token_age_seconds`, `:require_auth_time`, `:require_typ`, `:require_kid`, and `:trusted_audiences` apply
to an ID Token returned with the refresh, as in
`AttestoClient.IDToken.verify/2`. A token set does not retain the aliases
given to `AttestoClient.AuthorizationCode.start/2`, so pass them again here.

`require_auth_time: true` treats non-positive integer `auth_time` as missing.
`require_typ: true` requires `JWT` or `application/jwt`, case-insensitively,
and defaults to `false`. `:now` accepts integer Unix seconds or a zero-arity
function returning them. It supplies every ID Token time check, read after
key resolution and signature verification, and each DPoP proof. Invalid
options fail before refresh with `:invalid_time` or `:invalid_require_typ`;
an invalid clock result returns `:invalid_time`. Network timeouts and
coordinator deadlines still use elapsed time.
Concurrent callers sharing a refresh result must still meet their own
verification options; a caller with different options re-verifies the ID
Token without repeating the refresh request.

`:outbound` names deliberate exceptions to the HTTPS and public-address
rules for the issuer, its key fetch and the token request
(`AttestoClient.Outbound`). A token set does not retain it either.

A prior DPoP token set requires `:dpop` signing material before any network
request. Persisted `tokens.dpop_jkt` must match that key; a missing or changed
key is rejected locally. A requested or prior DPoP token cannot accept a
Bearer response. Shared results are also checked against each caller's key
before adoption. Legacy token sets without a thumbprint require a key, but
their historical key continuity cannot be checked; a successful DPoP response
records the supplied key for subsequent refreshes.

`:alg`, `:kid`, and `:now` configure each DPoP proof and are retained across
the one permitted nonce retry.

The locally retained `tokens.id_token_alg` selects the ID Token verification
algorithm. An explicit `:id_token_alg` must match it; mismatches fail before
HTTP. The algorithm survives refreshes even when the response omits an ID
Token, and shared results must match each caller's policy. Legacy token sets
without this field use the explicit option or the existing default (PS256 for
FAPI, RS256 otherwise), then retain that selection for subsequent refreshes.

# `revoke`

```elixir
@spec revoke(
  String.t(),
  keyword()
) :: :ok | {:error, term()}
```

Revoke a token according to RFC 7009.

A successful 2xx response is `:ok`, including when the server did not know
the token. Required options: `:revocation_endpoint`, `:client_id`; optional
`:token_type_hint`, `:client_auth`, `:req_options`, `:timeout`, and
`:outbound` (see `AttestoClient.Outbound`).
With `private_key_jwt`, pass `:issuer` from trusted discovery; it is the
assertion's audience (RFC 10070 §4). An explicit `:audience` in the assertion
options takes its place. With neither, the call returns
`{:error, {:client_assertion, :invalid_audience}}`; the endpoint URL is never
used as the audience.

---

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