Settings › Security: passkeys (#334) #116

Merged
jcoffey-dev merged 1 commits from feat/334-passkeys into main 2026-11-19 04:40:43 +00:00
13 changed files with 521 additions and 1 deletions

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
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" }));
import { addErrorMessage, listPasskeys, removePasskey, renamePasskey, startPasskey } from "@/lib/passkeys";
describe("passkeys (#334)", () => {
beforeEach(() => { call.mockReset(); });
it("lists the account's passkeys, newest first", async () => {
call.mockResolvedValue({
list: [
{ id: "a", name: "Phone", state: "active", usable: true, backedUp: true, createdAt: "2026-11-01T10:00:00Z", lastUsedAt: null },
{ id: "b", name: "Key", state: "active", usable: false, backedUp: false, createdAt: "2026-11-10T10:00:00Z", lastUsedAt: "2026-11-11T10:00:00Z" },
],
});
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" });
});
it("hides the section on a server without passkeys", async () => {
call.mockImplementation(async () => { throw new Error("unknownMethod"); });
expect(await listPasskeys("acc")).toBeNull();
});
it("returns the registration page of a new passkey", async () => {
call.mockResolvedValue({ created: { k: { id: "p", registrationUrl: "https://mail.example.org/passkey/register?t=x" } } });
await expect(startPasskey("acc", "Phone")).resolves.toBe("https://mail.example.org/passkey/register?t=x");
expect(call.mock.calls[0]![1]).toEqual({ accountId: "acc", create: { k: { accountId: "acc", name: "Phone" } } });
});
it("says why adding was refused", async () => {
call.mockResolvedValue({ notCreated: { k: { type: "overQuota" } } });
await expect(startPasskey("acc", "Phone")).rejects.toThrow(/as many passkeys/);
expect(addErrorMessage({ type: "forbidden" })).toMatch(/turned off/);
expect(addErrorMessage({ type: "invalidProperties", description: "Too long" })).toBe("Too long");
});
it("renames and removes, and reports a refusal", async () => {
call.mockResolvedValue({});
await renamePasskey("acc", "p", "Laptop");
expect(call.mock.calls[0]![1]).toEqual({ accountId: "acc", update: { p: { name: "Laptop" } } });
await removePasskey("acc", "p");
expect(call.mock.calls[1]![1]).toEqual({ accountId: "acc", destroy: ["p"] });
call.mockResolvedValue({ notDestroyed: { p: { type: "notFound" } } });
await expect(removePasskey("acc", "p")).rejects.toThrow();
});
});
+111
View File
@@ -0,0 +1,111 @@
import { client, INBUXA_CAP } from "@/jmap/client";
import { t } from "@/lib/i18n";
/**
* An account's passkeys, `inbuxa:Passkey` (inbuxa-server passkeys spec,
* PK-5 to PK-16). The browser part of registration runs on the mail server's
* own page (`registrationUrl`), because a passkey is bound to the server's
* name and this webmail runs on another one.
*/
export interface Passkey {
id: string;
name: string;
/** `pending` until the registration page has finished, then `active`. */
state: "pending" | "active";
/** False once the server's name changed after the passkey was added (PK-4). */
usable: boolean;
/** The authenticator said the key is synced, e.g. in a password manager. */
backedUp: boolean;
createdAt: string | null;
lastUsedAt: string | null;
}
/** Why adding a passkey failed, in words for the reader. */
export class PasskeyError extends Error {
constructor(public readonly type: string, message: string) {
super(message);
}
}
interface SetError { type: string; description?: string }
const PROPERTIES = ["id", "name", "state", "usable", "backedUp", "createdAt", "lastUsedAt"];
function parse(raw: Record<string, unknown>): Passkey {
return {
id: String(raw.id),
name: typeof raw.name === "string" ? raw.name : "",
state: raw.state === "pending" ? "pending" : "active",
usable: raw.usable === true,
backedUp: raw.backedUp === true,
createdAt: typeof raw.createdAt === "string" ? raw.createdAt : null,
lastUsedAt: typeof raw.lastUsedAt === "string" ? raw.lastUsedAt : null,
};
}
/**
* 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.
*/
export async function listPasskeys(accountId: string): Promise<Passkey[] | null> {
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;
}
}
/** Words for a refused create (PK-5). */
export function addErrorMessage(err: SetError): string {
switch (err.type) {
case "forbidden":
return t("Passkeys are turned off for this account.");
case "overQuota":
return t("This account has as many passkeys as it's allowed. Remove one to add another.");
default:
return err.description ?? t("Couldn't add the passkey.");
}
}
/**
* Starts registering a passkey: the server makes a pending record and
* returns the page that finishes it. The link is given out once and works
* for 10 minutes.
*/
export async function startPasskey(accountId: string, name: string): Promise<string> {
const res = await client.call<{
created?: Record<string, { id: string; registrationUrl?: string | null }> | null;
notCreated?: Record<string, SetError> | null;
}>("inbuxa:Passkey/set", { accountId, create: { k: { accountId, name } } }, [INBUXA_CAP]);
const failed = res.notCreated?.k;
if (failed) throw new PasskeyError(failed.type, addErrorMessage(failed));
const url = res.created?.k?.registrationUrl;
if (!url) throw new PasskeyError("serverFail", t("The server didn't return a page to add the passkey on."));
return url;
}
export async function renamePasskey(accountId: string, id: string, name: string): Promise<void> {
const res = await client.call<{ notUpdated?: Record<string, SetError> | null }>(
"inbuxa:Passkey/set",
{ accountId, update: { [id]: { name } } },
[INBUXA_CAP],
);
const failed = res.notUpdated?.[id];
if (failed) throw new PasskeyError(failed.type, failed.description ?? t("Couldn't rename the passkey."));
}
/** Removes a passkey. The server then ends every session of the account (PK-15). */
export async function removePasskey(accountId: string, id: string): Promise<void> {
const res = await client.call<{ notDestroyed?: Record<string, SetError> | null }>(
"inbuxa:Passkey/set",
{ accountId, destroy: [id] },
[INBUXA_CAP],
);
const failed = res.notDestroyed?.[id];
if (failed) throw new PasskeyError(failed.type, failed.description ?? t("Couldn't remove the passkey."));
}
+22
View File
@@ -1843,6 +1843,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "„{name}“ entfernen?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Sie können sich damit nicht mehr anmelden. Wenn Sie einen Passkey entfernen, werden Sie überall abgemeldet, auch hier.",
"Passkeys": "Passkeys",
"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.": "Melden Sie sich mit Fingerabdruck, Gesicht oder Geräte-PIN statt mit Ihrem Passwort an. Passkeys gelten für die Anmeldung hier; Mail-Apps verwenden weiterhin Ihr Passwort oder ein App-Passwort.",
"Added": "Hinzugefügt",
"Last used": "Zuletzt verwendet",
"not finished": "nicht abgeschlossen",
"needs re-adding": "neu hinzufügen",
"synced": "synchronisiert",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Ein Passkey mit „neu hinzufügen“ wurde für den alten Namen des Mailservers hinzugefügt. Fügen Sie einen neuen hinzu und entfernen Sie dann den alten.",
"New passkey name": "Name des neuen Passkeys",
"Phone or security key": "Telefon oder Sicherheitsschlüssel",
"Add a passkey": "Passkey hinzufügen",
"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.",
"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.",
"Couldn't rename the passkey.": "Der Passkey konnte nicht umbenannt werden.",
"Couldn't remove the passkey.": "Der Passkey konnte nicht entfernt werden.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1816,6 +1816,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "¿Quitar «{name}»?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Ya no podrá iniciar sesión con ella. Quitar una llave de acceso cierra su sesión en todas partes, también aquí.",
"Passkeys": "Llaves de acceso",
"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.": "Inicie sesión con su huella, su cara o el PIN del dispositivo en lugar de su contraseña. Las llaves de acceso sirven para iniciar sesión aquí; las apps de correo siguen usando su contraseña o una contraseña de aplicación.",
"Added": "Añadida",
"Last used": "Último uso",
"not finished": "sin terminar",
"needs re-adding": "hay que volver a añadirla",
"synced": "sincronizada",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Una llave de acceso marcada «hay que volver a añadirla» se añadió para el nombre anterior del servidor de correo. Añada una nueva y luego quite la anterior.",
"New passkey name": "Nombre de la nueva llave de acceso",
"Phone or security key": "Teléfono o llave de seguridad",
"Add a passkey": "Añadir una llave de acceso",
"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.",
"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.",
"Couldn't rename the passkey.": "No se pudo renombrar la llave de acceso.",
"Couldn't remove the passkey.": "No se pudo quitar la llave de acceso.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1821,6 +1821,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "Supprimer « {name} » ?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Vous ne pourrez plus vous connecter avec. Supprimer une clé d'accès vous déconnecte partout, ici compris.",
"Passkeys": "Clés d'accès",
"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.": "Connectez-vous avec votre empreinte, votre visage ou le code PIN de l'appareil au lieu de votre mot de passe. Les clés d'accès servent à vous connecter ici ; les applications de messagerie utilisent toujours votre mot de passe ou un mot de passe d'application.",
"Added": "Ajoutée",
"Last used": "Dernière utilisation",
"not finished": "non terminée",
"needs re-adding": "à ajouter de nouveau",
"synced": "synchronisée",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Une clé d'accès marquée « à ajouter de nouveau » a été ajoutée pour l'ancien nom du serveur de messagerie. Ajoutez-en une nouvelle, puis supprimez l'ancienne.",
"New passkey name": "Nom de la nouvelle clé d'accès",
"Phone or security key": "Téléphone ou clé de sécurité",
"Add a passkey": "Ajouter une clé d'accès",
"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.",
"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.",
"Couldn't rename the passkey.": "Impossible de renommer la clé d'accès.",
"Couldn't remove the passkey.": "Impossible de supprimer la clé d'accès.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1824,6 +1824,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "「{name}」を削除しますか?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "このパスキーではサインインできなくなります。パスキーを削除すると、ここを含むすべての場所でサインアウトされます。",
"Passkeys": "パスキー",
"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.": "パスワードの代わりに指紋、顔、またはデバイスの PIN でサインインします。パスキーはここでのサインインに使えます。メールアプリでは引き続きパスワードまたはアプリパスワードを使います。",
"Added": "追加日",
"Last used": "最終使用",
"not finished": "未完了",
"needs re-adding": "再登録が必要",
"synced": "同期済み",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "「再登録が必要」と表示されたパスキーは、メールサーバーの以前の名前で追加されたものです。新しいパスキーを追加してから、古いものを削除してください。",
"New passkey name": "新しいパスキーの名前",
"Phone or security key": "スマートフォンまたはセキュリティキー",
"Add a passkey": "パスキーを追加",
"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.": "このアカウントではパスキーが無効になっています。",
"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.": "サーバーからパスキー追加用のページが返されませんでした。",
"Couldn't rename the passkey.": "パスキーの名前を変更できませんでした。",
"Couldn't remove the passkey.": "パスキーを削除できませんでした。",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1816,6 +1816,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "‘{name}’ verwijderen?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "U kunt er niet meer mee inloggen. Een toegangssleutel verwijderen meldt u overal af, ook hier.",
"Passkeys": "Toegangssleutels",
"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.": "Log in met uw vingerafdruk, gezicht of apparaatpincode in plaats van uw wachtwoord. Toegangssleutels werken voor inloggen hier; mailapps gebruiken nog steeds uw wachtwoord of een app-wachtwoord.",
"Added": "Toegevoegd",
"Last used": "Laatst gebruikt",
"not finished": "niet voltooid",
"needs re-adding": "opnieuw toevoegen",
"synced": "gesynchroniseerd",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Een toegangssleutel met ‘opnieuw toevoegen’ is toegevoegd voor de oude naam van de mailserver. Voeg een nieuwe toe en verwijder daarna de oude.",
"New passkey name": "Naam van nieuwe toegangssleutel",
"Phone or security key": "Telefoon of beveiligingssleutel",
"Add a passkey": "Toegangssleutel toevoegen",
"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.",
"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.",
"Couldn't rename the passkey.": "Kon de toegangssleutel niet hernoemen.",
"Couldn't remove the passkey.": "Kon de toegangssleutel niet verwijderen.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1819,6 +1819,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "Remover “{name}”?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Você não poderá mais entrar com ela. Remover uma chave de acesso encerra sua sessão em todos os lugares, inclusive aqui.",
"Passkeys": "Chaves de acesso",
"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.": "Entre com sua digital, seu rosto ou o PIN do dispositivo em vez da senha. Chaves de acesso servem para entrar aqui; apps de e-mail continuam usando sua senha ou uma senha de app.",
"Added": "Adicionada",
"Last used": "Último uso",
"not finished": "não concluída",
"needs re-adding": "adicionar de novo",
"synced": "sincronizada",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Uma chave de acesso marcada como “adicionar de novo” foi adicionada para o nome antigo do servidor de e-mail. Adicione uma nova e depois remova a antiga.",
"New passkey name": "Nome da nova chave de acesso",
"Phone or security key": "Celular ou chave de segurança",
"Add a passkey": "Adicionar chave de acesso",
"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.",
"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.",
"Couldn't rename the passkey.": "Não foi possível renomear a chave de acesso.",
"Couldn't remove the passkey.": "Não foi possível remover a chave de acesso.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1818,6 +1818,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "Удалить «{name}»?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Вы больше не сможете входить с его помощью. Удаление ключа доступа завершает все ваши сеансы, включая этот.",
"Passkeys": "Ключи доступа",
"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.": "Входите по отпечатку пальца, лицу или PIN-коду устройства вместо пароля. Ключи доступа работают для входа здесь; почтовые приложения по-прежнему используют пароль или пароль приложения.",
"Added": "Добавлен",
"Last used": "Последнее использование",
"not finished": "не завершён",
"needs re-adding": "нужно добавить заново",
"synced": "синхронизирован",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Ключ доступа с пометкой «нужно добавить заново» был добавлен для прежнего имени почтового сервера. Добавьте новый, затем удалите старый.",
"New passkey name": "Имя нового ключа доступа",
"Phone or security key": "Телефон или ключ безопасности",
"Add a passkey": "Добавить ключ доступа",
"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.": "Ключи доступа отключены для этой учётной записи.",
"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.": "Сервер не вернул страницу для добавления ключа доступа.",
"Couldn't rename the passkey.": "Не удалось переименовать ключ доступа.",
"Couldn't remove the passkey.": "Не удалось удалить ключ доступа.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1694,6 +1694,28 @@ export const catalog: Catalog = {
"Sign out of all accounts": "Tüm hesaplardan çıkış yap",
"Shared mailbox:": "Paylaşılan posta kutusu:",
"New mail for {name}": "{name} için yeni posta",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "“{name}” kaldırılsın mı?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Artık bununla oturum açamazsınız. Bir geçiş anahtarını kaldırmak, burası dahil her yerde oturumunuzu kapatır.",
"Passkeys": "Geçiş anahtarları",
"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.": "Parolanız yerine parmak iziniz, yüzünüz veya cihaz PIN'inizle oturum açın. Geçiş anahtarları burada oturum açmak için çalışır; e-posta uygulamaları parolanızı veya bir uygulama parolasını kullanmaya devam eder.",
"Added": "Eklenme",
"Last used": "Son kullanım",
"not finished": "tamamlanmadı",
"needs re-adding": "yeniden eklenmeli",
"synced": "eşitlendi",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "“Yeniden eklenmeli” olarak işaretli bir geçiş anahtarı, posta sunucusunun eski adı için eklenmiş. Yeni bir tane ekleyin, sonra eskisini kaldırın.",
"New passkey name": "Yeni geçiş anahtarının adı",
"Phone or security key": "Telefon veya güvenlik anahtarı",
"Add a passkey": "Geçiş anahtarı ekle",
"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ı.",
"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.",
"Couldn't rename the passkey.": "Geçiş anahtarı yeniden adlandırılamadı.",
"Couldn't remove the passkey.": "Geçiş anahtarı kaldırılamadı.",
},
plurals: {
"({n} deleted first)": {
+22
View File
@@ -1812,6 +1812,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "Видалити «{name}»?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "Ви більше не зможете входити з ним. Видалення ключа доступу завершує всі ваші сеанси, зокрема цей.",
"Passkeys": "Ключі доступу",
"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.": "Входьте за відбитком пальця, обличчям або PIN-кодом пристрою замість пароля. Ключі доступу працюють для входу тут; поштові застосунки й далі використовують пароль або пароль застосунку.",
"Added": "Додано",
"Last used": "Останнє використання",
"not finished": "не завершено",
"needs re-adding": "треба додати знову",
"synced": "синхронізовано",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "Ключ доступу з позначкою «треба додати знову» було додано для попередньої назви поштового сервера. Додайте новий, а потім видаліть старий.",
"New passkey name": "Назва нового ключа доступу",
"Phone or security key": "Телефон або ключ безпеки",
"Add a passkey": "Додати ключ доступу",
"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.": "Ключі доступу вимкнено для цього облікового запису.",
"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.": "Сервер не повернув сторінку для додавання ключа доступу.",
"Couldn't rename the passkey.": "Не вдалося перейменувати ключ доступу.",
"Couldn't remove the passkey.": "Не вдалося видалити ключ доступу.",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+22
View File
@@ -1823,6 +1823,28 @@ export const catalog: Catalog = {
"POP3": "POP3",
"ManageSieve": "ManageSieve",
"SMTP": "SMTP",
// ── Passkeys (inbuxa #334) ──
"Remove “{name}”?": "删除“{name}”?",
"You can't sign in with it any more. Removing a passkey signs you out everywhere, here included.": "你将无法再用它登录。删除通行密钥会让你在所有地方退出登录,包括这里。",
"Passkeys": "通行密钥",
"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.": "使用指纹、面容或设备 PIN 代替密码登录。通行密钥可用于在此处登录;邮件应用仍使用你的密码或应用专用密码。",
"Added": "添加时间",
"Last used": "上次使用",
"not finished": "未完成",
"needs re-adding": "需要重新添加",
"synced": "已同步",
"A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.": "标记为“需要重新添加”的通行密钥是为邮件服务器的旧名称添加的。请添加一个新的,然后删除旧的。",
"New passkey name": "新通行密钥名称",
"Phone or security key": "手机或安全密钥",
"Add a passkey": "添加通行密钥",
"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.": "此账户已关闭通行密钥。",
"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.": "服务器没有返回用于添加通行密钥的页面。",
"Couldn't rename the passkey.": "无法重命名通行密钥。",
"Couldn't remove the passkey.": "无法删除通行密钥。",
},
plurals: {
// ── Administration: legacy mail protocols (INBUXA) ──────────────
+139 -1
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from "react";
import { useAppName } from "@/lib/brand";
import { Copy, KeyRound, ShieldCheck, Smartphone } from "lucide-react";
import { Copy, Fingerprint, KeyRound, ShieldCheck, Smartphone } from "lucide-react";
import { apiFetch, ApiError, legacyProtocolsOff, legacyProtocolsPartlyOff } from "@/jmap/client";
import { useSession } from "@/store/session";
import { formatFullDate } from "@/lib/format";
@@ -8,6 +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 { listPasskeys, removePasskey, renamePasskey, startPasskey, type Passkey } from "@/lib/passkeys";
interface SessionRow {
id: string;
@@ -85,6 +86,8 @@ export function SecuritySettings() {
</>
)}
{session?.ihasmail?.signIn === "oauth" && accountId && <Passkeys accountId={accountId} />}
<h2>{t("App passwords")}</h2>
{legacyProtocolsOff(session, accountId) && (
<p className="info-box mb-16">
@@ -368,6 +371,141 @@ 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,
* because a passkey is bound to the server's name, not this webmail's.
*/
export function Passkeys({ accountId }: { accountId: string }) {
const [rows, setRows] = useState<Passkey[] | null | undefined>(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]);
useEffect(() => { void reload(); }, [reload]);
if (rows === null) return null;
const add = async (e: React.FormEvent) => {
e.preventDefault();
// Opened before the request so the browser treats it as the click's window, not a pop-up.
const win = window.open("", "_blank");
setBusy(true);
try {
const url = await startPasskey(accountId, name.trim());
setName("");
if (win) {
win.opener = null;
win.location.href = url;
setWaiting(true);
const timer = window.setInterval(() => {
if (win.closed) {
window.clearInterval(timer);
setWaiting(false);
void reload();
}
}, 1000);
} else {
window.location.assign(url);
}
await reload();
} catch (err) {
win?.close();
toast.error((err as Error).message);
} finally {
setBusy(false);
}
};
const remove = async (row: Passkey) => {
const ok = await confirmDialog({
title: t("Remove “{name}”?", { name: row.name }),
message: t("You can't sign in with it any more. Removing a passkey signs you out everywhere, here included."),
confirmLabel: t("Remove"),
danger: true,
});
if (!ok) return;
try {
await removePasskey(accountId, row.id);
} catch (err) {
toast.error((err as Error).message);
return;
}
await signedOutBy("signed_out");
};
const rename = async () => {
if (!renaming) return;
try {
await renamePasskey(accountId, renaming.id, newName.trim());
setRenaming(null);
await reload();
} catch (err) {
toast.error((err as Error).message);
}
};
return (
<>
<h2>{t("Passkeys")}</h2>
<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 && (
<table className="sessions-table">
<thead><tr><th>{t("Name")}</th><th>{t("Added")}</th><th>{t("Last used")}</th><th /></tr></thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
<td>
<Fingerprint size={14} style={{ verticalAlign: "-2px", marginRight: 6 }} />{row.name}
{row.state === "pending" && <span className="badge" style={{ marginLeft: 6 }}>{t("not finished")}</span>}
{row.state === "active" && !row.usable && <span className="badge" style={{ marginLeft: 6 }}>{t("needs re-adding")}</span>}
{row.state === "active" && row.usable && row.backedUp && <span className="badge" style={{ marginLeft: 6 }}>{t("synced")}</span>}
</td>
<td>{row.createdAt ? formatFullDate(row.createdAt) : "—"}</td>
<td>{row.lastUsedAt ? formatFullDate(row.lastUsedAt) : t("Never")}</td>
<td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
{row.state === "active" && <button className="btn btn-sm btn-ghost" onClick={() => { setRenaming(row); setNewName(row.name); }}>{t("Rename")}</button>}
<button className="btn btn-sm btn-ghost" onClick={() => void remove(row)}>{t("Remove")}</button>
</td>
</tr>
))}
</tbody>
</table>
)}
{rows?.some((r) => r.state === "active" && !r.usable) && (
<p className="hint mt-8">{t("A passkey marked “needs re-adding” was added for the mail server's old name. Add a new one, then remove the old one.")}</p>
)}
<form onSubmit={add} className="row mt-16" style={{ gap: 8, alignItems: "flex-end", flexWrap: "wrap" }}>
<div className="field" style={{ marginBottom: 0, minWidth: 240 }}>
<label htmlFor="pk-name">{t("New passkey name")}</label>
<input id="pk-name" value={name} maxLength={64} onChange={(e) => setName(e.target.value)} placeholder={t("Phone or security key")} required />
</div>
<button className="btn" disabled={busy || !name.trim()}>{busy ? t("Opening…") : t("Add a passkey")}</button>
</form>
{waiting && <p className="hint mt-8">{t("Finish adding the passkey in the window that opened. The page there works for 10 minutes.")}</p>}
<Dialog open={Boolean(renaming)} onClose={() => setRenaming(null)} title={t("Rename passkey")} size="sm"
footer={<>
<button className="btn btn-ghost" onClick={() => setRenaming(null)}>{t("Cancel")}</button>
<button className="btn btn-primary" disabled={!newName.trim()} onClick={() => void rename()}>{t("Save")}</button>
</>}>
<div className="field">
<label htmlFor="pk-rename">{t("Name")}</label>
<input id="pk-rename" value={newName} maxLength={64} onChange={(e) => setNewName(e.target.value)} />
</div>
</Dialog>
</>
);
}
function CopyableSecret({ value }: { value: string }) {
return (
<div className="row" style={{ gap: 6, alignItems: "center" }}>