# Phone sign-in

Customers sign in to your storefront with a code texted to their phone: they enter their number, get
a 6-digit code from your store, and type it back. The plugin adds this as a Medusa auth provider, so
it works alongside email and password sign-in and through Medusa's own `/auth` routes and JS SDK.

## Start with a 2FA campaign

Login codes have to come from a number on a campaign registered for the **2FA** use case on your
Signal House brand. Your marketing campaign doesn't cover them, and carriers can filter codes sent
from a campaign registered for something else.

1. In Signal House, create a campaign with the 2FA use case (or a mixed or low-volume campaign that
   lists 2FA as a sub-use case) on your brand.
2. Assign a number to it.
3. Wait for carrier approval. **This is the slow part: days to a couple of weeks.** Start it before you
   build the login form.

Until the campaign is active, phone sign-in stays off: the storefront gets "Phone sign-in isn't
available right now", and the Signal House page in your Medusa admin says what's missing.

Only US numbers (including US territories) can sign in by phone for now. Toll-free senders aren't
supported.

## Set it up

Phone sign-in needs the plugin in `plugins` (for its database tables and its per-IP limit) and the
provider registered under Medusa's auth module with the id **`signalhouse-phone`**:

```ts
module.exports = defineConfig({
  projectConfig: {
    // ...
    http: {
      // ...
      authMethodsPerActor: {
        user: ["emailpass"],
        customer: ["emailpass", "signalhouse-phone"],
      },
    },
  },
  plugins: ["@signalhouse-sms/medusa-plugin"],
  modules: [
    {
      resolve: "@medusajs/medusa/auth",
      options: {
        providers: [
          { resolve: "@medusajs/medusa/auth-emailpass", id: "emailpass" },
          {
            resolve: "@signalhouse-sms/medusa-plugin/providers/signalhouse-phone-auth",
            id: "signalhouse-phone",
            options: {
              apiKey: process.env.SIGNALHOUSE_API_KEY,
              senderPhoneNumber: process.env.SIGNALHOUSE_2FA_SENDER, // the number on your 2FA campaign
              storeName: "Acme Outfitters", // named in every code text
            },
          },
        ],
      },
    },
  ],
})
```

Then run `npx medusa db:migrate`.

| Option | Required | Description |
| --- | --- | --- |
| `apiKey` | Yes | Signal House API key for your account. |
| `senderPhoneNumber` | Yes | The number on your 2FA campaign. Codes are only sent once it's on an active 2FA campaign. |
| `storeName` | Yes | Your store's name. Each text reads "123456 is your Acme Outfitters sign-in code." |
| `maxCodesPerHour` | No | Codes your whole store may send in an hour. Defaults to 300. Raise it if real sign-ins hit it. |
| `trustProxy` | No | Proxies whose `X-Forwarded-For` header the per-IP limit believes, in Express's `trust proxy` syntax (addresses, CIDR ranges, `loopback`, `linklocal`, `uniquelocal`). Defaults to private-network addresses. |
| `baseUrl` | No | Signal House API URL. Defaults to `https://v2.signalhouse.io`. |

Keep the id `signalhouse-phone` and leave `user` (admin) sign-in out of it: phone sign-in is for
customers only, and it refuses every request if it's registered under another id, because its per-IP
limit wouldn't run.

Open **Signal House** in the Medusa admin to check it. The **Phone sign-in** section shows Ready
once the sender is on an active 2FA campaign, or says what to fix.

## How sign-in works

Both steps are `POST /auth/customer/signalhouse-phone`:

1. `{ "phone": "(415) 555-0132" }` texts a code and answers `{ "location": "otp" }`.
2. `{ "phone": "(415) 555-0132", "code": "123456" }` answers `{ "token": "..." }`.

A returning customer's token is a normal signed-in session. A phone that has never signed in gets a
token with no customer yet, the same as after email sign-up. Create the customer with that token
(Medusa needs an email for every customer account), then refresh the token to start the session. The
customer only types one code either way.

Errors come back as Medusa's usual 401 body, `{ "type": "unauthorized", "message": "..." }`, with a
message you can show as is. A burst of requests from one network gets a 429.

## Sample login form (Next.js)

Uses `@medusajs/js-sdk`, as Medusa's Next.js starter does.

