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

Shopify access-token lifecycle for background / non-embedded paths.

## Why this module exists

Shopify expiring offline access tokens have a 1-hour TTL. The embedded
flow refreshes them via `Shopifex.Plug.ManagedInstall` (id_token →
access_token exchange on every page load past a threshold). But
background paths — schedulers, webhook handlers — don't have an
id_token. They refresh independently using the stored `refresh_token`
(90-day TTL, one-time use).

This module is that refresh path. It is the background-equivalent of the
embedded re-exchange, and `Shopifex.API.graphql/3` calls into it both
proactively (before a request) and reactively (after a 401).

## Shopify's recommended strategy

> "Proactively refresh tokens a few minutes before they expire, and
> when you receive a 401 response."
> -- https://shopify.dev/changelog/offline-access-tokens-now-support-expiry-and-refresh

- **Proactive:** `ensure_fresh_token/1` checks `token_expires_at` and
  refreshes if it's within the safety window (5 minutes).
- **Reactive:** `Shopifex.API.graphql/3` catches 401 responses and calls
  `refresh/1` once before retrying.

## Concurrency

Refresh tokens are one-time use — using a refresh_token invalidates it
immediately and the response includes a fresh refresh_token to use next
time. If two callers refresh in parallel, the second one will get
`invalid_grant` from Shopify and clobber the new refresh_token.

To prevent that, `refresh/1` acquires a cross-node lease in the dedicated
`shopifex_token_refresh_leases` table. The Shopify request runs without a
transaction or lock on the consumer's shop row. After Shopify responds, a
short transaction locks and re-checks the shop before persisting, so a
concurrent managed-install exchange is never overwritten.

## Caveats

