## Context

The API authenticates with Laravel Passport 9 (`league/oauth2-server` 8.3) on Laravel 6, using the password grant through a thin wrapper in `AuthController@login`. Tokens are JWTs; the `api` guard parses the JWT and then loads `oauth_access_tokens` to check the `revoked` flag, so revocation takes effect immediately.

Three facts about the current setup shape this design:

1. **No lifetimes are configured.** `AuthServiceProvider::boot()` never calls `Passport::tokensExpireIn()`, so both access and refresh tokens inherit Passport's one-year default.

2. **Rotation already happens.** `RefreshTokenGrant::respondToAccessTokenRequest()` revokes both the old access token and the old refresh token on every refresh, then issues a new pair. Rotation needs no work; it is already on.

3. **Rotation makes the refresh lifetime slide.** Each refresh issues a new refresh token with a new expiry computed from the moment of refresh, not inherited from the old token. So `refreshTokensExpireIn` is not "how long a session lasts" — it is "how long a session may stay silent".

A fourth fact is a live defect rather than a constraint: `Account::revokeTokens()` updates `oauth_access_tokens` only, while `RefreshTokenRepository::isRefreshTokenRevoked()` reads `oauth_refresh_tokens` independently. An account whose tokens were "revoked" can therefore refresh its way back to a valid access token.

## Goals / Non-Goals

**Goals:**
- Replace the unconfigured one-year lifetime with a deliberate, configured one.
- End sessions that have been unused for 3 days.
- Make logout actually revoke tokens, and make account-level revocation close the refresh path too.
- Return error codes that let a client distinguish "refresh" from "re-login".
- Achieve the above without schema changes.

**Non-Goals:**
- Absolute timeout, session/device listing, refresh-token reuse detection, login rate limiting, step-up authentication, token pruning. See the proposal's Out of Scope section for why each is excluded.
- Backward compatibility for existing clients. The front end ships in parallel.

## Decisions

### D1 — Idle timeout comes from the sliding refresh lifetime, not from stored state

Setting `Passport::refreshTokensExpireIn(3 days)` on top of the rotation that already happens produces an idle timeout for free:

```
10:00 day 1   login            → RT_1, expires day 4
11:00 day 1   refresh (RT_1)   → RT_2, expires day 4, 11:00
09:00 day 3   refresh (RT_2)   → RT_3, expires day 6
      day 3-6   no activity
      day 6     RT_3 has expired → re-login required
```

The alternative was a stored `last_used_at`, updated by middleware on every authenticated request, which is what an absolute timeout would have required anyway. It was rejected because it buys nothing here: both approaches end a silent session after 3 days, but one needs a schema change, a middleware and a write on every request.

The trade-off is recorded in Risks: this makes the idle timeout a contract with the client rather than a control the server enforces.

### D2 — No absolute timeout, and therefore no session record

A session that is used daily will never end. This is accepted deliberately. It matches how the system is actually used — employees order lunch through it every working day — and it matches the behaviour of the tools people already expect to stay signed in to.

Consequently there is nothing in this change that must survive refresh-token rotation, which is what removes the need for an `auth_sessions` table, for a Passport repository override to carry a session id across refresh, and for a session middleware. Should an absolute timeout be wanted later, all three come back together as one change.

### D3 — Logout finds the refresh token by walking back from the access token

`oauth_refresh_tokens.access_token_id` points at the access token the refresh token was issued with. The logout endpoint therefore reads the authenticated token's id, revokes it, and revokes the refresh-token rows pointing at it. The refresh token presented by the client never has to be read, so there is no need to decrypt it.

Logout is idempotent: revoking already-revoked rows is a no-op, so repeated calls succeed.

### D4 — Revocation is expressed as "access tokens and their refresh tokens", everywhere

`Account::revokeTokens()` and `Account::revokeTokensByAccountIds()` both gain the second step: after marking access tokens revoked, mark the refresh tokens pointing at them revoked too. Both keep their existing signatures and their existing scope and exception filtering, so the call sites that already pass `$exceptIds` or a scope keep working unchanged.

