import { loadAccount } from './account.svelte.js';
import { ApiFailure, request } from './http.js';
import { createCredential, getAssertion, passkeysSupported, type CreationOptions, type RequestOptions } from './webauthn.js';
import type { Passkey } from '../settings-types.js';
// The last outcome of a passkey or authenticator action, for the security page to show; null when there is nothing new.
export const securityNotice = $state<{ text: string | null; failed: boolean }>({ text: null, failed: false });
let noticeTimer: ReturnType<typeof setTimeout> | undefined;
const notify = (text: string, failed = false) => {
securityNotice.text = text;
securityNotice.failed = failed;
clearTimeout(noticeTimer);
noticeTimer = setTimeout(() => (securityNotice.text = null), 8000);
};
const sentence = (err: unknown, fallback: string) =>
err instanceof ApiFailure && err.status < 500 ? `${err.message.charAt(0).toUpperCase()}${err.message.slice(1)}.` : fallback;
// The sign-in second step and passkey rename have no field of their own yet, so they ask in the browser's own dialog.
const ask = (message: string, value = '') => (typeof window === 'undefined' ? null : window.prompt(message, value));
const isRecoveryCode = (code: string) => !/^\d{6}$/.test(code.replace(/\s/g, ''));
// Recovery codes the server just issued, shown once on the security page until dismissed.
export const freshRecoveryCodes = $state<{ codes: string[] | null }>({ codes: null });
export const notifySecurity = notify;
// Resolves to null once the passkey is saved, or to the line that says why it was not.
export async function addPasskey(name?: string): Promise<string | null> {
if (!passkeysSupported()) return 'This browser cannot create passkeys.';
try {
const start = await request<{ challenge: string; options: CreationOptions }>('POST', '/api/me/passkeys/register/start');
const credential = await createCredential(start.options);
const done = await request<{ passkey: Passkey; recoveryCodes?: string[] }>('POST', '/api/me/passkeys/register/finish', {
challenge: start.challenge,
credential,
...(name ? { name } : {})
});
await loadAccount();
notify(`Added ${done.passkey.name}.`);
if (done.recoveryCodes) freshRecoveryCodes.codes = done.recoveryCodes;
return null;
} catch (err) {
if (err instanceof DOMException) {
if (err.name === 'InvalidStateError') return 'This device already holds a passkey for your account.';
if (err.name === 'NotAllowedError' || err.name === 'AbortError') return 'No passkey was added. The request was canceled or timed out.';
return 'Your browser could not create the passkey.';
}
return sentence(err, 'Could not add the passkey. Try again in a moment.');
}
}
export async function renamePasskey(id: string, name: string): Promise<void> {
try {
const renamed = await request<Passkey>('PATCH', `/api/me/passkeys/${id}`, { name });
await loadAccount();
notify(`Renamed to ${renamed.name}.`);
} catch (err) {
notify(sentence(err, 'Could not rename the passkey. Try again in a moment.'), true);
}
}
// For the page's command actions: asks for the new name and returns the line to show in place of the action.
export function askToRename(passkey: Passkey): string {
const name = ask(`A new name for ${passkey.name}`, passkey.name)?.trim();
if (!name || name === passkey.name) return `Kept the name ${passkey.name}`;
void renamePasskey(passkey.id, name);
return `Renaming to ${name}`;
}
export async function removePasskey(id: string): Promise<void> {
try {
await request('DELETE', `/api/me/passkeys/${id}`);
} catch (err) {
if (!(err instanceof ApiFailure && err.status === 404)) notify(sentence(err, 'Could not remove the passkey. Try again in a moment.'), true);
}
await loadAccount();
}
// With a login the browser is offered only that account's passkeys; without one it offers any passkey it holds for this
// site. Resolves to null once signed in, or to the line that says why not.
export async function signInWithPasskey(login: string): Promise<string | null> {
if (!passkeysSupported()) return 'This browser cannot use passkeys.';
try {
const start = await request<{ challenge: string; options: RequestOptions }>('POST', '/api/auth/passkey/start', login.trim() ? { login: login.trim() } : {});
const credential = await getAssertion(start.options);
await request('POST', '/api/auth/passkey/finish', { challenge: start.challenge, credential });
return null;
} catch (err) {
// Security keys usually hold no discoverable passkey, so the browser finds nothing to offer without the email.
if (err instanceof DOMException)
return login.trim() ? 'No passkey was used. The request was canceled or timed out.' : 'No passkey was used. If yours is on a security key, enter your email first.';
return sentence(err, 'Could not sign in with a passkey. Try again in a moment.');
}
}
export type AuthenticatorSetup = { secret: string; otpauthUrl: string; qrSvg: string };
// A fresh secret for the app to scan; it does nothing until a code from it is confirmed.
export async function startAuthenticator(): Promise<AuthenticatorSetup | string> {
try {
return await request<AuthenticatorSetup>('POST', '/api/me/totp/setup');
} catch (err) {
return sentence(err, 'Could not start the authenticator setup. Try again in a moment.');
}
}
// Resolves to null once the authenticator is on, or to the line that says why it is not.
export async function enableAuthenticator(code: string): Promise<string | null> {
const digits = code.replace(/\s/g, '');
if (!/^\d{6}$/.test(digits)) return 'Enter the 6-digit code your app shows.';
try {
const enabled = await request<{ recoveryCodes: string[] }>('POST', '/api/me/totp/enable', { code: digits });
freshRecoveryCodes.codes = enabled.recoveryCodes;
await loadAccount();
notify('The authenticator app is on. Sign-ins with a password now ask for its code.');
return null;
} catch (err) {
return sentence(err, 'Could not turn on the authenticator app. Try again in a moment.');
}
}
// Takes a current code or a recovery code. Resolves to null once the authenticator is off.
export async function disableAuthenticator(code: string): Promise<string | null> {
const trimmed = code.trim();
if (!trimmed) return 'Enter a code from your authenticator app or a recovery code.';
try {
await request('DELETE', '/api/me/totp', isRecoveryCode(trimmed) ? { recoveryCode: trimmed } : { code: trimmed.replace(/\s/g, '') });
await loadAccount();
notify('The authenticator app is off.');
return null;
} catch (err) {
return sentence(err, 'Could not turn off the authenticator app. Try again in a moment.');
}
}
export type SecondFactorChallenge = {
needsSecondFactor: true;
methods: ('totp' | 'passkey' | 'recovery')[];
challenge: string;
passkey?: RequestOptions;
};
export const needsSecondFactor = (body: unknown): body is SecondFactorChallenge =>
typeof body === 'object' && body !== null && 'needsSecondFactor' in body && body.needsSecondFactor === true;
// Finishes a sign-in that asked for a second step: a passkey first when the account has one, else (or when the
// passkey is dismissed) a code. Resolves to null once signed in, or to the reason it stopped.
export async function completeSecondFactor(start: SecondFactorChallenge): Promise<string | null> {
const send = (proof: Record<string, unknown>) => request('POST', '/api/auth/sign-in/second-factor', { challenge: start.challenge, ...proof });
if (start.passkey && passkeysSupported()) {
try {
await send({ passkey: await getAssertion(start.passkey) });
return null;
} catch (err) {
if (err instanceof ApiFailure && err.status !== 401) return sentence(err, 'Could not sign in. Try again in a moment.');
}
}
const codes = start.methods.includes('totp') || start.methods.includes('recovery');
if (!codes) return 'Your passkey did not sign you in. Try again.';
let message = start.methods.includes('totp')
? 'Enter the 6-digit code from your authenticator app, or a recovery code.'
: 'Enter one of your recovery codes.';
for (;;) {
const code = ask(message)?.trim();
if (!code) return 'Signing in needs your second step. Sign in again when you have it.';
try {
await send(isRecoveryCode(code) ? { recoveryCode: code } : { code: code.replace(/\s/g, '') });
return null;
} catch (err) {
if (err instanceof ApiFailure && err.message === 'that second factor is not valid') {
message = 'That code did not work. Enter the code your app shows now, or a recovery code.';
continue;
}
return sentence(err, 'Could not sign in. Try again in a moment.');
}
}
}