# Logging in

`btdl` keeps one saved login (a token file) at a time. You can point
at a different file with `--token` (or `BTDL_TOKEN`), so several
accounts can coexist side by side:

```console
$ btdl --token ~/.config/btdl/hi-res auth token
```

The two ways to create a login:

## Device login (recommended)

No token hunting in a browser devtools console: Tidal’s own
device-activation flow, run from the terminal.

```console
$ btdl auth device-login
device login
  open:  https://link.tidal.com/activate
  enter: ABCD-EFGH
  waiting up to 120 s for approval (the code expires in 600 s)
logged in as user 1234567
```

1. open the URL on any device,
2. enter the code, approve with the account you want,
3. the terminal picks it up when Tidal confirms — the login is saved
   and the command exits `0`.

Options:

| Option      | Default   | Meaning                                                            |
|-------------|-----------|--------------------------------------------------------------------|
| `--timeout` | `120.0`   | how long to keep polling, seconds                                  |
| `--user-id` | none      | pin the login to a specific account (multi-account Tidal profiles) |

The instructions go to **stderr**; with `--json` the stdout payload
is the safe record summary (see below).

If the code is not approved within `--timeout`, the command ends
with a typed error — `btdl: error: device login timed out before approval; start the device login again` (exit `1`, plus the usual
login hint) — and the saved session is left untouched.

The poll loop tolerates server-side blips: a degraded answer from
the token endpoint (a 5xx or 429 envelope) is counted as an
endpoint failure, not a login denial — three consecutive failures
fail the command with `btdl: error: auth endpoint unreachable during device login (3 consecutive poll failures)` (exit `1`),
and a healthy answer resets the counter. A genuine server-side
rejection (any non-200 answer that is not a pending/slow-down)
fails at once with the server’s message (exit `1`, plus the usual
login hint) and saves nothing.

## Token login

If you already have an access token (a `TIDAL_ACCESS_TOKEN` from a
previous tool, or the Tidal web session token):

```console
$ btdl auth login
access token:                      # hidden — not echoed to the terminal
logged in as user 1234567
```

or pass it straight (scripts, CI):

```console
$ btdl auth login "$TIDAL_ACCESS_TOKEN"
```

| Option                                | Meaning                                                      |
|---------------------------------------|--------------------------------------------------------------|
| `ACCESS_TOKEN` (positional, optional) | the token to save; **prompted if omitted**                   |
| `--user-id`                           | pin the login to a specific account (multi-account profiles) |

The token is verified against Tidal before it is saved; a rejected
token never lands on disk. (A purely numeric paste — a user id by
mistake — is refused even before that verification: Tidal tokens
are not numbers.) A `Bearer ` prefix is tolerated and stripped —
a paste copied straight out of a request header works as-is. A
pasted JWT keeps its `exp` claim’s lifetime (`auth token` counts
it down; `token_type` is `web`); a non-JWT paste has no knowable
lifetime (`seconds_left` is `null` — not expired).
The verification probes the PASTED token
itself, so a dead paste (say, from a retired OAuth client) can only
fail the paste — a working saved login is never replaced, rotated,
or cleared by it.

## Checking and leaving

```console
$ btdl auth            # bare: the session state (a network call)
logged_in: True
user_id: 1234567
client: Tidekeeper OAuth
...

$ btdl auth token      # offline: what the saved record says alone
$ btdl auth status     # online: record + refreshed subscription
$ btdl auth subscription   # plan, status, quality ceiling
$ btdl auth refresh    # rotate the token now (a pasted or dead login says "not refreshed")
$ btdl auth logout     # remove the saved login (and revoke it remotely)
$ btdl auth clear      # remove the saved login locally only (no revocation)
```

The revocation is best-effort: a failed revocation still clears the
local login — the JSON payload is the honest `false`, and the
human line says `logged out (remote revocation failed)` rather
than pretending there was nothing to log out.

`btdl auth status` also shows the subscription’s quality ceiling,
which is what decides the top of the
[quality chain](https://git.binarycollective.de/binary/binary-tidal-py).

A dead login is reported, not raised: when the last refresh failed,
the status carries a `last_auth_failure` line (the JSON’s
`last_auth_failure`) naming the reason — a rejected rotation, a
deferral while the auth endpoint is degraded (a 429/5xx refresh
answer), or a pasted login with no refresh token — and the
subscription lookup degrades to nulls; the command still exits `0`.

So does a missing login: with no saved record at all, `auth status`
and `auth token` report the absence as facts (exit `0`,
`logged_in: false`, every fact null — the client’s registered
persona name is the one that is not, and no request is spent),
where the catalog verbs make the same absence a typed failure
(`no valid Tidal login available`).

## What you never see

Login-style commands emit a **safe summary** of the saved record —
`user_id`, `client_id`, `country_code` — never the token values.
`auth clients` shows the public OAuth client registry the same way:
ids, platforms, quality tiers; no `client_secret` ever reaches the
output.

## When something goes wrong

An auth problem is reported with a hint pointing at both login
paths:

```console
$ btdl search "x"
btdl: error: no valid Tidal login available: call TidalClient.device_login() or TidalClient.login(token) first
btdl: hint: log in with 'btdl auth login' (paste a token) or 'btdl auth device-login' (URL + code)
```

| Symptom                                 | Meaning                              | Fix                                                                                          |
|-----------------------------------------|--------------------------------------|----------------------------------------------------------------------------------------------|
| `no valid Tidal login available`        | no usable token at the resolved path | `btdl auth device-login` (or `login`)                                                        |
| `token rejected by Tidal ... 401`       | the token is invalid or revoked      | get a fresh token / re-run device login                                                      |
| `subscription expired` in `auth status` | the account lapsed                   | renew the account; the login stays valid                                                     |
| rate-limit messages                     | Tidal is throttling the client id    | the library waits and backs off automatically; `btdl auth rate-limit` shows the current pace |