Doing this inside the two existing methods, rather than at each of the roughly eight call sites, is what makes the fix complete — a future call site inherits the correct behaviour.

### D5 — Error codes are classified from the JWT, not from stored state

A client needs to know whether a 401 is worth a refresh attempt. With no session record, the classification is made from the token itself in `app/Http/Middleware/Authenticate.php`, which runs when `auth:api` has already declined:

- bearer token parses as a JWT whose `exp` has passed → `token_expired`, worth refreshing
- any other failure (revoked, malformed, missing) → `token_invalid`, go to the login screen

The JWT is decoded here only to pick an error code. It is never trusted for authentication — that decision has already been made and refused by the guard.

The token cannot be read from the request at that point: Passport's `TokenGuard` blanks the `Authorization` header whenever OAuth validation fails, which is precisely when `unauthenticated()` runs. The middleware therefore captures the bearer token in its own `handle()` before delegating to the guard.

On the login endpoint, a `grant_type=refresh_token` request that league rejects is reported as `session_expired` rather than the current blanket `invalid_credentials`, because the two mean opposite things to a client: one says the user typed the wrong password, the other says the session is over.

### D6 — Lifetimes are configured per scope, but Passport enforces a single global value

Values are read per token scope (`admin`, `employee`) and both are set to 30 minutes and 3 days. `AuthServiceProvider` takes the minimum across all configured scopes and gives that single value to `Passport::tokensExpireIn()` / `refreshTokensExpireIn()`, because Passport has no per-scope lifetime of its own — one JWT signing config serves every token it issues.

This means tightening one scope's lifetime in config does not, by itself, give that scope a shorter lifetime than the others: with the minimum-across-scopes rule, lowering `admin`'s value lowers every token's lifetime, employee included. Today this is invisible because both scopes hold the same numbers. Per-scope enforcement — checking the token's own scope against its matching config value before honouring it — is not implemented and would need the access-token-lifetime decision to move out of Passport's global setting and into application code, similar in shape to the per-scope session work this change deliberately left out (see proposal's Out of Scope).

The config is kept structured per scope anyway, documented as a floor to apply uniformly for now, so that the day a real per-scope lifetime is implemented, the values it should enforce are already named and in one place.

## Risks / Trade-offs

- **The idle timeout depends on the client refreshing only when the user is active.** A front end that refreshes on a background timer, or any script holding the tokens, keeps a session alive indefinitely. → Treated as an explicit contract with the front end, which is maintained by the same team and shipping alongside. Server-side enforcement is available later, as part of an absolute-timeout change, if the contract proves insufficient.
- **A daily user is never signed out.** → Accepted; see D2. The compensating controls are the 30-minute access token and immediate revocation.
- **Everyone is logged out at deploy.** → Expected; communicate the timing. One re-login, once.
- **30-minute access tokens multiply refresh traffic**, roughly one extra token request per user per half hour of use. → Negligible at this user count, but the login endpoint is now on the hot path for every active user; watch its latency after deploy.
- **Error codes are classified from an untrusted token (D5).** A caller can craft a JWT with a past `exp` and be told `token_expired`. → Harmless: the code changes nothing about whether the request is authorized, and leaks nothing the caller did not already supply.
- **Nothing detects a stolen refresh token.** Rotation invalidates the copy that is used second, so the two holders fight over the session, but no one is told. → Out of scope by decision; the 3-day window bounds the damage, and account-level revocation can end it.

## Migration Plan

1. Deploy the code: lifetimes, logout endpoint, revocation fix, error codes.
2. Revoke all existing access tokens, then all existing refresh tokens. Every user logs in once more.
3. The front-end release must land in the same window — before step 2, clients cannot refresh; after it, old clients cannot authenticate at all.

Rollback is a plain code revert. There is no schema change to undo, and tokens issued under the new policy keep working until they expire.
