Passkeys: say why the section can't list them, instead of vanishing #120

Merged
jcoffey-dev merged 1 commits from fix/119-passkeys-section-reason into main 2026-11-19 17:15:56 +00:00
14 changed files with 184 additions and 20 deletions

No files matched your search

+34 -6
View File
@@ -1,10 +1,19 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const call = vi.fn();
vi.mock("@/jmap/client", () => ({ client: { call: (...a: unknown[]) => call(...a) }, INBUXA_CAP: "urn:inbuxa:jmap" }));
vi.mock("@/jmap/client", async (importActual) => {
const actual = await importActual<typeof import("@/jmap/client")>();
return {
client: { call: (...a: unknown[]) => call(...a) },
INBUXA_CAP: "urn:inbuxa:jmap",
JmapMethodError: actual.JmapMethodError,
ApiError: actual.ApiError,
};
});
import { addErrorMessage, listPasskeys, passkeyPolicy, removePasskey, renamePasskey, startPasskey } from "@/lib/passkeys";
import type { JmapSession } from "@/jmap/types";
import { ApiError, JmapMethodError } from "@/jmap/client";
describe("passkeys (#334)", () => {
beforeEach(() => { call.mockReset(); });
@@ -18,13 +27,32 @@ describe("passkeys (#334)", () => {
});
const rows = await listPasskeys("acc");
expect(call).toHaveBeenCalledWith("inbuxa:Passkey/get", expect.objectContaining({ accountId: "acc", ids: null }), ["urn:inbuxa:jmap"]);
expect(rows?.map((r) => r.id)).toEqual(["b", "a"]);
expect(rows?.[0]).toMatchObject({ usable: false, lastUsedAt: "2026-11-11T10:00:00Z" });
expect(rows.kind).toBe("list");
if (rows.kind !== "list") return;
expect(rows.rows.map((r) => r.id)).toEqual(["b", "a"]);
expect(rows.rows[0]).toMatchObject({ usable: false, lastUsedAt: "2026-11-11T10:00:00Z" });
});
it("hides the section on a server without passkeys", async () => {
call.mockImplementation(async () => { throw new Error("unknownMethod"); });
expect(await listPasskeys("acc")).toBeNull();
it("hides the section only on a server without passkeys (#119)", async () => {
call.mockImplementation(async () => { throw new JmapMethodError("inbuxa:Passkey/get", { type: "unknownMethod" }); });
expect(await listPasskeys("acc")).toEqual({ kind: "none" });
call.mockImplementation(async () => { throw new ApiError(400, "urn:ietf:params:jmap:error:unknownCapability"); });
expect(await listPasskeys("acc")).toEqual({ kind: "none" });
});
it("says when the server won't let the account use passkeys (#119)", async () => {
call.mockImplementation(async () => {
throw new JmapMethodError("inbuxa:Passkey/get", { type: "forbidden", description: "You are not authorized to perform this action" });
});
expect(await listPasskeys("acc")).toEqual({ kind: "forbidden" });
});
it("reports any other failure so it can be retried (#119)", async () => {
call.mockImplementation(async () => { throw new ApiError(502, "error", "Bad Gateway"); });
expect(await listPasskeys("acc")).toEqual({ kind: "failed", message: "Bad Gateway" });
call.mockImplementation(async () => { throw new JmapMethodError("inbuxa:Passkey/get", { type: "serverFail" }); });
const failed = await listPasskeys("acc");
expect(failed.kind).toBe("failed");
});
it("returns the registration page of a new passkey", async () => {
+26 -7
View File
@@ -1,4 +1,4 @@
import { client, INBUXA_CAP } from "@/jmap/client";
import { ApiError, client, INBUXA_CAP, JmapMethodError } from "@/jmap/client";
import type { Id, JmapSession } from "@/jmap/types";
import { t } from "@/lib/i18n";
@@ -45,19 +45,38 @@ function parse(raw: Record<string, unknown>): Passkey {
}
/**
* The account's passkeys, newest first; null when the server has no passkeys
* (not inbuxa, or older than the feature), so the section stays hidden.
* What listing the account's passkeys found (#119): the passkeys; `none`
* when the server has no passkeys (not inbuxa, or older than the feature),
* so the section stays hidden; `forbidden` when the server has them but
* won't let this account use them; `failed` for anything else, with the
* reason, so the reader can try again.
*/
export async function listPasskeys(accountId: string): Promise<Passkey[] | null> {
export type PasskeyListing =
| { kind: "list"; rows: Passkey[] }
| { kind: "none" }
| { kind: "forbidden" }
| { kind: "failed"; message: string };
/** Errors that mean the server doesn't have passkeys at all. */
const NO_PASSKEYS = new Set(["unknownMethod", "unknownCapability", "urn:ietf:params:jmap:error:unknownCapability"]);
/** The account's passkeys, newest first, or why there are none to show. */
export async function listPasskeys(accountId: string): Promise<PasskeyListing> {
try {
const res = await client.call<{ list?: Record<string, unknown>[] }>(
"inbuxa:Passkey/get",
{ accountId, ids: null, properties: PROPERTIES },
[INBUXA_CAP],
);
return (res.list ?? []).map(parse).sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
} catch {
return null;
const rows = (res.list ?? []).map(parse).sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
return { kind: "list", rows };
} catch (err) {
if (err instanceof JmapMethodError) {
if (NO_PASSKEYS.has(err.type)) return { kind: "none" };
if (err.type === "forbidden") return { kind: "forbidden" };
}
if (err instanceof ApiError && NO_PASSKEYS.has(err.code)) return { kind: "none" };
return { kind: "failed", message: (err as Error)?.message || t("Couldn't load your passkeys.") };
}
}
+2
View File
@@ -1860,6 +1860,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Schließen Sie das Hinzufügen des Passkeys im geöffneten Fenster ab. Die Seite dort ist 10 Minuten gültig.",
"Rename passkey": "Passkey umbenennen",
"Passkeys are turned off for this account.": "Passkeys sind für dieses Konto deaktiviert.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Passkeys sind für dieses Konto nicht verfügbar. Wenden Sie sich an Ihren E-Mail-Administrator, wenn Sie sie benötigen.",
"Couldn't load your passkeys.": "Ihre Passkeys konnten nicht geladen werden.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Dieses Konto hat bereits so viele Passkeys wie erlaubt. Entfernen Sie einen, um einen weiteren hinzuzufügen.",
"Couldn't add the passkey.": "Der Passkey konnte nicht hinzugefügt werden.",
"The server didn't return a page to add the passkey on.": "Der Server hat keine Seite zum Hinzufügen des Passkeys zurückgegeben.",
+2
View File
@@ -1833,6 +1833,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Termine de añadir la llave de acceso en la ventana que se abrió. La página funciona durante 10 minutos.",
"Rename passkey": "Renombrar llave de acceso",
"Passkeys are turned off for this account.": "Las llaves de acceso están desactivadas para esta cuenta.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Las llaves de acceso no están disponibles para esta cuenta. Pide a tu administrador de correo que las active si las necesitas.",
"Couldn't load your passkeys.": "No se pudieron cargar tus llaves de acceso.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Esta cuenta ya tiene todas las llaves de acceso permitidas. Quite una para añadir otra.",
"Couldn't add the passkey.": "No se pudo añadir la llave de acceso.",
"The server didn't return a page to add the passkey on.": "El servidor no devolvió ninguna página para añadir la llave de acceso.",
+2
View File
@@ -1838,6 +1838,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Terminez l'ajout de la clé d'accès dans la fenêtre qui s'est ouverte. La page reste valable 10 minutes.",
"Rename passkey": "Renommer la clé d'accès",
"Passkeys are turned off for this account.": "Les clés d'accès sont désactivées pour ce compte.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Les clés d'accès ne sont pas disponibles pour ce compte. Demandez à votre administrateur de messagerie si vous en avez besoin.",
"Couldn't load your passkeys.": "Impossible de charger vos clés d'accès.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Ce compte a déjà autant de clés d'accès que permis. Supprimez-en une pour en ajouter une autre.",
"Couldn't add the passkey.": "Impossible d'ajouter la clé d'accès.",
"The server didn't return a page to add the passkey on.": "Le serveur n'a renvoyé aucune page pour ajouter la clé d'accès.",
+2
View File
@@ -1841,6 +1841,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "開いたウィンドウでパスキーの追加を完了してください。そのページは 10 分間有効です。",
"Rename passkey": "パスキーの名前を変更",
"Passkeys are turned off for this account.": "このアカウントではパスキーが無効になっています。",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "このアカウントではパスキーを利用できません。必要な場合はメール管理者にお問い合わせください。",
"Couldn't load your passkeys.": "パスキーを読み込めませんでした。",
"This account has as many passkeys as it's allowed. Remove one to add another.": "このアカウントには上限までパスキーがあります。追加するには 1 つ削除してください。",
"Couldn't add the passkey.": "パスキーを追加できませんでした。",
"The server didn't return a page to add the passkey on.": "サーバーからパスキー追加用のページが返されませんでした。",
+2
View File
@@ -1833,6 +1833,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Rond het toevoegen van de toegangssleutel af in het venster dat is geopend. De pagina daar werkt 10 minuten.",
"Rename passkey": "Toegangssleutel hernoemen",
"Passkeys are turned off for this account.": "Toegangssleutels zijn uitgeschakeld voor dit account.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Toegangssleutels zijn niet beschikbaar voor dit account. Vraag je e-mailbeheerder als je ze nodig hebt.",
"Couldn't load your passkeys.": "Je toegangssleutels konden niet worden geladen.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Dit account heeft al zoveel toegangssleutels als toegestaan. Verwijder er een om een andere toe te voegen.",
"Couldn't add the passkey.": "Kon de toegangssleutel niet toevoegen.",
"The server didn't return a page to add the passkey on.": "De server gaf geen pagina terug om de toegangssleutel toe te voegen.",
+2
View File
@@ -1836,6 +1836,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Conclua a adição da chave de acesso na janela que abriu. A página funciona por 10 minutos.",
"Rename passkey": "Renomear chave de acesso",
"Passkeys are turned off for this account.": "As chaves de acesso estão desativadas para esta conta.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "As chaves de acesso não estão disponíveis para esta conta. Peça ao administrador do seu e-mail se precisar delas.",
"Couldn't load your passkeys.": "Não foi possível carregar suas chaves de acesso.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Esta conta já tem o máximo de chaves de acesso permitido. Remova uma para adicionar outra.",
"Couldn't add the passkey.": "Não foi possível adicionar a chave de acesso.",
"The server didn't return a page to add the passkey on.": "O servidor não retornou uma página para adicionar a chave de acesso.",
+2
View File
@@ -1835,6 +1835,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Завершите добавление ключа доступа в открывшемся окне. Страница там действует 10 минут.",
"Rename passkey": "Переименовать ключ доступа",
"Passkeys are turned off for this account.": "Ключи доступа отключены для этой учётной записи.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Ключи доступа недоступны для этой учётной записи. Если они вам нужны, обратитесь к администратору почты.",
"Couldn't load your passkeys.": "Не удалось загрузить ваши ключи доступа.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "У этой учётной записи уже максимальное число ключей доступа. Удалите один, чтобы добавить другой.",
"Couldn't add the passkey.": "Не удалось добавить ключ доступа.",
"The server didn't return a page to add the passkey on.": "Сервер не вернул страницу для добавления ключа доступа.",
+2
View File
@@ -1711,6 +1711,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Geçiş anahtarını eklemeyi açılan pencerede tamamlayın. Oradaki sayfa 10 dakika geçerlidir.",
"Rename passkey": "Geçiş anahtarını yeniden adlandır",
"Passkeys are turned off for this account.": "Bu hesap için geçiş anahtarları kapalı.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Bu hesap için geçiş anahtarları kullanılamıyor. Gerekirse e-posta yöneticinize başvurun.",
"Couldn't load your passkeys.": "Geçiş anahtarlarınız yüklenemedi.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Bu hesapta izin verilen sayıda geçiş anahtarı var. Başka bir tane eklemek için birini kaldırın.",
"Couldn't add the passkey.": "Geçiş anahtarı eklenemedi.",
"The server didn't return a page to add the passkey on.": "Sunucu, geçiş anahtarını eklemek için bir sayfa döndürmedi.",
+2
View File
@@ -1829,6 +1829,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "Завершіть додавання ключа доступу у вікні, що відкрилося. Сторінка там діє 10 хвилин.",
"Rename passkey": "Перейменувати ключ доступу",
"Passkeys are turned off for this account.": "Ключі доступу вимкнено для цього облікового запису.",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "Ключі доступу недоступні для цього облікового запису. Якщо вони вам потрібні, зверніться до адміністратора пошти.",
"Couldn't load your passkeys.": "Не вдалося завантажити ваші ключі доступу.",
"This account has as many passkeys as it's allowed. Remove one to add another.": "Цей обліковий запис уже має максимальну кількість ключів доступу. Видаліть один, щоб додати інший.",
"Couldn't add the passkey.": "Не вдалося додати ключ доступу.",
"The server didn't return a page to add the passkey on.": "Сервер не повернув сторінку для додавання ключа доступу.",
+2
View File
@@ -1840,6 +1840,8 @@ export const catalog: Catalog = {
"Finish adding the passkey in the window that opened. The page there works for 10 minutes.": "请在打开的窗口中完成添加通行密钥。该页面 10 分钟内有效。",
"Rename passkey": "重命名通行密钥",
"Passkeys are turned off for this account.": "此账户已关闭通行密钥。",
"Passkeys aren't available for this account. Ask your mail administrator if you need them.": "此账户无法使用通行密钥。如需使用,请联系您的邮件管理员。",
"Couldn't load your passkeys.": "无法加载您的通行密钥。",
"This account has as many passkeys as it's allowed. Remove one to add another.": "此账户的通行密钥已达上限。删除一个后才能添加新的。",
"Couldn't add the passkey.": "无法添加通行密钥。",
"The server didn't return a page to add the passkey on.": "服务器没有返回用于添加通行密钥的页面。",
+25 -7
View File
@@ -8,7 +8,7 @@ import { toast } from "@/ui/toast";
import { confirmDialog, Dialog } from "@/ui/dialog";
import { plural, t, tNode } from "@/lib/i18n";
import { SIGNIN_NOTICE_KEY } from "@/views/Login";
import { addErrorMessage, listPasskeys, passkeyPolicy, removePasskey, renamePasskey, startPasskey, type Passkey } from "@/lib/passkeys";
import { addErrorMessage, listPasskeys, passkeyPolicy, removePasskey, renamePasskey, startPasskey, type Passkey, type PasskeyListing } from "@/lib/passkeys";
interface SessionRow {
id: string;
@@ -375,22 +375,40 @@ function AppPasswords({ state, reload }: { state: SecurityState | null; reload:
/**
* inbuxa #334: the account's passkeys. Only with sign-in on the mail
* server's page, the one place a passkey can be used; hidden when the server
* has no passkeys. Adding one runs on the server's own page in a new window,
* server's page, the one place a passkey can be used; hidden only when the
* server has no passkeys, and otherwise says why it can't list them (#119). Adding one runs on the server's own page in a new window,
* because a passkey is bound to the server's name, not this webmail's.
*/
export function Passkeys({ accountId, allowed, max }: { accountId: string; allowed?: boolean; max?: number }) {
const [rows, setRows] = useState<Passkey[] | null | undefined>(undefined);
const [listing, setListing] = useState<PasskeyListing | undefined>(undefined);
const rows = listing?.kind === "list" ? listing.rows : undefined;
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [waiting, setWaiting] = useState(false);
const [renaming, setRenaming] = useState<Passkey | null>(null);
const [newName, setNewName] = useState("");
const reload = useCallback(async () => setRows(await listPasskeys(accountId)), [accountId]);
const reload = useCallback(async () => setListing(await listPasskeys(accountId)), [accountId]);
useEffect(() => { void reload(); }, [reload]);
if (rows === null) return null;
if (listing?.kind === "none") return null;
// #119: the server has passkeys but this account can't use them, or the
// list didn't load: say so, rather than the section disappearing
if (listing?.kind === "forbidden" || listing?.kind === "failed") {
return (
<>
<h2>{t("Passkeys")}</h2>
{listing.kind === "forbidden" ? (
<p className="info-box">{t("Passkeys aren't available for this account. Ask your mail administrator if you need them.")}</p>
) : (
<div className="info-box row" style={{ gap: 8, alignItems: "center", flexWrap: "wrap" }}>
<span style={{ flex: 1 }}>{t("Couldn't load your passkeys.")} <span className="hint">{listing.message}</span></span>
<button className="btn btn-sm" onClick={() => { setListing(undefined); void reload(); }}>{t("Retry")}</button>
</div>
)}
</>
);
}
const add = async (e: React.FormEvent) => {
e.preventDefault();
@@ -457,7 +475,7 @@ export function Passkeys({ accountId, allowed, max }: { accountId: string; allow
<p className="hint" style={{ marginBottom: 12 }}>
{t("Sign in with your fingerprint, face or device PIN instead of your password. Passkeys work for signing in here; mail apps still use your password or an app password.")}
</p>
{rows === undefined ? <p className="hint">{t("Loading…")}</p> : rows.length > 0 && (
{listing === undefined ? <p className="hint">{t("Loading…")}</p> : rows && rows.length > 0 && (
<table className="sessions-table">
<thead><tr><th>{t("Name")}</th><th>{t("Added")}</th><th>{t("Last used")}</th><th /></tr></thead>
<tbody>
@@ -0,0 +1,79 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PasskeyListing } from "@/lib/passkeys";
const listPasskeys = vi.fn<(accountId: string) => Promise<PasskeyListing>>();
vi.mock("@/lib/passkeys", async (importActual) => ({
...(await importActual<typeof import("@/lib/passkeys")>()),
listPasskeys: (accountId: string) => listPasskeys(accountId),
}));
import { Passkeys } from "../SecuritySettings";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
/**
* #119: the section used to show "Loading…" and then vanish whenever the
* list didn't load, so a reader whose account wasn't allowed passkeys saw
* the feature appear and disappear with no reason. It hides itself only on
* a server without passkeys now, and otherwise says why.
*/
describe("Passkeys section", () => {
let host: HTMLDivElement;
let root: Root;
const render = async () => {
await act(async () => {
root.render(<Passkeys accountId="acc" />);
});
};
beforeEach(() => {
listPasskeys.mockReset();
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
});
it("stays hidden on a server without passkeys", async () => {
listPasskeys.mockResolvedValue({ kind: "none" });
await render();
expect(host.textContent).toBe("");
});
it("says when the account isn't allowed passkeys, and offers no add", async () => {
listPasskeys.mockResolvedValue({ kind: "forbidden" });
await render();
expect(host.textContent).toContain("Passkeys");
expect(host.textContent).toContain("aren't available for this account");
expect(host.querySelector("form")).toBeNull();
});
it("shows a failure with its reason, and tries again", async () => {
listPasskeys.mockResolvedValueOnce({ kind: "failed", message: "Bad Gateway" });
await render();
expect(host.textContent).toContain("Couldn't load your passkeys.");
expect(host.textContent).toContain("Bad Gateway");
listPasskeys.mockResolvedValueOnce({ kind: "list", rows: [] });
const retry = [...host.querySelectorAll("button")].find((b) => b.textContent === "Retry")!;
await act(async () => retry.click());
expect(listPasskeys).toHaveBeenCalledTimes(2);
expect(host.querySelector("form")).not.toBeNull();
});
it("lists the passkeys and offers the add", async () => {
listPasskeys.mockResolvedValue({
kind: "list",
rows: [{ id: "a", name: "Phone", state: "active", usable: true, backedUp: false, createdAt: null, lastUsedAt: null }],
});
await render();
expect(host.textContent).toContain("Phone");
expect(host.querySelector("form")).not.toBeNull();
});
});