# `Shopifex.Plug`
[🔗](https://github.com/ericdude4/shopifex/blob/main/lib/shopifex/plug.ex#L1)

An API for accessing the Shopify session data for the current request.

# `shop`

```elixir
@type shop() :: %{access_token: String.t(), scope: String.t(), url: String.t()}
```

# `shopify_host`

```elixir
@type shopify_host() :: String.t()
```

# `build_hmac`

```elixir
@spec build_hmac(conn :: Plug.Conn.t()) :: String.t()
```

Returns the HMAC the request should carry, computed with the app's current
secret. Used for verification and for (re)issuing signed values.

# `build_hmac`

```elixir
@spec build_hmac(conn :: Plug.Conn.t(), secret :: binary()) :: String.t()
```

Like `build_hmac/1`, but computes the HMAC with an explicit `secret`. Used by
`hmac_matches?/2` to accept either the current or a rotated `:old_secret`.

# `build_session`

```elixir
@spec build_session(
  conn :: Plug.Conn.t(),
  shop :: shop(),
  shopify_host :: shopify_host(),
  locale :: Gettext.locale()
) :: Plug.Conn.t()
```

Build the Shopifex session. Used in various `:shopify_*` pipelines.

Stores the current shop and Shopify host in `conn.private.shopifex`, where
`current_shop/1` and `current_shopify_host/1` read them, and applies the
request locale. No app-issued token is minted — embedded auth is carried by
Shopify's per-request `id_token` (see `Shopifex.SessionToken`).

# `current_shop`

```elixir
@spec current_shop(conn :: Plug.Conn.t()) :: shop()
```

Get current request shop resource for give `conn`.

Available in requests that passed through a `:shopify_session`,
`:managed_install`, or `:shopify_proxy` pipeline. (For `:shopify_proxy`,
`Shopifex.Plug.LoadProxyShop` resolves it from the signed `shop` param; it is
`nil` when that shop isn't found.)

## Examples:

    iex> current_shop(conn)
    %MyApp.Shop{}

# `current_shopify_host`

```elixir
@spec current_shopify_host(conn :: Plug.Conn.t()) :: shopify_host()
```

Get host parameter provided in URL params when Shopify loaded
your app in the Shopify admin portal.

Useful when initializing app-bridge instance from SPA application.

## Examples:

    iex> current_shopify_host(conn)
    "host from URL search parameter"

# `get_hmac`

```elixir
@spec get_hmac(conn :: Plug.Conn.t()) :: String.t() | nil
```

# `hmac_matches?`

```elixir
@spec hmac_matches?(conn :: Plug.Conn.t(), received :: term()) :: boolean()
```

Constant-time check that `received` matches the request's expected HMAC under
the app's current secret &mdash; or, when `config :shopifex, :old_secret` is
set, the previous one. Trying both lets you rotate the app secret without
dropping in-flight webhooks / signed requests still carrying the old signature.
Returns `false` for a non-binary `received` (e.g. a missing header), and
`false` without computing anything when a query value is not a string (a
bracket-syntax `foo[x]=y` parses to a map) — the only non-scalar Shopify
signs is the bulk-action `ids[]` list.

# `put_shop_in_session`

```elixir
@spec put_shop_in_session(conn :: Plug.Conn.t(), shop :: shop()) :: Plug.Conn.t()
```

Places given shop into current session, making it accessible later on
via `Shopifex.Plug.current_shop(conn)`

# `session_token`

```elixir
@spec session_token(conn :: Plug.Conn.t()) :: String.t() | nil
```

Returns the Shopify App Bridge session token (`id_token`) for the current
request, read from the `id_token` or `token` query param, or the
`Authorization: Bearer` header.

Embedded apps no longer mint their own session token — Shopify supplies a
fresh short-lived `id_token` on every embedded page load (App Bridge appends
it to the URL as `id_token`, and sends it as a `Bearer` token on authenticated
fetches). Verify it with `Shopifex.SessionToken`.

## Example
    iex> session_token(conn)
    "header.payload.signature"

# `sign_redirect`

```elixir
@spec sign_redirect(String.t(), String.t(), keyword()) :: String.t()
```

Signs an app-issued redirect for `shop_url` that `Shopifex.Plug.ShopifySession`
will accept **only** at `path` (the request path, without query) and only for
`:max_age` seconds. Used by `Shopifex.Plug.PaymentGuard` so a request
authenticated without an App Bridge `id_token` (legacy HMAC / non-embedded)
still reaches the plans page, and by `ShopifexWeb.PaymentHTML.select_plan_path/1`
so that page's Select request can authenticate its POST the same way.

The token is bound to one destination on purpose: it is not a Shopify-style
query HMAC, so it cannot be replayed on other routes, and a guarded route will
not mint a fresh one from it.

## Options

  * `:max_age` - seconds the token stays valid. Embedded in the token as an
    explicit `exp` claim (and as the `Plug.Crypto` signing max age), so the
    lifetime is fixed at signing time and `verify_redirect/2` needs no
    per-call override. Defaults to 90.

# `timestamp_fresh?`

```elixir
@spec timestamp_fresh?(conn :: Plug.Conn.t(), opts :: keyword()) :: boolean()
```

Returns true if the request timestamp is fresh according to `validate_timestamp/2`.

# `valid_webhook_hmac?`

```elixir
@spec valid_webhook_hmac?(conn :: Plug.Conn.t()) :: boolean()
```

Constant-time check that a Shopify **webhook** request is authentic: the
Base64 `x-shopify-hmac-sha256` header against the HMAC of the raw request
body (`conn.assigns[:raw_body]`). Tries the rotated `:old_secret` when set.

Unlike `hmac_matches?/2`, this reads the signature only from the header and
computes only over the body, so a query-string `hmac`/`signature` a caller
appended to the URL is never consulted. Returns `false` when the header is
absent, empty, or the raw body was not captured.

# `validate_timestamp`

```elixir
@spec validate_timestamp(conn :: Plug.Conn.t(), opts :: keyword()) ::
  :ok | {:error, String.t()}
```

Validates that the request timestamp in `conn.query_params["timestamp"]` is fresh.

Options:
  * `:require_timestamp` - boolean, default `false`. When `false`, returns `:ok` if no timestamp is present.
  * `:timestamp_tolerance_seconds` - integer tolerance window in seconds. Defaults to
    `Application.get_env(:shopifex, :hmac_timestamp_tolerance_seconds, 90)`.

Returns `:ok` or `{:error, reason}` where `reason` is `"missing timestamp"`,
`"malformed timestamp"` (not a string or integer, e.g. a bracket-syntax
`timestamp[x]=y` that parses to a map) or `"stale timestamp"`.

# `verify_redirect`

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

Verifies a token from `sign_redirect/3` against `path`, trying the rotated
`:old_secret` when set. The lifetime the signer embedded applies: the token
must be within its `Plug.Crypto` max age **and** its `exp` claim must still
be in the future. A token without an `exp` claim is rejected. Returns
`{:ok, shop_url}` or `:error`.

---

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