Skip to content

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.

  1. Set handoff.schemes on the API to the app scheme, with its ://.
The handoff config
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://"] },
});
}
  1. In the app, make a handoff with the redirect myapp://auth and the opener of the platform.
  2. In Expo, pass expoOpener(WebBrowser) and expoCrypto(Crypto). Hermes has no crypto.subtle.
  3. In Electron, call app.requestSingleInstanceLock() first, then app.setAsDefaultProtocolClient("myapp").
  4. In Electron, forward the URL of the second-instance event to opener.receive.
  5. Call handoff.signIn(). It answers { token, user, session }.
  6. Store the token. In Electron, use createTokenStore on safeStorage, in the main process only.
  7. Make the client with credentials: "omit" and token: () => store.get().
The app side
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,
});
}
A full handoff as a test
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" });
});
});
  • 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.email after 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 has handoff-redeem:ip:<ip> 20 per 15 minutes.
  • 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_mismatch and cancelled come from the handoff package, not from the server. The handoff reference lists them.