# Signing in by mail: magic

A link, and a six-digit code in the same message, for whoever holds the
address: an [extension](../extensions/README.md) over the
[mail](mail.md) extension, into the same accounts and sessions as a
password. Back to the [map](README.md).

```text
use "pkg:magic/magic.mote"

action send
  magicSend(email, "/orders")?
  said = "Look in your mail."

action enter
  go(magicCode(email, code)?)
```

```toml
[packages]
magic = "../mote/extensions/magic"
mail = "../mote/extensions/mail"
```

| | |
|---|---|
| `magicSend(email, to)` | A `server fn`: mails a link to `/auth/magic/<token>` and a code. The same answer whether or not there is an account for the address (and nothing is sent when there is none): who has an account is nobody else's to learn. Five an hour for one address. |
| `magicCode(email, code)` | Signs in by the code; gives where to go (`to`, a path of this site, `/` else). Ten a minute from one address; five wrong tries spend that mail. |
| `GET /auth/magic/<token>` | A page with a button. Opening it spends nothing, so a mail service's scanner that opens every link (Outlook's does) does not use it up. |
| `POST /auth/magic/<token>` | The button: spends the link and signs in. |

- A link and its code are good for fifteen minutes, once, and only the
  newest mail's. Both are kept as hashes.
- Using one shows the address is the person's (`auth.setVerified`). An
  account with a [second factor](second-factor.md) owes it after this, as
  after a password.
- `MAGIC_SIGNUP=1`: an address with no account gets one when its link or
  code is used. Unset, only accounts that are there are signed in.
  `MAGIC_SUBJECT` says the subject (unset: "Your sign-in code is …").
- A link opened on another device signs in that device: it is the mail's
  holder, wherever they open it.

Tested by `tests/all.sh real_magic` (`mote test`: codes, tries, the newest
only, fifteen minutes, an address with no account, `MAGIC_SIGNUP`). The two
routes have not been driven by a browser, and no real mail has been sent.
Source: `extensions/magic/magic.mote`.
