# Device-Code Sign-In

How a device that cannot type in (an Apple TV) signs in by showing a code that a signed-in phone approves, and what the starter ships for both ends.

- [Introduction](#introduction)
- [Enabling It](#enabling-it)
- [The TV Screen](#the-tv-screen)
- [The Approval Screen](#the-approval-screen)
- [Proximity and Typed Codes](#proximity)
- [Step-Up on Approve](#step-up)
- [Routes and View Keys](#routes-and-view-keys)
- [Overriding a Screen](#overriding-a-screen)
- [The Backend](#the-backend)
- [Gotchas](#gotchas)
- [Related Documentation](#related-documentation)

## Introduction

Registered with `magic_starter.features.device_code` (default `false`). The device that cannot type asks `magic-starter-laravel` for a code, shows it with a QR code and a web address, and polls until someone approves it from an app where they are already signed in. No password is typed on the TV, and the flow only mints a session: it never carries a video or any other content.

Two controllers and two views make up the feature. `MagicStarterDeviceCodeController` and `MagicStarterDeviceCodeView` run on the device that wants the session. `MagicStarterDeviceApproveController` and `MagicStarterDeviceApproveView` run on the signed-in phone or desktop.

## Enabling It

```dart
'features': {
  'device_code': true,
},
```

Set it in `lib/config/magic_starter.dart`. Read it through `MagicStarterConfig.hasDeviceCodeFeatures()`, never an inline `Config.get`. The toggle is read when the manager is first resolved, so a `Config.set` after boot registers no view key. `MagicStarterConfig.deviceCodeRoute()` builds the TV screen's path from `routes.auth_prefix` (`/auth/device` by default), for a "Sign in with your phone" button on the login screen. `MagicStarterConfig.deviceApproveRoute()` builds the approval screen's path the same way (`/auth/device/approve` by default), for a deep link or a "Approve a TV" entry in the signed-in app.

An app installed before this release has its own `assets/lang/en.json` without the new copy, and with the toggle on both screens would show raw key names. Before you turn `device_code` on, merge the `magic_starter.device_code.*` and `magic_starter.device_approve.*` keys and the two titles `magic_starter.titles.device_code` and `magic_starter.titles.device_approve` by hand from `assets/stubs/install/en.stub`: `starter:publish --tag=lang` skips an `en.json` that already exists unless you pass `--force`, which overwrites your own strings. Do the same in every other language file the app ships.

The screen draws the QR code with `pretty_qr_code`, a direct dependency of the starter; a host adds nothing.

## The TV Screen

`MagicStarterDeviceCodeView` opens with `MagicStarterDeviceCodeController.start()`, once:

1. `POST auth/device/code` sends `device_name` (`tvOS`, `web`, or the platform name) and receives `device_code`, `user_code`, `verification_uri`, `verification_uri_complete`, `expires_in` and `interval`. The `device_code` stays in the controller and is never drawn.
2. The page shows the `XXXX-XXXX` code in large type, the verification address, a QR code of `verification_uri_complete` on a white ground (a QR inverted by a dark theme cannot be read by a camera) and a countdown. The QR sits beside the code when the card is at least 400 wide and above it otherwise, measured on the card rather than read off a breakpoint. On a window under 800 high (a television is 720) the QR, the code and the gaps are drawn smaller so every element and both actions fit; the guest layout's scroll covers a host whose header leaves even less. Only the countdown repaints each second: the controller's ticks go through `remaining`, not through the controller's listeners.
3. `POST auth/device/token` asks whether the code was approved, first `interval` seconds after the issue and then never sooner than `interval` seconds after the previous answer (the backend answers `slow_down` to a poll that arrives earlier). The backend's refusals are HTTP 400 answers with an `error` field:

| Answer | What the controller does |
|:-------|:-------------------------|
| `authorization_pending` | Keeps waiting. |
| `slow_down` | Adds five seconds to the interval, for good. |
| `access_denied` | Stops. The screen says the sign-in was declined. |
| `expired_token` | Stops. The screen says the code has expired. |
| A session (`data.token`, `data.user`) | Concludes through `completeSignIn`, like every other sign-in. A success whose body does not read as a session ends in the failure message with **Get a new code**. |

A failed poll (a dropped connection, a 5xx) is not an answer: the loop keeps its rhythm and the countdown bounds it. Reaching zero on the countdown expires the code without another request.

A declined, expired or never-issued code turns the page into that message with **Get a new code**, which calls `start()` again. Nothing is issued again unless the viewer presses it. **Sign in with email** stays in reach in every state, and so does **Continue as guest** when `guest_auth` is on. Leaving the page calls `cancel()`, which stops the countdown and the poll, and an answer that arrives after that is dropped.

The `device_code`, the `user_code` and the token never reach a log line.

## The Approval Screen

`MagicStarterDeviceApproveView` opens at `MagicStarterConfig.deviceApproveRoute()` with an optional `?code=` and calls `MagicStarterDeviceApproveController.open(code:)`:

- **With no code** it shows a field for the code on the TV.
- **With a code** it looks it up (`GET auth/device/{code}`) and shows two groups. Under one "Reported by the device, not checked" marker: the client that asked (parsed from the code request's user agent, named as the sessions screen names a device) and the name the device gave itself; both come from the device and either can be made up. Then the server's own facts: the country the code was requested from, the country the approval comes from, and how many minutes ago the code was issued.

Opening the page only ever looks the code up: it never approves. Approve and Deny share one intent and one size, under the sentence "Approve only if this code is on your TV". Approve sends `POST auth/device/{code}/approve`, Deny sends `POST auth/device/{code}/deny`, and either one ends the screen with a message and a Close button that goes home.

Approve acts only on the code whose facts are on screen. A typed code other than that one hides the facts and turns Approve into **Continue**, which looks the new code up and shows its facts first. A request that gets no answer (offline, a timeout) leaves the screen where it was with the failure sentence, so the person can press the same button again. A `429` from the backend's throttle does the same with its own sentence, "Too many attempts. Wait a minute and try again." (`magic_starter.device_approve.throttled`), for the lookup, Approve and Deny alike. Every visit to another location of the route (a new `code`, or none after a finished approval) drops what the last one left and opens again, and a code it carries is only looked up, as above; an answer that arrives after the screen was left or a newer lookup began is dropped.

The code is normalised before it goes anywhere: upper case, then every character outside the alphabet `BCDFGHJKLMNPQRSTVWXZ` dropped, so `bcdf-ghjk` and `BCDFGHJK` are the same code. A code that is not eight characters long costs no request. The backend answers `404 invalid_code` identically for a wrong, expired or already decided code, and the screen sends the person back to the field with one sentence.

## Proximity and Typed Codes

The QR code and its link can be forwarded by anyone, so a code that arrives through a link is not enough to approve from somewhere else. Every code that arrives in the route's `code` is a link code, whatever the URL's `entry` says: a forwarded URL can drop `entry=link` or claim `entry=typed`, so the screen does not read it. Only a code the person typed into the field during this visit counts as typed.

1. The lookup answers `same_network`: whether the approval comes from the network that requested the code.
2. Whenever the facts on screen say another network, typed code or route code, a strong warning names both countries.
3. A route code on the same network is approved with `entry: link`, without retyping.
4. A route code from another network is cleared from the field, and a second warning asks the person to type the code from the TV. The approval then goes up as `entry: typed`. A route code whose lookup failed stays a link code when it is looked up again.
5. Should a link approval from another network still reach the backend, it is refused with `422 code_must_be_typed` and the controller applies the same rule.

Every sign-in minted this way also notifies the account on the backend side, so an approval that was not the owner's is seen.

## Step-Up on Approve

An account with two-factor confirmed has to prove who is approving. The backend answers `423 step_up_required`, `MagicStarterDeviceApproveController.approve()` returns `MagicStarterDeviceApproveOutcome.needsProof`, and the view opens the identity dialog (`confirmIdentity`, see [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md)). The proof is spread into the approve body and sent again:

```dart
final outcome = await controller.approve();
if (outcome == MagicStarterDeviceApproveOutcome.needsProof) {
  await confirmIdentity(
    context,
    title: trans('magic_starter.device_approve.step_up_title'),
    description: trans('magic_starter.device_approve.step_up_description'),
    attempt: (proof) async {
      final next = await controller.approve(proof: proof);
      return next == MagicStarterDeviceApproveOutcome.needsProof
          ? controller.proofError ??
              trans('magic_starter.device_approve.proof_refused')
          : null;
    },
  );
}
```

A wrong proof is a `422` with field errors: the dialog stays open and shows the server's sentence (`proofError`), or `magic_starter.device_approve.proof_refused` when it sent none. Any other end closes the dialog and leaves the controller's error on the page.

## Routes and View Keys

`registerMagicStarterAuthRoutes()` registers both routes while `device_code` is on:

| Route | Helper | Group | View key | Layout |
|:------|:-------|:------|:---------|:-------|
| `/auth/device` | `MagicStarterConfig.deviceCodeRoute()` | `guest` middleware | `auth.device_code` | `layout.guest` |
| `/auth/device/approve?code=` | `MagicStarterConfig.deviceApproveRoute()` | `auth` middleware | `auth.device_approve` | `layout.guest` |

The approval route sits behind `auth`, so a signed-out visit is sent to sign in first. Where it lands afterwards depends on the `auth` middleware the host registers. The installer-generated copy (`lib/app/middleware/ensure_authenticated.dart`) records no intended url, so sign-in goes home and the approval page is not reopened. The package's `EnsureAuthenticated` records the link with its query, so sign-in returns to the approval page with its `code`, which is looked up as a link code like any other (see [Middleware](https://anilcancakir.com/magic/docs/starter/basics/middleware.md)). Both keys are registered only while `device_code` is on, and `MagicStarter.view.make` throws `StateError` for either one otherwise. The page titles are `magic_starter.titles.device_code` and `magic_starter.titles.device_approve`; the copy lives under `magic_starter.device_code.*` and `magic_starter.device_approve.*` in the English stub.

## Overriding a Screen

Register a builder under the key before the manager is first resolved; a default registers only while its key is free.

```dart
MagicStarter.view.register(
  'auth.device_code',
  () => const BrandedDeviceCodeView(),
);
```

Your view extends `MagicStatefulView<MagicStarterDeviceCodeController>`, calls `controller.start()` once after its first frame, reads `status`, `userCode`, `verificationUri`, `verificationUriComplete` and `secondsRemaining`, listens to `remaining` (a `ValueListenable<int>`, for example through a `ValueListenableBuilder`) for the countdown, since a tick does not notify the controller's listeners, and calls `controller.cancel()` when it closes. An approval view does the same with `MagicStarterDeviceApproveController`: `open`, `lookup`, `approve`, `deny`, `forget`, and the getters `status`, `facts`, `lookedUpCode`, `error`, `mustType`, `canApprove`, `needsLookup`, `factsMatchField` and `isBusy`.

## The Backend

The screens call `magic-starter-laravel`'s `api/v1` routes, which exist only with the `device-code` feature on (`Features::deviceCode()`). Every route answers 404 without it.

| Controller call | Request |
|:----------------|:--------|
| `MagicStarterDeviceCodeController.start` | `POST /auth/device/code` (guest) |
| `MagicStarterDeviceCodeController` poll | `POST /auth/device/token` (guest) |
| `MagicStarterDeviceApproveController.lookup` | `GET /auth/device/{user_code}` |
| `MagicStarterDeviceApproveController.approve` | `POST /auth/device/{user_code}/approve` with `entry` and any proof |
| `MagicStarterDeviceApproveController.deny` | `POST /auth/device/{user_code}/deny` |

The backend's `device_code` config holds the code lifetime, the poll interval, the `slow_down` step, the verification address the QR code is built on, and the abilities and lifetime of the token the TV receives. A token that cannot `*` (the TV's own) cannot approve another device.

## Gotchas

| Mistake | Fix |
|:--------|:----|
| Turning `device_code` on with the backend feature off | Every request answers 404 and the TV screen shows its failure message. Enable `device-code` on `magic-starter-laravel` too. |
| Expecting the approval link to approve on open | Opening it only looks the code up; the person presses Approve. |
| Relying on `entry=typed` in a URL to skip the typing step | The screen ignores `entry`: any code in the route is a link code, and from another network it must be typed from the TV. |
| Calling `Auth.login` with the polled token | Use the controller: the session concludes through `completeSignIn`, which every sign-in shares. |
| Reading `device_code` or `user_code` into a log or breadcrumb | Neither belongs there; the controllers log only a status or an error type. |
| Comparing a typed code as it stands | Normalise it with `MagicStarterDeviceApproveController.normaliseCode`; the dash and the case are not part of the code. |
| Calling `MagicStarter.view.make('auth.device_code')` with the toggle off | It throws `StateError`; check `MagicStarterConfig.hasDeviceCodeFeatures()` first. |

## Related Documentation

- [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): the other sign-in routes and the handoff.
- [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md): how the step-up proof is produced.
- [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature toggles and route prefixes.
- [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md): overriding a screen by key.
