Sign in from a native or desktop app
For: a developer of an Expo app or an Electron app.
What it does: the app opens core’s sign-in page in the system browser. The person signs in with any method, and the app receives a bearer token.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- An app scheme, such as
myapp://, that the device routes to your app. The opener contract uses it.
- Set
handoff.schemeson the API to the app scheme, with its://.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
export function createHandoffAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, // The app schemes that the one-time code may go to, each with its "://". // A sign-in ends at myapp://auth?code=… on the device. handoff: { schemes: ["myapp://"] }, });}- In the app, make a handoff with the redirect
myapp://authand the opener of the platform. - In Expo, pass
expoOpener(WebBrowser)andexpoCrypto(Crypto). Hermes has nocrypto.subtle. - In Electron, call
app.requestSingleInstanceLock()first, thenapp.setAsDefaultProtocolClient("myapp"). - In Electron, forward the URL of the
second-instanceevent toopener.receive. - Call
handoff.signIn(). It answers{ token, user, session }. - Store the token. In Electron, use
createTokenStoreonsafeStorage, in the main process only. - Make the client with
credentials: "omit"andtoken: () => store.get().
import { createHandoff, type HandoffOpener } from "@authtempo/handoff";
/** * The app side. In Expo the opener is `expoOpener(WebBrowser)` and the crypto * is `expoCrypto(Crypto)` from `@authtempo/handoff/expo`. In Electron the * opener is `electronOpener({ shell, app })` from `@authtempo/handoff/electron`. */export function createAppHandoff( opener: HandoffOpener, fetchImpl: typeof fetch = globalThis.fetch,) { return createHandoff({ baseURL: "https://api.example.com", // `<scheme>auth` for the scheme `myapp://` of the API's handoff.schemes. redirect: "myapp://auth", opener, fetch: fetchImpl, });}import type { HandoffOpener } from "@authtempo/handoff";import { describe, expect, it } from "vitest";import { API, call, harness, linkIn, sessionCookieOf } from "../support/harness.ts";import { createHandoffAuth } from "./handoff.ts";import { createAppHandoff } from "./handoff-app.ts";
describe("sign in from a native or desktop app", () => { it("signs in through the system browser and redeems the code for a bearer token", async () => { const h = harness(); const auth = createHandoffAuth(h); // The system browser: the person signs in by magic link and presses Continue. const opener: HandoffOpener = { async open(url) { const page = await (await auth.handle(new Request(url))).text(); const id = /hs_[A-Za-z0-9_-]{43}/.exec(page)?.[0] ?? ""; const next = `/auth/handoff/continue?h=${id}`; await call(auth, "POST", "/auth/magic-link/request", { email: "ada@example.com", next }); const token = linkIn(h, "ada@example.com").searchParams.get("token") ?? ""; const verify = await auth.handle( new Request(`${API}/auth/magic-link/verify`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: API }, body: new URLSearchParams({ token }).toString(), }), ); const cookie = sessionCookieOf(verify); expect(verify.headers.get("location")).toBe(`${API}${next}`); const press = await auth.handle( new Request(`${API}/auth/handoff/continue`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: API, cookie }, body: new URLSearchParams({ h: id }).toString(), }), ); return press.headers.get("location"); }, }; const handoff = createAppHandoff(opener, ((input: RequestInfo | URL, init?: RequestInit) => auth.handle(new Request(input, init))) as typeof fetch); const result = await handoff.signIn(); expect(result.ok && result.value.token.startsWith("ts_")).toBe(true); expect(result.ok && result.value.user.email).toBe("ada@example.com"); });
it("refuses a redirect that no scheme of the config admits", async () => { const auth = createHandoffAuth(harness()); const res = await call( auth, "GET", `/auth/handoff/start?challenge=${"a".repeat(43)}&redirect=evil://auth`, ); expect(await res.json()).toEqual({ error: "invalid_body" }); });});How it behaves
Section titled “How it behaves”- The app makes a PKCE verifier. The verifier leaves the app once, in the redeem body.
- The sign-in page shows every method of the config. Each method ends on a confirm page that names the account.
- The code is minted only when the person presses the button of the confirm page. It lives two minutes and redeems once.
- The URL that the app receives must start with exactly the configured redirect, or no redeem happens.
- Show
user.emailafter each sign-in, so that the person sees a sign-in to another account. - The start has the limit
handoff-start:ip:<ip>30 per 15 minutes. The redeem hashandoff-redeem:ip:<ip>20 per 15 minutes.
If it fails
Section titled “If it fails”invalid_body: the challenge or the redirect of the start is malformed, or no scheme of the config admits it.invalid_token: the code is spent or unknown, or the verifier does not match.token_expired: the code is older than two minutes.rate_limited: too many starts or redeems from the IP.redirect_mismatchandcancelledcome from the handoff package, not from the server. The handoff reference lists them.