- **Legacy installs have `refresh_token = nil`** — they were installed
  with the non-expiring offline token flow. For these shops,
  `ensure_fresh_token/1` returns the shop unchanged, `refresh/1` returns
  `{:error, :no_refresh_token}`, and the non-expiring access token keeps
  working for API calls. A 401 on such a token is terminal:
  `Shopifex.API.graphql/3` returns
  `{:error, {:token_refresh_failed, :no_refresh_token}}`, and the shop needs
  a new token exchange or a reinstall. Such a shop is **not** upgraded automatically: opening the
  embedded app does not re-exchange it, because `Shopifex.Plug.ManagedInstall`
  treats a `nil` `token_expires_at` as fresh (its `token_stale?` guard returns
  false for a nil expiry). The exception is a stored `scope` that lacks a
  configured scope, which does trigger a re-exchange. To move a legacy shop
  onto expiring tokens, back-fill it with `migrate_to_expiring_token/1` (see
  that function's docs) or have the merchant reinstall the app.

- **If the refresh_token itself expires** (after 90 days of no refresh),
  Shopify returns 400 with `invalid_grant`. `refresh/1` returns
  `{:error, ...}`. The next embedded page load fixes it via fresh token
  exchange.

## Configuration

Uses the existing Shopifex configuration:

    config :shopifex,
      api_key: "your_api_key",
      secret: "your_api_secret"

Tests can inject Req options (e.g. a `Req.Test` plug) via:

    config :shopifex, :req_options, plug: {Req.Test, Shopifex.ReqStub}

Refresh coordination can be tuned when necessary:

    config :shopifex,
      token_refresh_lease_ttl_ms: 120_000,
      token_refresh_wait_timeout_ms: 15_000,
      token_refresh_poll_interval_ms: 100

## References

- About offline access tokens:
  https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens/offline-access-tokens
- Expiry & refresh changelog:
  https://shopify.dev/changelog/offline-access-tokens-now-support-expiry-and-refresh
- Expiring offline access tokens required for public apps (Shopify changelog):
  https://shopify.dev/changelog/expiring-offline-access-tokens-required-for-public-apps-april-1-2026

# `ensure_fresh_token`

```elixir
@spec ensure_fresh_token(struct()) :: struct()
```

Same as `fresh_token/1`, but always returns the shop rather than an error
tuple: on refresh failure it returns the (now-stale) input shop instead of
propagating the error.

This is the right default for background workers, where a transient
refresh error shouldn't crash the caller. `Shopifex.API.graphql/3` reacts
to a stale token via its 401 retry. Callers that need to distinguish
success from failure (or terminal from transient errors) should call
`fresh_token/1` directly.

# `fresh_token`

```elixir
@spec fresh_token(struct()) :: {:ok, struct()} | {:error, term()}
```

Returns `{:ok, shop}` with an access_token guaranteed fresh enough to make
at least one Shopify API call against, or `{:error, reason}` if a needed
refresh fails.

Strategy:
- Token expiry is unknown (`nil`) → `{:ok, shop}` as-is. The caller is
  responsible for invoking `refresh/1` reactively on 401. This covers
  legacy shops that pre-date the expiry columns.
- Token expires within the safety window → refresh and return
  `refresh/1`'s result.
- Otherwise → `{:ok, shop}` as-is.

`reason` is whatever `refresh/1` returns; see its docs for the terminal
vs. transient distinction (`terminal_refresh_error?/1`).

# `migrate_to_expiring_token`

```elixir
@spec migrate_to_expiring_token(struct()) :: {:ok, struct()} | {:error, term()}
```

Exchange a legacy **non-expiring** offline access token for an expiring one
plus a refresh token.

This is the in-place way for a shop installed before expiring offline tokens
existed to acquire a `refresh_token`. Until it runs (or the merchant
reinstalls the app), `refresh/1` returns `{:error, :no_refresh_token}` for
that shop. Re-opening the embedded app does **not** upgrade it:
`Shopifex.Plug.ManagedInstall` treats a `nil` `token_expires_at` as fresh (its
`token_stale?` guard returns false for a nil expiry) and re-exchanges only
when the stored `scope` lacks a configured scope.

> #### Irreversible {: .warning}
>
> Shopify destroys the non-expiring token in the same transaction that issues
> the expiring pair. The call must never be retried — if the response is lost,
> that shop has no usable token until a merchant reinstalls. The request pins
> `retry: false` even when the host app configured retries globally.

Expiring offline access tokens are required for public apps' GraphQL Admin API
requests as of 2027-01-01.

## Back-filling an install base

Idempotence lives in the *selection*, not the call — a shop that already has a
`token_expires_at` has been migrated:

    import Ecto.Query

    MyApp.Repo.all(from s in MyApp.Shop, where: is_nil(s.token_expires_at))
    |> Enum.each(fn shop ->
      case Shopifex.Auth.migrate_to_expiring_token(shop) do
        {:ok, _migrated} -> :ok
        {:error, reason} -> MyApp.report_migration_failure(shop, reason)
      end
    end)

Returns `{:ok, shop}`, or:

  * `{:error, :already_expiring}` — the shop already has a `token_expires_at`
  * `{:error, :no_access_token}` — nothing to exchange
  * `{:error, :shop_not_found}` — the row vanished between call and persist
  * `{:error, {:migrate_failed, status, body}}` — Shopify rejected the exchange
  * `{:error, {:migrate_request_failed, exception}}` — transport failure; the
    token may or may not have been cycled, so treat the shop as needing manual
    inspection rather than re-running this function
  * `{:error, {:persist_failed, changeset, attrs}}` — Shopify cycled the token
    but the database write failed. `attrs` carries the new token material so
    the caller can recover the shop; it is deliberately **not** logged.

# `refresh`

```elixir
@spec refresh(struct()) :: {:ok, struct()} | {:error, term()}
```

Force-refresh the shop's access_token by exchanging its stored
`refresh_token` for a new access + refresh token pair.

Uses a cross-node database lease so concurrent callers don't both invalidate
the same refresh token. The outbound Shopify request does not hold a lock on
the shop row; only the final compare-and-persist step uses a short row lock.

Returns `{:ok, refreshed_shop}` on success or `{:error, reason}` if Shopify
rejects the refresh (most commonly `invalid_grant` when the refresh_token
itself has expired) or the shop has no refresh_token.

A caller that cannot acquire or observe completion of the lease before the
configured wait deadline receives `{:error, :refresh_in_progress}`.

A shop whose stored `refresh_token_expires_at` has passed (or is within a
60s skew of passing) fails fast with `{:error, :refresh_token_expired}`
without contacting Shopify. Recovery is the same as for a rejected refresh:
the merchant opens the embedded app, and `Shopifex.Plug.ManagedInstall`
re-exchanges the `id_token` for a fresh token pair.

See `terminal_refresh_error?/1` for which `reason` values are worth
giving up on vs. worth retrying later.

# `terminal_refresh_error?`

```elixir
@spec terminal_refresh_error?(term()) :: boolean()
```

Classifies a `refresh/1` / `fresh_token/1` error reason as terminal
(retrying won't help without merchant action) or transient (worth retrying,
e.g. with the shop's current token).

Terminal: `:refresh_token_expired`, `:no_refresh_token`,
`{:refresh_failed, 400}`, `{:refresh_failed, 401}`, `:shop_not_found`.

Transient (returns `false`): `:refresh_in_progress`,
`{:refresh_failed, 5xx}`, transport errors, and anything else unrecognized.

`Shopifex.API.graphql/3` uses this to decide whether to send the request
with a stale token or fail immediately.

---

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