```tsx
// src/modules/account/components/phone-login.tsx
"use client"

import { useState } from "react"
import { sdk } from "@lib/config"

type Step = "phone" | "code" | "details"

export default function PhoneLogin({ onSignedIn }: { onSignedIn: () => void }) {
  const [step, setStep] = useState<Step>("phone")
  const [phone, setPhone] = useState("")
  const [code, setCode] = useState("")
  const [email, setEmail] = useState("")
  const [firstName, setFirstName] = useState("")
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  async function run(action: () => Promise<void>) {
    setBusy(true)
    setError(null)
    try {
      await action()
    } catch (err: any) {
      setError(err?.message ?? "Something went wrong. Try again.")
    } finally {
      setBusy(false)
    }
  }

  const sendCode = () =>
    run(async () => {
      await sdk.auth.login("customer", "signalhouse-phone", { phone })
      setStep("code")
    })

  const verify = () =>
    run(async () => {
      await sdk.auth.login("customer", "signalhouse-phone", { phone, code })
      // A returning customer is signed in now. A new phone has no customer yet.
      const signedIn = await sdk.store.customer.retrieve().then(() => true, () => false)
      if (signedIn) onSignedIn()
      else setStep("details")
    })

  const createAccount = () =>
    run(async () => {
      await sdk.store.customer.create({ email, phone, first_name: firstName })
      await sdk.auth.refresh()
      onSignedIn()
    })

  return (
    <form onSubmit={(e) => e.preventDefault()}>
      {step === "phone" && (
        <>
          <label htmlFor="phone">Mobile number</label>
          <input id="phone" type="tel" autoComplete="tel" value={phone} onChange={(e) => setPhone(e.target.value)} />
          <button onClick={sendCode} disabled={busy || !phone}>Text me a code</button>
        </>
      )}
      {step === "code" && (
        <>
          <label htmlFor="code">Enter the 6-digit code we texted you</label>
          <input id="code" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={code} onChange={(e) => setCode(e.target.value)} />
          <button onClick={verify} disabled={busy || code.length !== 6}>Sign in</button>
          <button type="button" onClick={sendCode} disabled={busy}>Send a new code</button>
        </>
      )}
      {step === "details" && (
        <>
          <p>Welcome! Add your details to finish creating your account.</p>
          <label htmlFor="first_name">First name</label>
          <input id="first_name" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
          <label htmlFor="email">Email</label>
          <input id="email" type="email" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          <button onClick={createAccount} disabled={busy || !email}>Create account</button>
        </>
      )}
      {error && <p role="alert">{error}</p>}
    </form>
  )
}
```

`autoComplete="one-time-code"` lets iOS and Android offer the texted code above the keyboard.

## Limits and safety

| Rule | Value |
| --- | --- |
| Code length | 6 digits, from a secure random source |
| Code lifetime | 10 minutes. Requesting a new code replaces the old one. |
| Wrong guesses per code | 5, then the customer requests a new code |
| Wait between codes to one number | 60 seconds |
| Codes per number | 5 an hour, 10 a day |
| Code requests per IP address | 10 an hour |
| Code checks per IP address | 30 an hour |
| Codes the whole store sends | 300 an hour (the `maxCodesPerHour` option) |

- Codes are stored only as a keyed hash, derived from your store's `jwtSecret`. IP addresses are
  stored only as a keyed hash too, and both are deleted after two days.
- A phone gets an account only after its code checks out, so nobody can claim a number they can't
  receive texts on.
- The per-IP limit counts each request under the address it connected from. It believes an
  `X-Forwarded-For` header only when the connection comes from a private-network address (where load
  balancers and ingress controllers usually sit), so a client on the internet can't dodge the limit by
  changing the header. If your proxy connects from a public address, list it in `trustProxy`.
- Signing in by phone is not consent to texts. It never creates or changes an SMS consent record, and
  no marketing or cart-recovery text goes to a number just because it signed in. Consent still comes
  only from the customer replying JOIN (see the [consent integration guide](./CONSENT_INTEGRATION.md)).

## Accounts that already exist

Phone sign-in creates its own sign-in for the phone. A customer who already has an email and password
account and then signs in by phone for the first time will be asked for an email; using the same
email fails with "Customer with this email already has an account". Linking a phone to an existing
email account isn't supported yet: those customers should keep signing in with their email.

## Troubleshooting

| What you see | Why |
| --- | --- |
| "Phone sign-in isn't available right now" | Check the **Phone sign-in** section in the admin. The sender isn't on an active 2FA campaign, Signal House couldn't be reached, or the provider id isn't `signalhouse-phone`. The server log has the detail. |
| `The actor type customer is not allowed to use the auth provider signalhouse-phone` | Add `signalhouse-phone` to `authMethodsPerActor.customer`. |
| "We couldn't text a code to that number" | Signal House didn't accept the text, for example because the number opted out of your messages. The server log has Signal House's reason. |
| Everyone hits the 429 at once | Every request looks like it comes from your proxy, because the proxy connects from a public address. Add it to `trustProxy`. |
| `Sign up through POST /auth/customer/signalhouse-phone` | Your storefront called `sdk.auth.register`. Phone sign-up goes through `sdk.auth.login`, as in the sample above. |
| "Phone sign-in isn't available right now" for everyone, and the log says the store-wide cap was reached | More sign-in codes went out this hour than `maxCodesPerHour` allows. If that's real traffic, raise it. If not, someone is requesting codes for numbers that aren't your customers. |
