Files
webmail/app/api/auth/pair/token/route.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

104 lines
4.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { openPhoneRefreshToken, sealPhoneRefreshToken } from '@/lib/auth/pair-bundle';
import { getClientSecret } from '@/lib/oauth/token-exchange';
import { fetchPublicUrl } from '@/lib/security/url-guard';
import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
// Token endpoint for paired phones whose grant the phone cannot renew itself:
// the client is confidential (its secret stays on this server), or the
// provider's host is one current app builds refuse to talk to. The app posts
// the standard refresh grant here; we renew at the provider that minted the
// grant, with the secret, and hand back a re-sealed refresh token.
//
// Only refresh tokens this webmail sealed for a phone are accepted (see
// lib/auth/pair-bundle.ts), so the route cannot be used to renew arbitrary
// tokens with our client secret. No cookies are involved.
const UPSTREAM_TIMEOUT_MS = 10_000;
const NO_STORE = { 'Cache-Control': 'no-store', Pragma: 'no-cache' };
function oauthError(error: string, status: number) {
return NextResponse.json({ error }, { status, headers: NO_STORE });
}
export async function POST(request: NextRequest) {
const crossOrigin = rejectCrossOriginRequest(request);
if (crossOrigin) return crossOrigin;
let params: URLSearchParams;
try {
params = new URLSearchParams(await request.text());
} catch {
return oauthError('invalid_request', 400);
}
if (params.get('grant_type') !== 'refresh_token') {
return oauthError('unsupported_grant_type', 400);
}
const sealed = openPhoneRefreshToken(params.get('refresh_token') ?? '');
if (!sealed) {
return oauthError('invalid_grant', 400);
}
const upstreamParams = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: sealed.refreshToken,
client_id: sealed.clientId,
});
// The secret is the admin's, for the admin's servers only.
const secret = sealed.trusted ? getClientSecret(sealed.serverId) : '';
if (secret) upstreamParams.set('client_secret', secret);
let upstream: Response;
try {
const init = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: upstreamParams.toString(),
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
};
// The body carries the refresh token and the client secret: never follow
// a redirect with it. A user-chosen server goes through the
// rebinding-safe fetch (which never follows redirects either).
upstream = sealed.trusted
? await fetch(sealed.tokenEndpoint, { ...init, redirect: 'error' })
: (await fetchPublicUrl(sealed.tokenEndpoint, init)) as unknown as Response;
} catch (error) {
logger.warn('Pair token proxy: provider unreachable', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return oauthError('temporarily_unavailable', 503);
}
if (!upstream.ok) {
// 400/401/403: the grant is dead (expired, revoked, password changed) and
// the app signs the account out. Anything else is an outage it waits out.
const dead = upstream.status === 400 || upstream.status === 401 || upstream.status === 403;
logger.warn('Pair token proxy: refresh rejected', { status: upstream.status });
return oauthError(dead ? 'invalid_grant' : 'temporarily_unavailable', dead ? 400 : 503);
}
let tokens: { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown; token_type?: unknown };
try {
tokens = await upstream.json();
} catch {
return oauthError('temporarily_unavailable', 503);
}
if (typeof tokens.access_token !== 'string' || !tokens.access_token) {
return oauthError('temporarily_unavailable', 503);
}
const refreshToken = typeof tokens.refresh_token === 'string' && tokens.refresh_token
? tokens.refresh_token
: sealed.refreshToken;
return NextResponse.json(
{
access_token: tokens.access_token,
token_type: typeof tokens.token_type === 'string' ? tokens.token_type : 'Bearer',
...(typeof tokens.expires_in === 'number' ? { expires_in: tokens.expires_in } : {}),
refresh_token: sealPhoneRefreshToken({ ...sealed, refreshToken }),
},
{ headers: NO_STORE },
);
}