Files
webmail/lib/auth/pair-attempts.ts
T
Linus Rath 1446fd39dc fix: link the mobile app from every account with a sign-in of its own
"Link Mobile App" only appeared for OAuth sessions, its step-up could
only go through the identity provider (which failed without an OAuth
client and bounced password+TOTP users to the provider's login page),
and it handed the phone the desktop's own refresh token. Revoking that
token on sign-out, or a rotating provider, signed the phone out too; a
confidential client stopped the phone at its first token expiry; and an
identity provider on another host was refused by the app.

The step-up now mints the phone's own grant:

- Password and password+TOTP accounts confirm the current password (and
  code) in the dialog. The server uses it once to get an OAuth grant
  from Stalwart's structured login for the app's own client, retries
  with the webmail's client when the server insists on a registered one,
  and falls back to an app password ("Bulwark mobile (paired <date>)")
  or, on servers that offer neither, the verified password. Failed
  attempts are limited per account so the webmail's address cannot be
  banned by guessing through it.
- SSO accounts keep the provider round trip, now with `offline_access`
  where offered; its fresh tokens become the phone's grant instead of
  being thrown away, and must belong to the account being paired.
- The account and server always come from the slot's verified session
  context, never from the request.

Grants live 5 minutes server-side, codes 2 minutes, both single use; the
store is pinned on `globalThis`. Redeem answers `invalid_code`,
`expired_code` or `used_code`, and the desktop polls a separate status
id to replace the QR with "Signed in on your phone". A phone whose
client is confidential, or whose provider is on another host, renews
through `/api/auth/pair/token` with a sealed refresh token, so current
app builds work unchanged. Signing out discards a pending grant but no
longer affects a paired phone.

The dialog shows for every account (not in Lite), with a copyable
sign-in link, a TOTP field when needed, and the app's own "Scan a
sign-in code" wording.
2026-09-27 04:16:18 +02:00

81 lines
2.7 KiB
TypeScript

// Failed password step-ups for "Link mobile app", per signed-in account.
//
// The step-up checks the typed password against the mail server from this
// server's address. Stalwart bans an address after too many failed logins
// (100 a day per IP or login name) - across the whole server - so a signed-in
// session must not be able to guess passwords through the webmail and get it
// banned for everyone. A handful of mistakes is plenty for a person.
//
// An attempt counts as a failure from the moment it starts, and is given back
// only once it turns out not to have been a wrong credential: otherwise
// parallel requests would all pass the check before the first one failed.
const MAX_FAILURES = 5;
const WINDOW_MS = 15 * 60 * 1000;
const STORE_KEY = '__bulwarkPairAttempts';
interface Entry {
failures: number;
windowStart: number;
}
function store(): Map<string, Entry> {
const g = globalThis as typeof globalThis & { [STORE_KEY]?: Map<string, Entry> };
if (!g[STORE_KEY]) g[STORE_KEY] = new Map();
return g[STORE_KEY];
}
function live(key: string, now: number): Entry | null {
const entry = store().get(key);
if (!entry) return null;
if (now - entry.windowStart >= WINDOW_MS) {
store().delete(key);
return null;
}
return entry;
}
export function isPairStepUpLocked(key: string, now = Date.now()): boolean {
return (live(key, now)?.failures ?? 0) >= MAX_FAILURES;
}
export function recordPairStepUpFailure(key: string, now = Date.now()): void {
const entry = live(key, now);
if (entry) entry.failures += 1;
else store().set(key, { failures: 1, windowStart: now });
// Bound the map: drop windows that ran out.
for (const [k, e] of store()) {
if (now - e.windowStart >= WINDOW_MS) store().delete(k);
}
}
/**
* Start a step-up: false when the account is locked out, otherwise the
* attempt is counted as a failure until {@link settlePairStepUp} says better.
*/
export function beginPairStepUp(key: string, now = Date.now()): boolean {
if (isPairStepUpLocked(key, now)) return false;
recordPairStepUpFailure(key, now);
return true;
}
/**
* Finish a step-up begun with {@link beginPairStepUp}: a success clears the
* count, a wrong credential keeps its failure, anything else (the server was
* unreachable, pairing is unavailable) gives the attempt back.
*/
export function settlePairStepUp(key: string, outcome: 'success' | 'wrong_credential' | 'other'): void {
if (outcome === 'success') {
clearPairStepUpFailures(key);
return;
}
if (outcome === 'other') {
const entry = store().get(key);
if (entry) entry.failures = Math.max(0, entry.failures - 1);
}
}
export function clearPairStepUpFailures(key: string): void {
store().delete(key);
}