Skip to content

Sign in from a browser extension

For: a developer of a browser extension that calls an authtempo API.

What it does: the extension signs a person in by email code and keeps a bearer token. The API trusts the extension’s origin.

Chrome only. A Firefox extension cannot sign in today: each browser instance has a random origin, and the API answers 403 origin_not_trusted.

  1. Add chrome-extension:// and the ID to trustedOrigins on the API. Write the exact origin: core refuses a wildcard.
  2. Add the API’s origin to host_permissions in manifest.json.
  3. Make the client with credentials: "omit" and the stored token as the bearer.
  4. Sign in by email code in the popup, and keep the token in chrome.storage.local.
  5. Clear the token when the session ends. The client calls onSessionEnd with the token that ended. Clear the token store only when it still holds that token.
  6. Sign out with the signOut of the sample. It clears the token store when the server ended the session.
The API
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/**
* The origin of the extension: `chrome-extension://` and its ID. Put the
* `key` of the store item in manifest.json, so a build you load unpacked
* has the same ID as the store item.
*/
export const EXTENSION_ORIGIN = "chrome-extension://abcdefghijklmnopabcdefghijklmnop";
export function createExtensionAuth(
deps: { storage: StorageAdapter; mail: MailPort; secret: string },
mode: "token" | "cookie" = "token",
) {
return createAuth({
baseURL: "https://api.example.com",
// An exact origin. Core refuses a wildcard.
trustedOrigins: [EXTENSION_ORIGIN],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
// Cookie mode only: the extension is another site than the API.
...(mode === "cookie" ? { cookie: { sameSite: "None" as const } } : {}),
});
}
The extension
import { type Client, createClient } from "@authtempo/client";
/** Where the extension keeps the token. In an extension: chrome.storage.local. */
export interface TokenBox {
get(): Promise<string | null>;
set(token: string): Promise<void>;
clear(): Promise<void>;
}
/** The client of the extension, in token mode: the bearer, and no cookie. */
export function createExtensionClient(box: TokenBox, fetch?: typeof globalThis.fetch): Client {
return createClient({
baseURL: "https://api.example.com",
credentials: "omit",
token: () => box.get(),
// The server ended the session: the token is dead. Clear it only when the box still
// holds the token that ended, because a newer sign-in may have written another one.
onSessionEnd: async (sent) => {
if ((await box.get()) === sent) await box.clear();
},
...(fetch ? { fetch } : {}),
});
}
/** The sign-in by email code. `askCode` shows a field in the popup and answers what the person types. */
export async function signInByCode(
client: Client,
box: TokenBox,
email: string,
askCode: () => Promise<string>,
) {
const sent = await client.emailOtp.request({ email });
if (!sent.ok) return sent;
const r = await client.emailOtp.verify({ email, code: await askCode() });
// A person with the second factor on gets a challenge, not a token.
if (r.ok && "token" in r.value) {
await box.set(r.value.token);
// The verify read the session before the box held the token: read it again for the popup.
client.store.refetchIfStarted();
}
return r;
}
/** The sign-out. It clears the box when the server ended the session or did not know it. */
export async function signOut(client: Client, box: TokenBox) {
const r = await client.signOut();
// A network failure keeps the token, so the person can sign out again.
if (r.ok || r.code === "unauthorized") await box.clear();
return r;
}
The sign-in as a test
import { describe, expect, it, vi } from "vitest";
import { call, codeIn, harness } from "../support/harness.ts";
import { createExtensionAuth, EXTENSION_ORIGIN } from "./browser-extension.ts";
import {
createExtensionClient,
signInByCode,
signOut,
type TokenBox,
} from "./browser-extension-client.ts";
function memoryBox(): TokenBox & { value(): string | null } {
let token: string | null = null;
return {
get: async () => token,
set: async (t) => {
token = t;
},
clear: async () => {
token = null;
},
value: () => token,
};
}
/** The extension's fetch: the browser sends the extension's origin. */
function extensionFetch(auth: ReturnType<typeof createExtensionAuth>): typeof globalThis.fetch {
return (async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const headers = new Headers(req.headers);
headers.set("origin", EXTENSION_ORIGIN);
return auth.handle(new Request(req, { headers }));
}) as typeof globalThis.fetch;
}
describe("sign in from a browser extension", () => {
it("signs in by email code in token mode: the bearer, no cookie, and the sign-out clears the token", async () => {
const h = harness();
const auth = createExtensionAuth(h);
const seen: {
credentials: RequestCredentials;
cookie: string | null;
authorization: string | null;
}[] = [];
// The extension's fetch: the browser sends the extension's origin.
const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const req = new Request(input, init);
const headers = new Headers(req.headers);
headers.set("origin", EXTENSION_ORIGIN);
seen.push({
credentials: req.credentials,
cookie: headers.get("cookie"),
authorization: headers.get("authorization"),
});
return auth.handle(new Request(req, { headers }));
}) as typeof globalThis.fetch;
const box = memoryBox();
const client = createExtensionClient(box, fetch);
const r = await signInByCode(client, box, "ada@example.com", async () =>
codeIn(h, "ada@example.com"),
);
expect(r.ok).toBe(true);
expect(box.value()).toMatch(/^ts_/);
const s = await client.session();
expect(s.ok && s.value?.user.email).toBe("ada@example.com");
expect(seen.at(-1)).toEqual({
credentials: "omit",
cookie: null,
authorization: `Bearer ${box.value()}`,
});
// The sign-out helper clears the box itself, with no later read.
expect(await signOut(client, box)).toEqual({ ok: true, value: { ok: true } });
expect(box.value()).toBeNull();
});
it("answers the extension's preflight, and refuses an origin of another extension", async () => {
const auth = createExtensionAuth(harness());
const ok = await call(auth, "OPTIONS", "/auth/session", undefined, {
origin: EXTENSION_ORIGIN,
});
expect(ok.status).toBe(204);
expect(ok.headers.get("access-control-allow-origin")).toBe(EXTENSION_ORIGIN);
// Firefox: a random UUID per browser instance, which trustedOrigins cannot name.
const firefox = await call(
auth,
"POST",
"/auth/otp/request",
{ email: "a@example.com" },
{
origin: "moz-extension://944cfddf-7a95-3c47-bd9a-663b3ce8d699",
},
);
expect(firefox.status).toBe(403);
expect(await firefox.json()).toEqual({ error: "origin_not_trusted" });
});
it("sets a SameSite=None cookie in cookie mode", async () => {
const h = harness();
const auth = createExtensionAuth(h, "cookie");
await call(
auth,
"POST",
"/auth/otp/request",
{ email: "ada@example.com" },
{ origin: EXTENSION_ORIGIN },
);
const res = await call(
auth,
"POST",
"/auth/otp/verify",
{ email: "ada@example.com", code: codeIn(h, "ada@example.com") },
{ origin: EXTENSION_ORIGIN },
);
expect(res.status).toBe(200);
expect(res.headers.get("set-cookie")).toContain("SameSite=None");
expect(res.headers.get("access-control-allow-credentials")).toBe("true");
// Token mode keeps the default: the API's cookie stays SameSite=Lax for every other site.
const t = harness();
const tokenAuth = createExtensionAuth(t);
await call(
tokenAuth,
"POST",
"/auth/otp/request",
{ email: "ada@example.com" },
{
origin: EXTENSION_ORIGIN,
},
);
const tokenRes = await call(
tokenAuth,
"POST",
"/auth/otp/verify",
{ email: "ada@example.com", code: codeIn(t, "ada@example.com") },
{ origin: EXTENSION_ORIGIN },
);
expect(tokenRes.headers.get("set-cookie")).toContain("SameSite=Lax");
});
it("shows the person in a subscribed store after the sign-in", async () => {
const h = harness();
const box = memoryBox();
const client = createExtensionClient(box, extensionFetch(createExtensionAuth(h)));
// A popup renders from client.store: it subscribes before the sign-in.
const stop = client.store.subscribe(() => {});
await vi.waitFor(() => expect(client.store.get().isPending).toBe(false));
await signInByCode(client, box, "ada@example.com", async () => codeIn(h, "ada@example.com"));
await vi.waitFor(() => expect(client.store.get().data?.user.email).toBe("ada@example.com"));
stop();
});
it("keeps a newer token when the session read of an older token ends", async () => {
const h = harness();
const auth = createExtensionAuth(h);
const box = memoryBox();
let during: (() => Promise<void>) | null = null;
const base = extensionFetch(auth);
const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const res = await base(input, init);
// A newer sign-in writes its token while the read of the older token is on its way back.
if (during && new URL(new Request(input, init).url).pathname.endsWith("/session"))
await during();
return res;
}) as typeof globalThis.fetch;
const client = createExtensionClient(box, fetch);
await signInByCode(client, box, "ada@example.com", async () => codeIn(h, "ada@example.com"));
// The server ends the older session.
for (const row of await h.storage.findMany("session", []))
await h.storage.delete("session", [{ field: "id", op: "eq", value: row.id }]);
during = () => box.set("ts_newer");
expect(await client.session()).toEqual({ ok: true, value: null });
expect(box.value()).toBe("ts_newer");
});
it("keeps the token when the sign-out does not reach the server", async () => {
const h = harness();
const base = extensionFetch(createExtensionAuth(h));
let offline = false;
const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
if (offline) throw new TypeError("Failed to fetch");
return base(input, init);
}) as typeof globalThis.fetch;
const box = memoryBox();
const client = createExtensionClient(box, fetch);
await signInByCode(client, box, "ada@example.com", async () => codeIn(h, "ada@example.com"));
const token = box.value();
offline = true;
// The server never heard the sign-out, so the token stays for a second try.
expect(await signOut(client, box)).toEqual({ ok: false, code: "network", status: 0 });
expect(box.value()).toBe(token);
});
});
  • Token mode sends no cookie, so no cross-site cookie rule applies. It is the mode of this page.
  • Cookie mode needs cookie: { sameSite: "None" } on the API, because the extension is another site. This page shows the client of token mode only.
  • Firefox gives each browser instance its own moz-extension:// origin. trustedOrigins cannot name it. If Firefox sends that origin, the API answers 403.
  • chrome.storage.local is not encrypted on disk, and a content script of the extension can read it. The token is a bearer credential for the whole session.
  • Read the token only in the service worker or the popup. Never read it in a content script.
  • chrome.storage.session keeps the token in memory only. The cost: the person signs in again after each browser restart.
  • host_permissions lets the extension send any request to the API origin. Name the API origin only.
  • Cookie mode sets SameSite=None on the API’s session cookie for every site, not only for the extension. A request from another site then carries the cookie.
  • Token mode is the safer default. Its cookie keeps SameSite=Lax, and the client sends no cookie.