mirror of
https://github.com/bulwarkmail/webmail.git
synced 2026-11-01 16:12:02 +00:00
"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.
48 lines
2.3 KiB
TypeScript
48 lines
2.3 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { logger } from '@/lib/logger';
|
|
import { redeemPairingCode } from '@/lib/auth/pairing-store';
|
|
import { PAIR_TOKEN_PROXY_PATH, buildRedeemBundle } from '@/lib/auth/pair-bundle';
|
|
import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
|
|
|
|
// Phone side of "Link mobile app". The app POSTs the code it scanned and gets
|
|
// the sign-in the desktop's step-up minted for it (see /api/auth/pair/create):
|
|
// an OAuth bundle, or for servers without OAuth login a username + (app)
|
|
// password. The code is the only credential required - it carries 256 bits,
|
|
// works once and expires within two minutes - so this route is intentionally
|
|
// unauthenticated (the scanning device has no webmail cookies).
|
|
//
|
|
// Failures say what happened, so the app can tell the user what to do:
|
|
// 400 invalid_code (never issued), 410 expired_code, 410 used_code.
|
|
|
|
const NO_STORE = { 'Cache-Control': 'no-store' };
|
|
|
|
export async function POST(request: NextRequest) {
|
|
// CSRF gate (GHSA-qvr9-m8cq-7wvg): cookies written here are SameSite=Lax,
|
|
// so a cross-site top-level POST would otherwise reach this handler.
|
|
const crossOrigin = rejectCrossOriginRequest(request);
|
|
if (crossOrigin) return crossOrigin;
|
|
try {
|
|
const body = await request.json().catch(() => ({}));
|
|
const pairingCode = body?.pairing_code;
|
|
if (typeof pairingCode !== 'string' || !/^[0-9a-f]{64}$/.test(pairingCode)) {
|
|
return NextResponse.json({ error: 'invalid_code' }, { status: 400, headers: NO_STORE });
|
|
}
|
|
|
|
const result = redeemPairingCode(pairingCode);
|
|
if (!result.ok) {
|
|
const status = result.reason === 'invalid' ? 400 : 410;
|
|
return NextResponse.json({ error: `${result.reason}_code` }, { status, headers: NO_STORE });
|
|
}
|
|
|
|
const bundle = buildRedeemBundle(result.grant, result.webmailBase);
|
|
logger.info('Pair code redeemed', {
|
|
flow: bundle.flow,
|
|
proxied: bundle.flow === 'oauth' && bundle.token_endpoint.endsWith(PAIR_TOKEN_PROXY_PATH),
|
|
});
|
|
return NextResponse.json(bundle, { headers: NO_STORE });
|
|
} catch (error) {
|
|
logger.error('Pair redeem error', { error: error instanceof Error ? error.message : 'Unknown error' });
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500, headers: NO_STORE });
|
|
}
|
|
}
|