fix: keep a desktop sign-in in the browser's page until the user says yes

The hand-off parked a password before its question, for up to five
minutes, and on a shared computer another local user could ask for
someone's sign-in with a link of their own. Now nothing leaves the page
before the yes, and the instance has a switch for such machines.

- `/check` tests a password and keeps nothing, `/park` runs on the yes and
  hands over tokens wherever the server allows, a password as a last
  resort
- `/discard` and a timer take out what SSO has to park first, and a no
  revokes the refresh token, and the shared store's TTL is the real expiry
- `DESKTOP_BROWSER_SIGN_IN`, default on, closes the routes, the page's
  hand-off and the app's button; the question says which device asked
- tokens from a typed password stay a password account under the name
  typed (#1432)
- redeem refuses a server of the user's own when the device's rule says
  no
- the park budget is reserved before going upstream, and only failures
  count
- "Not now" ends the flow in the app at once, and the question names the
  account

`desktop-handoff-routes.test.ts` now tests the two-step flow against the
real budgets. `sso-start-route.test.ts`'s config mock answers the new
setting, and the SSO test's expected answer has the account in it.
This commit is contained in:
Linus Rath
2026-11-04 02:40:37 +01:00
parent 02a900ef07
commit ab21bf2df3
62 changed files with 1260 additions and 381 deletions
+3
View File
@@ -366,6 +366,9 @@ LOGIN_WEBSITE_URL=https://bulwarkmail.org
# that authenticate API tokens as Bearer tokens instead of passwords, such
# as Fastmail (JMAP_SERVER_URL=https://api.fastmail.com).
# LOGIN_SHOW_TOKEN_LOGIN=true
# The desktop app's "Sign in with your browser" through this login page. On by default.
# Turn it off on a terminal server: another user there could send a link asking for a sign-in.
# DESKTOP_BROWSER_SIGN_IN=false
#
# Show the "Remember me" box (default false). Without it every sign-in is
# remembered, provided SESSION_SECRET is set. The box also decides for SSO
+40 -11
View File
@@ -10,8 +10,8 @@ import { LITE_OAUTH_AVAILABLE, getLiteOAuthRedirectUri } from "@/lib/auth/lite-o
import { AlertCircle } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { useParams } from "next/navigation";
import { buildMobileHandoffUrl, desktopHandoffTarget, handoffTarget } from "@/lib/auth/mobile-handoff";
import { confirmMobileHandoffCodeUrl } from "@/lib/auth/mobile-handoff-client";
import { buildMobileHandoffUrl, desktopHandoffDeclineUrl, desktopHandoffPort, desktopHandoffTarget, handoffTarget } from "@/lib/auth/mobile-handoff";
import { confirmMobileHandoffCodeUrl, discardDesktopSignIn } from "@/lib/auth/mobile-handoff-client";
import { MobileHandoffConsent } from "@/components/auth/mobile-handoff-consent";
import { MailSkeleton } from "@/components/boot-skeleton/mail-skeleton";
import { useSkeletonLabels } from "@/components/boot-skeleton/use-skeleton-labels";
@@ -30,8 +30,21 @@ function OAuthCallbackInner() {
url: string | null;
resolveUrl?: () => Promise<string | null>;
username: string;
desktop?: boolean;
/** The desktop app's: what ends it, if the user says no or leaves. */
desktop?: { code: string; target: string; state: string };
} | null>(null);
// Unanswered, and the tab goes: the tokens the server parked go too. A yes has left this
// to the app, and "Not now" has already said.
const desktopPending = pendingHandoff?.desktop;
const desktopAnswered = useRef(false);
useEffect(() => {
if (!desktopPending) return;
const leave = () => {
if (!desktopAnswered.current) discardDesktopSignIn(desktopPending.code);
};
window.addEventListener("pagehide", leave);
return () => window.removeEventListener("pagehide", leave);
}, [desktopPending]);
// The authorization code is single-use. React's development double effect
// ran this twice: the second pass no longer saw the pairing re-auth flag
// (the first had removed it) and spent the code on the login flow instead.
@@ -185,15 +198,22 @@ function OAuthCallbackInner() {
sessionStorage.removeItem("mobile_redirect_uri");
sessionStorage.removeItem("mobile_state");
} catch { /* ignore */ }
const desktopTarget = desktopHandoffTarget(mobileRedirectUri);
setPendingHandoff({
url: null,
resolveUrl: () => confirmMobileHandoffCodeUrl({
target: mobileRedirectUri,
code: handoffCode,
state: handoffState,
}),
desktop: Boolean(desktopHandoffTarget(mobileRedirectUri)),
username: typeof data.server_url === "string" ? data.server_url : "",
resolveUrl: () => {
desktopAnswered.current = true;
return confirmMobileHandoffCodeUrl({
target: mobileRedirectUri,
code: handoffCode,
state: handoffState,
});
},
...(desktopTarget ? { desktop: { code: handoffCode, target: desktopTarget, state: handoffState } } : {}),
// Who is being handed over, where the server could say. Its address otherwise.
username: desktopTarget && typeof data.account === "string" && data.account
? data.account
: typeof data.server_url === "string" ? data.server_url : "",
});
return;
}
@@ -268,13 +288,22 @@ function OAuthCallbackInner() {
url={pendingHandoff.url}
resolveUrl={pendingHandoff.resolveUrl ?? null}
username={pendingHandoff.username}
desktop={pendingHandoff.desktop}
desktopPort={pendingHandoff.desktop ? desktopHandoffPort(pendingHandoff.desktop.target) : undefined}
onError={() => {
setPendingHandoff(null);
setError("token_exchange_failed");
}}
onCancel={() => {
const desktop = pendingHandoff.desktop;
setPendingHandoff(null);
if (desktop) {
// Ends the flow here and at the app. A plain login page from here would be a way
// to get a browser session nobody asked for.
desktopAnswered.current = true;
discardDesktopSignIn(desktop.code);
window.location.replace(desktopHandoffDeclineUrl(desktop.target, desktop.state));
return;
}
router.push(toRouterPath(`${getPathPrefix(params.locale as string)}/${params.locale}/login`));
}}
/>
@@ -32,6 +32,7 @@ vi.mock('@/hooks/use-config', () => ({
oauthEnabled: true,
oauthOnly: true,
oauthClientId: 'webmail',
desktopBrowserSignIn: true,
...configOverrides.value,
}),
}));
@@ -164,6 +165,14 @@ describe('sign-in with the browser, in the app', () => {
expect(screen.queryByTestId('desktop-browser-sign-in')).toBeNull();
}, 30_000);
it('is gone when the instance\'s admin turned it off', async () => {
configOverrides.value = { oauthEnabled: false, oauthOnly: false, desktopBrowserSignIn: false };
appBridge();
render(<LoginPage />);
await waitFor(() => expect(document.getElementById('password')).not.toBeNull(), { timeout: 10000 });
expect(screen.queryByTestId('desktop-browser-sign-in')).toBeNull();
}, 30_000);
it('is not there in a browser', async () => {
configOverrides.value = { oauthEnabled: false, oauthOnly: false };
render(<LoginPage />);
@@ -188,6 +197,31 @@ describe('sign-in with the browser, in the app', () => {
expect(await browserButton()).not.toBeDisabled();
}, 30_000);
it('a forced server says no to a server of the user\'s own, in what it asks the instance', async () => {
const snapshot = resolvePolicies({ ...EMPTY_POLICY_LAYERS, forcedMachine: { InstanceUrl: 'https://bulwark.example.org' } });
const controls = appBridge({ complete: () => ({ ok: true, code: 'c'.repeat(64), state: 'main-state' }) });
window.bulwarkDesktop = {
version: 1,
platform: 'win32',
mode: 'instance',
auth: { claim: () => controls },
policy: { get: () => snapshot, onChange: () => () => {} },
} as unknown as BulwarkDesktopBridge;
let sent: Record<string, unknown> | null = null;
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (url.includes('/api/auth/oauth/metadata')) return new Response(JSON.stringify(METADATA), { status: 200 });
if (url.includes('/api/auth/desktop-handoff/redeem')) {
sent = JSON.parse(String(init?.body));
return new Response(JSON.stringify({ error: 'blocked_by_policy' }), { status: 403 });
}
return new Response('{}', { status: 200 });
}));
render(<LoginPage />);
fireEvent.click(await browserButton());
await waitFor(() => expect(sent).toMatchObject({ custom_servers_allowed: false }));
}, 30_000);
it('asks the instance with the device\'s list, and a refusal is the policy\'s notice', async () => {
appBridge({ servers: ['https://mail.example.org'], complete: () => ({ ok: true, code: 'c'.repeat(64), state: 'main-state' }) });
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
@@ -195,7 +229,8 @@ describe('sign-in with the browser, in the app', () => {
fetched.push(url);
if (url.includes('/api/auth/oauth/metadata')) return new Response(JSON.stringify(METADATA), { status: 200 });
if (url.includes('/api/auth/desktop-handoff/redeem')) {
expect(JSON.parse(String(init?.body))).toMatchObject({ allowed_servers: ['https://mail.example.org'] });
// The same rule as the field for a server of one's own, on an instance with a server of its own.
expect(JSON.parse(String(init?.body))).toMatchObject({ allowed_servers: ['https://mail.example.org'], custom_servers_allowed: true });
return new Response(JSON.stringify({ error: 'blocked_by_policy' }), { status: 403 });
}
return new Response('{}', { status: 200 });
@@ -211,30 +246,98 @@ describe('the page the app opens in the browser', () => {
const CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';
const search = (entries: Record<string, string>) => new URLSearchParams(entries);
it('parks the password and leaves this browser signed out, after asking', async () => {
configOverrides.value = { oauthEnabled: false, oauthOnly: false };
function handoffPage(checkAnswer: () => Response = () => new Response('{"ok":true}', { status: 200 }), parkAnswer: () => Response = () => new Response(JSON.stringify({ code: 'a'.repeat(64) }), { status: 200 })) {
configOverrides.value = { oauthEnabled: false, oauthOnly: false, loginShowTotp: true };
params.value = search({ mobile_redirect_uri: 'http://127.0.0.1:51234/bulwark-desktop/callback', mobile_state: 's', mobile_code_challenge: CHALLENGE });
const bodies: Record<string, unknown>[] = [];
const parks: Record<string, unknown>[] = [];
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
fetched.push(url);
if (url.includes('/api/auth/desktop-handoff/check')) return checkAnswer();
if (url.includes('/api/auth/desktop-handoff/park')) {
bodies.push(JSON.parse(String(init?.body)));
return new Response(JSON.stringify({ code: 'a'.repeat(64) }), { status: 200 });
parks.push(JSON.parse(String(init?.body)));
return parkAnswer();
}
return new Response('{}', { status: 200 });
}));
return parks;
}
async function submit(totp?: string) {
render(<LoginPage />);
await screen.findByTestId('desktop-handoff-banner', {}, { timeout: 10000 });
fireEvent.change(document.getElementById('username')!, { target: { value: 'a@example.org' } });
fireEvent.change(document.getElementById('password')!, { target: { value: 'secret' } });
if (totp) {
fireEvent.click(screen.getByText('totp_toggle'));
fireEvent.change(await screen.findByLabelText('totp_label'), { target: { value: totp } });
}
fireEvent.submit(document.getElementById('password')!.closest('form')!);
}
it('holds the password until the yes: checked first, parked only then, with no browser session', async () => {
const parks = handoffPage();
await submit();
expect(await screen.findByText('consent_title')).toBeInTheDocument();
expect(bodies[0]).toMatchObject({ code_challenge: CHALLENGE, state: 's', username: 'a@example.org', password: 'secret' });
expect(parks).toEqual([]);
expect(fetched.filter((url) => url.includes('/desktop-handoff/check'))).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'consent_confirm' }));
await waitFor(() => expect(parks).toHaveLength(1));
expect(parks[0]).toMatchObject({ code_challenge: CHALLENGE, state: 's', username: 'a@example.org', password: 'secret' });
// No session anywhere: nothing went to the routes a browser sign-in writes cookies from.
expect(fetched.some((url) => /api\/auth\/(session|verify|token)/.test(url))).toBe(false);
}, 30_000);
it('"Not now" parks nothing', async () => {
const parks = handoffPage();
await submit();
fireEvent.click(await screen.findByRole('button', { name: 'consent_cancel' }));
await waitFor(() => expect(screen.queryByText('consent_title')).toBeNull());
expect(parks).toEqual([]);
}, 30_000);
it('a two-factor code is not spent before the yes, as it works once', async () => {
const parks = handoffPage();
await submit('123456');
expect(await screen.findByText('consent_title')).toBeInTheDocument();
expect(parks).toEqual([]);
expect(fetched.some((url) => url.includes('/desktop-handoff/check'))).toBe(false);
fireEvent.click(screen.getByRole('button', { name: 'consent_confirm' }));
await waitFor(() => expect(parks).toHaveLength(1));
expect(parks[0]).toMatchObject({ totp: '123456' });
}, 30_000);
it('a wrong password stays on the form, with no question', async () => {
const parks = handoffPage(() => new Response(JSON.stringify({ error: 'invalid_credentials' }), { status: 401 }));
await submit();
expect(await screen.findByText('error.invalid_credentials')).toBeInTheDocument();
expect(screen.queryByText('consent_title')).toBeNull();
expect(parks).toEqual([]);
}, 30_000);
it('too many attempts says so, and not that something broke', async () => {
handoffPage(() => new Response(JSON.stringify({ error: 'too_many_attempts' }), { status: 429 }));
await submit();
expect(await screen.findByText('too_many')).toBeInTheDocument();
expect(screen.queryByText('error.server_error')).toBeNull();
}, 30_000);
it('a failure at the yes goes back to the form and says why', async () => {
handoffPage(undefined, () => new Response(JSON.stringify({ error: 'invalid_credentials' }), { status: 401 }));
await submit('000000');
fireEvent.click(await screen.findByRole('button', { name: 'consent_confirm' }));
await waitFor(() => expect(screen.queryByText('consent_title')).toBeNull());
expect(await screen.findByText(/totp_invalid/)).toBeInTheDocument();
}, 30_000);
it('is the ordinary page when the instance\'s admin turned it off', async () => {
configOverrides.value = { oauthEnabled: false, oauthOnly: false, desktopBrowserSignIn: false };
params.value = search({ mobile_redirect_uri: 'http://127.0.0.1:51234/bulwark-desktop/callback', mobile_state: 's', mobile_code_challenge: CHALLENGE });
render(<LoginPage />);
await waitFor(() => expect(document.getElementById('password')).not.toBeNull(), { timeout: 10000 });
expect(screen.queryByTestId('desktop-handoff-banner')).toBeNull();
}, 30_000);
it('ignores a loopback target with no challenge, and is the ordinary page', async () => {
configOverrides.value = { oauthEnabled: false, oauthOnly: false };
params.value = search({ mobile_redirect_uri: 'http://127.0.0.1:51234/bulwark-desktop/callback', mobile_state: 's' });
+51 -29
View File
@@ -43,8 +43,8 @@ import {
} from "@/lib/auth/lite-oauth";
import { toAsciiDomain } from "@/lib/idn";
import { usePrefetchMailView } from "@/hooks/use-prefetch-mail-view";
import { buildMobileHandoffUrl, desktopHandoffTarget, mobileCodeChallenge, mobileHandoffTarget, signedInLoginAction } from "@/lib/auth/mobile-handoff";
import { confirmMobileHandoffCodeUrl, parkDesktopSignIn, requestMobileHandoffCodeUrl } from "@/lib/auth/mobile-handoff-client";
import { buildMobileHandoffCodeUrl, buildMobileHandoffUrl, desktopHandoffDeclineUrl, desktopHandoffPort, desktopHandoffTarget, mobileCodeChallenge, mobileHandoffTarget, signedInLoginAction } from "@/lib/auth/mobile-handoff";
import { checkDesktopSignIn, parkDesktopSignIn, requestMobileHandoffCodeUrl } from "@/lib/auth/mobile-handoff-client";
import { MobileHandoffConsent } from "@/components/auth/mobile-handoff-consent";
import { HelpLinks } from "@/components/layout/help-links";
import { LoginSkeleton } from "@/components/boot-skeleton/login-skeleton";
@@ -235,7 +235,8 @@ function LoginPageContent() {
const mobileChallenge = mobileCodeChallenge(rawMobileCodeChallenge);
// The desktop app's loopback listener is the other target, only ever with a code and a
// state, and the desktop build itself has no hand-off routes (lib/desktop/blocked-routes.ts).
const desktopTarget = !IS_DESKTOP_BUILD && mobileChallenge && rawMobileState
const { desktopBrowserSignIn: desktopSignInEnabled } = useConfig();
const desktopTarget = !IS_DESKTOP_BUILD && desktopSignInEnabled && mobileChallenge && rawMobileState
? desktopHandoffTarget(searchParams.get("mobile_redirect_uri"))
: "";
const isDesktopHandoff = Boolean(desktopTarget);
@@ -1058,6 +1059,7 @@ function LoginPageContent() {
const showBrowserSignInOutcome = (outcome: DesktopBrowserSignInOutcome) => {
setDesktopWaiting(false);
if (outcome.kind === "policy") setDesktopPolicyNotice(tDesktopPolicy("server_refused"));
else if (outcome.kind === "denied") setDesktopNotice(tBrowser("declined"));
else if (outcome.kind === "declined") setDesktopNotice(tDesktop("server_declined"));
else if (outcome.kind === "invalid") setDesktopNotice(tDesktop("server_invalid"));
else if (outcome.kind === "timeout") setDesktopNotice(tBrowser("timed_out"));
@@ -1127,6 +1129,8 @@ function LoginPageContent() {
remember: persistProviderSession,
rememberPassword: persistSession,
allowedServers: desktopPolicy.AllowedJmapServers.value,
// The same rule as the field for a server of one's own on this page.
customServersAllowed: customServerAllowedByDesktopPolicy(desktopPolicy) || !configuredServerUrl,
});
setDesktopWaiting(false);
if (redeemed === "ok") router.push('/');
@@ -1134,7 +1138,7 @@ function LoginPageContent() {
else setDesktopNotice(tBrowser("failed"));
};
const browserSignInShown = browserSignInAvailable();
const browserSignInShown = browserSignInAvailable() && desktopSignInEnabled;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -1143,35 +1147,51 @@ function LoginPageContent() {
// when the admin hasn't configured a server list.
const effectiveServerUrl = selectedServer?.url
|| (allowCustomJmapEndpoint ? jmapEndpoint : serverUrl);
// The desktop app opened this page in the user's browser. The password is checked and
// parked for the app, and this browser gets no session of its own out of it.
// The desktop app opened this page in the user's browser. Nothing leaves this page until
// the user says yes: the password is only checked, and a two-factor code can't be, as it
// works once. This browser gets no session of its own out of any of it.
if (isDesktopHandoff) {
useAuthStore.setState({ isLoading: true, error: null });
setHandoffError(null);
const prefix = getPathPrefix(params.locale as string);
const parked = await parkDesktopSignIn({
challenge: mobileChallenge,
state: mobileState,
serverUrl: effectiveServerUrl,
serverId: selectedServer?.id,
username: formData.username,
password: formData.password,
totp: totpCode || undefined,
redirectUri: `${window.location.origin}${prefix}/${params.locale}/auth/callback`,
});
if ("error" in parked) {
const failed = (reason: string) => {
useAuthStore.setState({
isLoading: false,
error: parked.error === "invalid_credentials" || parked.error === "totp_required" ? parked.error : "server_error",
error: reason === "invalid_credentials" || reason === "totp_required" ? reason : reason === "too_many_attempts" ? null : "server_error",
});
return;
setDesktopNotice(reason === "too_many_attempts" ? tBrowser("too_many") : null);
};
const { username, password } = formData;
const totp = totpCode || undefined;
useAuthStore.setState({ isLoading: true, error: null });
setHandoffError(null);
setDesktopNotice(null);
if (!totp) {
const checked = await checkDesktopSignIn({ serverUrl: effectiveServerUrl, serverId: selectedServer?.id, username, password });
if ("error" in checked) {
failed(checked.error);
return;
}
}
useAuthStore.setState({ isLoading: false });
const { code } = parked;
const prefix = getPathPrefix(params.locale as string);
setPendingHandoff({
url: null,
resolveUrl: () => confirmMobileHandoffCodeUrl({ target: mobileRedirectUri, code, state: mobileState }),
username: formData.username,
resolveUrl: async () => {
const parked = await parkDesktopSignIn({
challenge: mobileChallenge,
state: mobileState,
serverUrl: effectiveServerUrl,
serverId: selectedServer?.id,
username,
password,
totp,
redirectUri: `${window.location.origin}${prefix}/${params.locale}/auth/callback`,
});
if ("error" in parked) {
failed(parked.error);
return null;
}
return buildMobileHandoffCodeUrl(mobileRedirectUri, parked.code, mobileState);
},
username,
});
return;
}
@@ -1568,15 +1588,17 @@ function LoginPageContent() {
url={pendingHandoff?.url ?? null}
resolveUrl={pendingHandoff?.resolveUrl ?? null}
username={pendingHandoff?.username ?? ""}
desktop={isDesktopHandoff}
desktopPort={isDesktopHandoff ? desktopHandoffPort(desktopTarget) : undefined}
onCancel={() => {
setPendingHandoff(null);
// The app's sign-in stays open here, to try again or to leave.
if (!isDesktopHandoff) router.push('/');
// Ends the flow at the app, which isn't left waiting. Nothing was parked.
if (isDesktopHandoff) window.location.replace(desktopHandoffDeclineUrl(desktopTarget, mobileState));
else router.push('/');
}}
onError={() => {
setPendingHandoff(null);
setHandoffError("server_error");
// The desktop's answer has said what went wrong, on the form.
if (!isDesktopHandoff) setHandoffError("server_error");
}}
/>
{/* Theme toggle - top right, dropdown style; hidden while the theme policy locks the mode (#1280) */}
+1
View File
@@ -133,6 +133,7 @@ export function SettingsPage() {
</SettingsSection>
<SettingsSection id="login" title="Login page">
<ConfigToggleItem label="Desktop app: sign in with the browser" description="Lets the desktop app sign in through this login page in the user's browser, so their password manager works there. Turn off on a terminal server or any computer several people use at once: another user there can send a link that asks for someone's sign-in. The app's own form keeps working." configKey="desktopBrowserSignIn" value={currentValue('desktopBrowserSignIn') as boolean} source={config.desktopBrowserSignIn?.source} onChange={handleChange} onRevert={handleRevert} />
<ConfigToggleItem label="Show version" description="Show the webmail version in the login page footer. Turn off to keep the exact version hidden from visitors who are not signed in." configKey="loginShowVersion" value={currentValue('loginShowVersion') as boolean} source={config.loginShowVersion?.source} onChange={handleChange} onRevert={handleRevert} />
<ConfigToggleItem label="Show 2FA code option" term="two_factor" description="Show the &quot;I have a 2FA code&quot; toggle on the login form. Turn off when two-factor authentication is handled by an external identity provider. Accounts that require a code still get the field." configKey="loginShowTotp" value={currentValue('loginShowTotp') as boolean} source={config.loginShowTotp?.source} onChange={handleChange} onRevert={handleRevert} />
<ConfigToggleItem label="Show access token sign-in" term="access_token" description="Offer signing in with an access token instead of a password. For JMAP servers that authenticate API tokens as Bearer tokens, such as Fastmail, which accepts no passwords over JMAP." configKey="loginShowTokenLogin" value={currentValue('loginShowTokenLogin') as boolean} source={config.loginShowTokenLogin?.source} onChange={handleChange} onRevert={handleRevert} />
@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { resolveDesktopHandoffServer } from '@/lib/auth/desktop-handoff-server';
import { loginClientAddress } from '@/lib/auth/client-address';
import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable';
import { LOGIN_BUDGET_RETRY_AFTER_SECONDS, reserveLoginAttempt } from '@/lib/auth/verify-budget';
import { JmapAuthVerificationError, verifyJmapAuth } from '@/lib/auth/verify-jmap-auth';
import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
// The desktop app's sign-in, in the browser, before the question: is this password right?
// So a password manager never saves a wrong one, and the user isn't asked about a sign-in
// that can't work. Nothing is kept: the page holds the password until the user says yes.
const NO_STORE = { 'Cache-Control': 'no-store' };
function answer(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;
try {
const body = await request.json().catch(() => null);
const { server_url: serverUrl, username, password } = body ?? {};
if (
typeof serverUrl !== 'string' || !serverUrl || serverUrl.length > 2048
|| typeof username !== 'string' || !username || username.length > 512
|| typeof password !== 'string' || !password || password.length > 4096
) {
return answer('invalid_request', 400);
}
const server = await resolveDesktopHandoffServer(serverUrl, body?.server_id);
if ('refusal' in server) return answer(server.refusal.error, server.refusal.status);
const clientIp = loginClientAddress(request, server.upstream);
const refund = await reserveLoginAttempt(clientIp);
if (!refund) {
return NextResponse.json(
{ error: 'too_many_attempts' },
{ status: 429, headers: { ...NO_STORE, 'Retry-After': String(LOGIN_BUDGET_RETRY_AFTER_SECONDS) } },
);
}
try {
await verifyJmapAuth(server.upstream, `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, { trusted: server.trusted, clientIp });
await refund();
return NextResponse.json({ ok: true }, { headers: NO_STORE });
} catch (error) {
const status = error instanceof JmapAuthVerificationError ? error.upstreamStatus : undefined;
if (status === 401) return answer('invalid_credentials', 401);
await refund();
// Stalwart: the right password on an account with a second factor.
if (status === 402) return answer('totp_required', 401);
return answer('login_failed', 502);
}
} catch (error) {
if (isStoreUnavailable(error)) return storeUnavailableResponse(NO_STORE);
logger.error('Desktop hand-off check error', { error: error instanceof Error ? error.message : 'Unknown error' });
return answer('Internal server error', 500);
}
}
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { revokeParkedTokens } from '@/lib/auth/desktop-handoff-revoke';
import { discardDesktopHandoff, isHandoffCode } from '@/lib/auth/handoff-store';
import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable';
import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
// "Not now" on an SSO sign-in the desktop app asked for, or its tab closed. sso/complete
// has to park the tokens before the question can be shown, so this is what ends them: gone
// from the store, and revoked where the provider can. Only the page holding the code knows it.
const NO_STORE = { 'Cache-Control': 'no-store' };
export async function POST(request: NextRequest) {
const crossOrigin = rejectCrossOriginRequest(request);
if (crossOrigin) return crossOrigin;
try {
const body = await request.json().catch(() => null);
if (!isHandoffCode(body?.code)) return NextResponse.json({ error: 'invalid_code' }, { status: 400, headers: NO_STORE });
const parked = await discardDesktopHandoff(body.code);
if (parked) {
await revokeParkedTokens(parked);
logger.info('Desktop hand-off discarded', { flow: parked.flow });
}
return NextResponse.json({ ok: true }, { headers: NO_STORE });
} catch (error) {
if (isStoreUnavailable(error)) return storeUnavailableResponse(NO_STORE);
logger.error('Desktop hand-off discard error', { error: error instanceof Error ? error.message : 'Unknown error' });
return NextResponse.json({ error: 'Internal server error' }, { status: 500, headers: NO_STORE });
}
}
+69 -94
View File
@@ -1,28 +1,26 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { configManager } from '@/lib/admin/config-manager';
import { findServerById, findServerByUrl, parseJmapServers, resolveTrustedJmapUrl } from '@/lib/admin/jmap-servers';
import { loginClientAddress } from '@/lib/auth/client-address';
import { isHandoffCodeChallenge, reserveHandoffCreate, stashHandoff } from '@/lib/auth/handoff-store';
import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable';
import { resolveDesktopHandoffServer } from '@/lib/auth/desktop-handoff-server';
import { isHandoffCodeChallenge, reserveDesktopHandoffPark, stashHandoff } from '@/lib/auth/handoff-store';
import { stalwartPasswordLogin } from '@/lib/auth/stalwart-password-login';
import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable';
import { LOGIN_BUDGET_RETRY_AFTER_SECONDS, reserveLoginAttempt } from '@/lib/auth/verify-budget';
import { JmapAuthVerificationError, verifyJmapAuth } from '@/lib/auth/verify-jmap-auth';
import { IS_DESKTOP_BUILD } from '@/lib/desktop/flag';
import { readFileEnv } from '@/lib/read-file-env';
import { DEFAULT_CLIENT_ID } from '@/lib/oauth/token-exchange';
import { readFileEnv } from '@/lib/read-file-env';
import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
import { isPublicHttpUrl } from '@/lib/security/url-guard';
// The desktop app's "Sign in with your browser", on the browser's side. The app opened
// this instance's login page with a PKCE challenge. The page posts the password here
// instead of signing the browser in: the user came to sign the app in, and a session
// left in their default browser is something they didn't ask for. So nothing here
// writes a cookie. The password is checked against the mail server and parked, and the
// page takes the code to the app's loopback listener once the user has confirmed.
// The desktop app's "Sign in with your browser", on the browser's side, after the user
// said yes. /check tested the password; until now it has only been in the page. It goes
// no further than it has to: Stalwart's login turns it into tokens, and those are what's
// parked. A password is parked only for a server with no such login, for 60 seconds, for
// whoever holds the verifier. Nothing here writes a cookie, so this browser gets no session.
//
// With a two-factor code the code is spent here, so what's parked is the tokens it gets,
// not the password: the app could never present that code a second time.
// A two-factor code works once, so it's only spent here, after the yes. Tokens minted here
// are never dropped for budget reasons: the budget is reserved first, and a success gives
// it back, so an office behind one address can sign in as often as it likes.
const NO_STORE = { 'Cache-Control': 'no-store' };
@@ -30,12 +28,13 @@ function bounded(value: unknown, max: number): value is string {
return typeof value === 'string' && value.length > 0 && value.length <= max;
}
function answer(error: string, status: number) {
return NextResponse.json({ error }, { status, headers: NO_STORE });
function answer(error: string, status: number, headers: Record<string, string> = NO_STORE) {
return NextResponse.json({ error }, { status, headers });
}
const tooMany = () => answer('too_many_attempts', 429, { ...NO_STORE, 'Retry-After': String(LOGIN_BUDGET_RETRY_AFTER_SECONDS) });
export async function POST(request: NextRequest) {
if (IS_DESKTOP_BUILD) return answer('Not found', 404);
const crossOrigin = rejectCrossOriginRequest(request);
if (crossOrigin) return crossOrigin;
try {
@@ -43,7 +42,6 @@ export async function POST(request: NextRequest) {
const challenge = body?.code_challenge;
const state = typeof body?.state === 'string' ? body.state : '';
const totp = typeof body?.totp === 'string' && body.totp ? body.totp : undefined;
const requestedServerId = typeof body?.server_id === 'string' && body.server_id ? body.server_id : null;
if (
!isHandoffCodeChallenge(challenge)
|| !state
@@ -56,101 +54,78 @@ export async function POST(request: NextRequest) {
return answer('invalid_request', 400);
}
await configManager.ensureLoaded();
if (configManager.get<boolean>('oauthEnabled', false) && configManager.get<boolean>('oauthOnly', false)) {
return answer('oauth_only', 403);
}
// The same pinning as the sign-in routes.
const serverUrl: string = body.server_url;
// This route is the browser's. It has no business with the device's policy.
const configured =
configManager.get<string>('jmapServerUrl', '') || process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL || '';
const list = parseJmapServers(configManager.get<unknown>('jmapServers', []));
const allowCustom = configManager.get<boolean>('allowCustomJmapEndpoint', false);
const entry = findServerById(list, requestedServerId) || findServerByUrl(list, serverUrl);
// What's checked is what's parked: the app signs in to this one, whatever the body said.
let resolved: string;
let trusted = true;
if (entry) {
resolved = entry.url;
} else {
const pinned = resolveTrustedJmapUrl(serverUrl, configured, list);
if (pinned) {
resolved = pinned;
} else if (allowCustom && (await isPublicHttpUrl(serverUrl))) {
resolved = serverUrl;
trusted = false;
} else {
return answer('invalid_server_url', 400);
}
}
const upstream = resolved.replace(/\/+$/, '');
const server = await resolveDesktopHandoffServer(body.server_url, body.server_id);
if ('refusal' in server) return answer(server.refusal.error, server.refusal.status);
const { entry, resolved, upstream, trusted, custom } = server;
const clientIp = loginClientAddress(request, upstream);
const refund = await reserveLoginAttempt(clientIp);
if (!refund) {
return NextResponse.json(
{ error: 'too_many_attempts' },
{ status: 429, headers: { ...NO_STORE, 'Retry-After': String(LOGIN_BUDGET_RETRY_AFTER_SECONDS) } },
);
}
// Before anything goes upstream, so a code is never spent on a sign-in that can't finish.
const refundPark = await reserveDesktopHandoffPark(clientIp);
if (!refundPark) return tooMany();
const refundLogin = await reserveLoginAttempt(clientIp);
if (!refundLogin) return tooMany();
const configuredClientId =
entry?.oauth?.clientId || configManager.get<string>('oauthClientId', '') || process.env.OAUTH_CLIENT_ID;
const clientSecret =
entry?.oauth?.clientSecret
|| configManager.get<string>('oauthClientSecret', '')
|| process.env.OAUTH_CLIENT_SECRET
|| readFileEnv(process.env.OAUTH_CLIENT_SECRET_FILE)
|| '';
const redirectUri = typeof body?.redirect_uri === 'string' && /^https?:\/\//.test(body.redirect_uri) ? body.redirect_uri : upstream;
const login = await stalwartPasswordLogin({
serverUrl: upstream,
username: body.username,
password: body.password,
totp,
clientId: configuredClientId || DEFAULT_CLIENT_ID,
clientSecret,
redirectUri,
trusted,
clientIp,
registerUnknownClient: !configuredClientId,
});
let parked: Parameters<typeof stashHandoff>[0];
if (totp) {
const configuredClientId =
entry?.oauth?.clientId || configManager.get<string>('oauthClientId', '') || process.env.OAUTH_CLIENT_ID;
const clientSecret =
entry?.oauth?.clientSecret
|| configManager.get<string>('oauthClientSecret', '')
|| process.env.OAUTH_CLIENT_SECRET
|| readFileEnv(process.env.OAUTH_CLIENT_SECRET_FILE)
|| '';
const redirectUri = typeof body?.redirect_uri === 'string' && /^https?:\/\//.test(body.redirect_uri) ? body.redirect_uri : upstream;
const result = await stalwartPasswordLogin({
serverUrl: upstream,
username: body.username,
password: body.password,
totp,
clientId: configuredClientId || DEFAULT_CLIENT_ID,
clientSecret,
redirectUri,
trusted,
clientIp,
registerUnknownClient: !configuredClientId,
});
if (result.ok || result.error !== 'invalid_credentials') await refund();
if (!result.ok) {
if (result.error === 'invalid_credentials') return answer('invalid_credentials', 401);
if (result.error === 'totp_required') return answer('totp_required', 401);
return answer('login_failed', 502);
}
if (login.ok) {
parked = {
flow: 'desktop-tokens',
server_url: resolved,
server_id: entry?.id ?? null,
access_token: result.tokens.access_token,
refresh_token: result.tokens.refresh_token,
expires_in: result.tokens.expires_in ?? 3600,
custom,
password_login: true,
username: body.username,
access_token: login.tokens.access_token,
refresh_token: login.tokens.refresh_token,
expires_in: login.tokens.expires_in ?? 3600,
signed_in_at: Date.now(),
};
await refundLogin();
} else if (login.error === 'invalid_credentials') {
return answer('invalid_credentials', 401);
} else if (login.error === 'totp_required') {
await refundLogin();
return answer('totp_required', 401);
} else if (totp) {
await refundLogin();
return answer('login_failed', 502);
} else {
// The last resort: a server with no token login, or one that won't give this client any.
try {
await verifyJmapAuth(upstream, `Basic ${Buffer.from(`${body.username}:${body.password}`).toString('base64')}`, { trusted, clientIp });
await refund();
await refundLogin();
} catch (error) {
const status = error instanceof JmapAuthVerificationError ? error.upstreamStatus : undefined;
if (status === 401) return answer('invalid_credentials', 401);
await refund();
// Stalwart: the right password on an account with a second factor.
if (status === 402) return answer('totp_required', 401);
return answer('login_failed', 502);
await refundLogin();
return status === 402 ? answer('totp_required', 401) : answer('login_failed', 502);
}
parked = { flow: 'desktop-password', server_url: resolved, server_id: entry?.id ?? null, username: body.username, password: body.password };
parked = { flow: 'desktop-password', server_url: resolved, server_id: entry?.id ?? null, custom, username: body.username, password: body.password };
}
if (!(await reserveHandoffCreate(clientIp))) return answer('too_many_requests', 429);
const code = await stashHandoff(parked, { challenge, state, awaitConfirm: true });
const code = await stashHandoff(parked, { challenge, state });
await refundPark();
logger.info('Desktop hand-off parked', { flow: parked.flow });
return NextResponse.json({ code }, { headers: NO_STORE });
} catch (error) {
+14 -4
View File
@@ -3,6 +3,9 @@ import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { MAX_ACCOUNT_SLOTS } from '@/lib/account-utils';
import { loginClientAddress } from '@/lib/auth/client-address';
import { desktopHandoffEnabled } from '@/lib/auth/desktop-handoff-server';
import { revokeParkedTokens } from '@/lib/auth/desktop-handoff-revoke';
import { configManager } from '@/lib/admin/config-manager';
import { isHandoffCode, isHandoffCodeVerifier, redeemHandoff, reserveHandoffRedeem } from '@/lib/auth/handoff-store';
import { writeSignInStamp } from '@/lib/auth/session-age';
import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable';
@@ -19,9 +22,10 @@ import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
// challenge it opened the browser with. Same origin as the page, so an instance's cookies
// set here work under SameSite=Strict. Every attempt spends the code.
//
// The device's own list of servers is the page's to send: only it knows the OS policy,
// and the browser the user signed in with knows nothing of it. A refused server gets
// nothing written.
// The device's rules are the page's to send: only it knows the OS policy, and the browser
// the user signed in with knows nothing of it. That's its list of servers, and whether it
// may use a server of the user's own. A refused server gets nothing written, and a token
// minted for it is revoked.
const NO_STORE = { 'Cache-Control': 'no-store' };
@@ -33,6 +37,8 @@ export async function POST(request: NextRequest) {
if (IS_DESKTOP_BUILD) return answer('Not found', 404);
const crossOrigin = rejectCrossOriginRequest(request);
if (crossOrigin) return crossOrigin;
await configManager.ensureLoaded();
if (!desktopHandoffEnabled()) return answer('disabled', 403);
let refund: BudgetRefund | null = null;
try {
refund = await reserveHandoffRedeem(loginClientAddress(request));
@@ -58,7 +64,10 @@ export async function POST(request: NextRequest) {
const parked = result.bundle;
// A code the mobile path parked isn't one of ours.
if (parked.flow !== 'desktop-password' && parked.flow !== 'desktop-tokens') return answer('invalid_code', 400);
if (!jmapServerAllowed(allowedServers, parked.server_url)) return answer('blocked_by_policy', 403, { code: 'blocked_by_policy' });
if (!jmapServerAllowed(allowedServers, parked.server_url) || (parked.custom && body?.custom_servers_allowed !== true)) {
await revokeParkedTokens(parked);
return answer('blocked_by_policy', 403, { code: 'blocked_by_policy' });
}
await refund();
logger.info('Desktop hand-off redeemed', { flow: parked.flow });
@@ -86,6 +95,7 @@ export async function POST(request: NextRequest) {
{
flow: 'tokens',
server_url: parked.server_url,
...(parked.password_login && parked.username ? { password_login: true, username: parked.username } : {}),
access_token: parked.access_token,
expires_in: parked.expires_in,
signed_in_at: parked.signed_in_at,
+28
View File
@@ -36,6 +36,32 @@ function webmailBaseFromCallback(redirectUri: string): string | null {
}
}
/**
* Who just signed in, for the question the desktop app's hand-off asks: the id token says, as
* it came straight from the provider, and otherwise the mail server's session does.
*/
async function accountName(serverUrl: string, accessToken: string, idToken: string | undefined): Promise<string> {
try {
const claims = JSON.parse(Buffer.from((idToken ?? '').split('.')[1] ?? '', 'base64url').toString('utf8')) as Record<string, unknown>;
for (const claim of ['email', 'preferred_username', 'name']) {
if (typeof claims[claim] === 'string' && claims[claim]) return claims[claim] as string;
}
} catch {
// Not a JWT, or none: the server can say.
}
try {
const session = await fetch(`${serverUrl.replace(/\/+$/, '')}/.well-known/jmap`, {
headers: { Authorization: `Bearer ${accessToken}` },
redirect: 'error',
signal: AbortSignal.timeout(5000),
});
const body = (await session.json()) as { username?: unknown };
return typeof body.username === 'string' ? body.username : '';
} catch {
return '';
}
}
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.
@@ -158,6 +184,7 @@ export async function POST(request: NextRequest) {
flow: 'desktop-tokens',
server_url: serverUrl,
server_id: pendingServerId,
custom: false,
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
id_token: tokens.id_token,
@@ -168,6 +195,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json({
mobile_handoff_code: handoffCode,
server_url: serverUrl,
account: await accountName(serverUrl, tokens.access_token, tokens.id_token),
mobile_redirect_uri: mobileRedirectUri,
mobile_state: mobileState,
});
+5
View File
@@ -13,6 +13,7 @@ import { hasSessionSecret } from '@/lib/auth/session-secret';
import { configManager } from '@/lib/admin/config-manager';
import { rejectCrossOriginRequest } from '@/lib/security/same-origin';
import { desktopHandoffTarget, isMobileCodeChallenge, mobileHandoffTarget } from '@/lib/auth/mobile-handoff';
import { desktopHandoffEnabled } from '@/lib/auth/desktop-handoff-server';
const SSO_PENDING_COOKIE = 'sso_pending';
const SSO_PENDING_MAX_AGE = 300; // 5 minutes
@@ -81,6 +82,10 @@ export async function POST(request: NextRequest) {
if (mobileRedirectUri && desktopHandoffTarget(mobileRedirectUri) && !isMobileCodeChallenge(rawMobileCodeChallenge)) {
return NextResponse.json({ error: 'Invalid mobile_code_challenge' }, { status: 400 });
}
// The admin turned the desktop app's sign-in off here (a terminal server, say).
if (mobileRedirectUri && desktopHandoffTarget(mobileRedirectUri) && !desktopHandoffEnabled()) {
return NextResponse.json({ error: 'disabled' }, { status: 403 });
}
// An app build that sends a PKCE challenge gets a one-time code instead
// of the tokens (lib/auth/handoff-store.ts). A malformed one is refused
// rather than ignored, which would hand the tokens over in the link.
+1
View File
@@ -89,6 +89,7 @@ export async function GET(request: NextRequest) {
loginShowSubtitle: configManager.get<boolean>('loginShowSubtitle', true),
loginShowTotp: configManager.get<boolean>('loginShowTotp', true),
loginShowTokenLogin: configManager.get<boolean>('loginShowTokenLogin', false),
desktopBrowserSignIn: configManager.get<boolean>('desktopBrowserSignIn', true),
loginShowRememberMe: configManager.get<boolean>('loginShowRememberMe', false),
loginShowVersion: configManager.get<boolean>('loginShowVersion', true),
demoMode: configManager.get<boolean>('demoMode', false),
+5 -4
View File
@@ -19,8 +19,8 @@ interface MobileHandoffConsentProps {
onCancel: () => void;
/** `resolveUrl` returned null: nothing was handed over. */
onError?: () => void;
/** The desktop app on this computer, not the phone's app. */
desktop?: boolean;
/** The desktop app, not the phone's: the port its listener asked from. */
desktopPort?: string;
}
/**
@@ -31,7 +31,8 @@ interface MobileHandoffConsentProps {
* `bulwarkmobile` scheme on the device receives whatever is handed over
* (lib/auth/mobile-handoff.ts). Nothing leaves without this confirmation.
*/
export function MobileHandoffConsent({ url, resolveUrl, username, onCancel, onError, desktop }: MobileHandoffConsentProps) {
export function MobileHandoffConsent({ url, resolveUrl, username, onCancel, onError, desktopPort }: MobileHandoffConsentProps) {
const desktop = Boolean(desktopPort);
const t = useTranslations("login");
const tDesktop = useTranslations("desktop_browser_sign_in");
// The dialog closes itself right after confirming; while the code is being
@@ -63,7 +64,7 @@ export function MobileHandoffConsent({ url, resolveUrl, username, onCancel, onEr
if (url) window.location.replace(url);
}}
title={desktop ? tDesktop("consent_title") : t("mobile_handoff.title")}
message={desktop ? tDesktop("consent_description", { username }) : t("mobile_handoff.description", { username })}
message={desktop ? tDesktop("consent_description", { username, port: desktopPort ?? "" }) : t("mobile_handoff.description", { username })}
confirmText={desktop ? tDesktop("consent_confirm") : t("mobile_handoff.confirm")}
cancelText={desktop ? tDesktop("consent_cancel") : t("mobile_handoff.cancel")}
/>
+4
View File
@@ -40,6 +40,7 @@ export interface ConfigData {
loginShowSubtitle: boolean;
loginShowTotp: boolean;
loginShowTokenLogin: boolean;
desktopBrowserSignIn: boolean;
loginShowRememberMe: boolean;
loginShowVersion: boolean;
demoMode: boolean;
@@ -199,6 +200,7 @@ export function useConfig(): AppConfig {
loginShowSubtitle: configCache?.loginShowSubtitle ?? true,
loginShowTotp: configCache?.loginShowTotp ?? true,
loginShowTokenLogin: configCache?.loginShowTokenLogin ?? false,
desktopBrowserSignIn: configCache?.desktopBrowserSignIn ?? true,
loginShowRememberMe: configCache?.loginShowRememberMe ?? false,
loginShowVersion: configCache?.loginShowVersion ?? true,
demoMode: configCache?.demoMode || false,
@@ -252,6 +254,7 @@ export function useConfig(): AppConfig {
loginShowSubtitle: configCache.loginShowSubtitle,
loginShowTotp: configCache.loginShowTotp,
loginShowTokenLogin: configCache.loginShowTokenLogin,
desktopBrowserSignIn: configCache.desktopBrowserSignIn,
loginShowRememberMe: configCache.loginShowRememberMe,
loginShowVersion: configCache.loginShowVersion,
demoMode: configCache.demoMode,
@@ -306,6 +309,7 @@ export function useConfig(): AppConfig {
loginShowSubtitle: data.loginShowSubtitle,
loginShowTotp: data.loginShowTotp,
loginShowTokenLogin: data.loginShowTokenLogin,
desktopBrowserSignIn: data.desktopBrowserSignIn,
loginShowRememberMe: data.loginShowRememberMe,
loginShowVersion: data.loginShowVersion,
demoMode: data.demoMode,
+270 -123
View File
@@ -3,8 +3,8 @@ import { createHash } from 'crypto';
import { NextRequest } from 'next/server';
/**
* The desktop app's sign-in on an instance: what the browser parks, and what the app's
* own page gets for the code. The real store and routes, with the mail server faked.
* The desktop app's sign-in on an instance: what the browser checks and parks, and what the
* app's own page gets for the code. The real store, budgets and routes, with the mail server faked.
*/
const cookieJar = vi.hoisted(() => new Map<string, { value: string; options?: Record<string, unknown> }>());
@@ -47,32 +47,35 @@ vi.mock('@/lib/auth/verify-budget', async (original) => ({
reserveLoginAttempt,
}));
const discoverOAuth = vi.hoisted(() => vi.fn());
vi.mock('@/lib/oauth/discovery', () => ({ discoverOAuth }));
vi.mock('@/lib/logger', () => ({ logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() } }));
// This file parks more sign-ins than one client may in a quarter of an hour.
vi.mock('@/lib/auth/handoff-store', async (original) => ({
...(await original<object>()),
reserveHandoffCreate: async () => true,
reserveHandoffRedeem: async () => async () => {},
}));
const { POST: check } = await import('@/app/api/auth/desktop-handoff/check/route');
const { POST: park } = await import('@/app/api/auth/desktop-handoff/park/route');
const { POST: redeem } = await import('@/app/api/auth/desktop-handoff/redeem/route');
const { POST: discard } = await import('@/app/api/auth/desktop-handoff/discard/route');
const { POST: mobileRedeem } = await import('@/app/api/auth/handoff/redeem/route');
const { JmapAuthVerificationError } = await import('@/lib/auth/verify-jmap-auth');
const { confirmHandoff, resetHandoffStoreForTests, stashHandoff } = await import('@/lib/auth/handoff-store');
const { desktopHandoffTarget, mobileHandoffTarget } = await import('@/lib/auth/mobile-handoff');
const { HANDOFF_CONFIRM_TTL_MS, HANDOFF_TTL_MS, resetHandoffStoreForTests, stashHandoff } = await import('@/lib/auth/handoff-store');
const { desktopHandoffDeclineUrl, desktopHandoffPort, desktopHandoffTarget, mobileHandoffTarget } = await import('@/lib/auth/mobile-handoff');
const { isDesktopBlockedRoute } = await import('@/lib/desktop/blocked-routes');
const ORIGIN = 'https://bulwark.example';
const VERIFIER = 'v'.repeat(64);
const CHALLENGE = createHash('sha256').update(VERIFIER, 'ascii').digest('base64url');
const SERVER = 'https://mail.example';
const TOKENS = { ok: true, tokens: { access_token: 'access', refresh_token: 'refresh', expires_in: 3600 }, tokenEndpoint: `${SERVER}/auth/token`, clientId: 'x' };
/** A client of its own per test, so the budgets don't carry over: the real ones, unmocked. */
let clientAddress = '';
let nextClient = 1;
function post(path: string, body: unknown, origin = ORIGIN) {
return new NextRequest(`${ORIGIN}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: origin, Host: 'bulwark.example' },
headers: { 'Content-Type': 'application/json', Origin: origin, Host: 'bulwark.example', 'x-forwarded-for': clientAddress },
body: JSON.stringify(body),
});
}
@@ -85,30 +88,47 @@ const parkBody = (extra: Record<string, unknown> = {}) => ({
password: 'secret',
...extra,
});
const checkBody = (extra: Record<string, unknown> = {}) => ({ server_url: SERVER, username: 'a@example.org', password: 'secret', ...extra });
const parkIt = (extra: Record<string, unknown> = {}) => park(post('/api/auth/desktop-handoff/park', parkBody(extra)));
async function parkedCode(extra: Record<string, unknown> = {}): Promise<string> {
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody(extra)));
const answer = await parkIt(extra);
expect(answer.status).toBe(200);
const { code } = (await answer.json()) as { code: string };
// What the page does when the user confirms.
expect(await confirmHandoff(code)).toBe(true);
return code;
return ((await answer.json()) as { code: string }).code;
}
const redeemBody = (code: string, extra: Record<string, unknown> = {}) => ({ code, code_verifier: VERIFIER, slot: 1, remember: true, allowed_servers: null, ...extra });
const redeemBody = (code: string, extra: Record<string, unknown> = {}) => ({ code, code_verifier: VERIFIER, slot: 1, remember: true, allowed_servers: null, custom_servers_allowed: true, ...extra });
const redeemIt = (code: string, extra: Record<string, unknown> = {}) => redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code, extra)));
/** Everything the store holds, in the open. Nothing secret may be in it after its use. */
const heldInMemory = () => JSON.stringify([...((globalThis as unknown as { __bulwarkMobileHandoffStore?: Map<string, unknown> }).__bulwarkMobileHandoffStore ?? new Map()).values()]);
let revoked: string[];
beforeEach(() => {
cookieJar.clear();
resetHandoffStoreForTests();
clientAddress = `203.0.113.${(nextClient += 1)}`;
config.values = { jmapServerUrl: SERVER };
verifyJmapAuth.mockReset();
verifyJmapAuth.mockResolvedValue(undefined);
stalwartPasswordLogin.mockReset();
stalwartPasswordLogin.mockResolvedValue(TOKENS);
reserveLoginAttempt.mockReset();
reserveLoginAttempt.mockResolvedValue(async () => {});
discoverOAuth.mockReset();
discoverOAuth.mockResolvedValue({ revocation_endpoint: `${SERVER}/revoke` });
revoked = [];
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
if (String(url).endsWith('/revoke')) revoked.push(new URLSearchParams(String(init?.body)).get('token') ?? '');
return new Response('{}', { status: 200 });
}));
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
vi.restoreAllMocks();
});
@@ -135,173 +155,298 @@ describe('the target', () => {
expect(mobileHandoffTarget('http://127.0.0.1:51234/bulwark-desktop/callback')).toBe('');
});
it('a no goes back with the state and no code', () => {
const target = 'http://127.0.0.1:51234/bulwark-desktop/callback';
expect(desktopHandoffPort(target)).toBe('51234');
expect(desktopHandoffDeclineUrl(target, 's t')).toBe(`${target}?error=access_denied&state=s+t`);
});
it('the embedded build has none of these routes', () => {
expect(isDesktopBlockedRoute('/api/auth/desktop-handoff/park')).toBe(true);
expect(isDesktopBlockedRoute('/api/auth/desktop-handoff/redeem')).toBe(true);
for (const route of ['check', 'park', 'redeem', 'discard']) expect(isDesktopBlockedRoute(`/api/auth/desktop-handoff/${route}`)).toBe(true);
expect(isDesktopBlockedRoute('/api/auth/desktop-oauth')).toBe(false);
});
});
describe('parking a sign-in, in the browser', () => {
it('leaves this browser with no session', async () => {
await parkedCode();
describe('checking, before the question', () => {
const checkIt = (extra: Record<string, unknown> = {}, origin = ORIGIN) => check(post('/api/auth/desktop-handoff/check', checkBody(extra), origin));
it('keeps nothing: no record, no cookie, and the password appears nowhere', async () => {
const answer = await checkIt();
expect(answer.status).toBe(200);
expect(heldInMemory()).toBe('[]');
expect([...cookieJar.keys()]).toEqual([]);
expect(stalwartPasswordLogin).not.toHaveBeenCalled();
});
it('refuses another origin', async () => {
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody(), 'https://evil.example'));
expect(answer.status).toBe(403);
expect((await checkIt({}, 'https://evil.example')).status).toBe(403);
expect(verifyJmapAuth).not.toHaveBeenCalled();
});
it('says a wrong password is wrong, and that a second factor is needed', async () => {
verifyJmapAuth.mockRejectedValueOnce(new JmapAuthVerificationError('no', 401, 401));
expect(await (await checkIt()).json()).toEqual({ error: 'invalid_credentials' });
verifyJmapAuth.mockRejectedValueOnce(new JmapAuthVerificationError('no', 401, 402));
expect(await (await checkIt()).json()).toEqual({ error: 'totp_required' });
});
it('holds no password on an OAuth-only instance', async () => {
config.values = { jmapServerUrl: SERVER, oauthEnabled: true, oauthOnly: true };
expect((await checkIt()).status).toBe(403);
expect(verifyJmapAuth).not.toHaveBeenCalled();
});
it('over the login budget, nothing reaches the mail server, and the answer says why', async () => {
reserveLoginAttempt.mockResolvedValue(null);
const answer = await checkIt();
expect(answer.status).toBe(429);
expect(await answer.json()).toEqual({ error: 'too_many_attempts' });
expect(verifyJmapAuth).not.toHaveBeenCalled();
});
it('never goes to a server the instance does not know', async () => {
expect((await checkIt({ server_url: 'https://evil.example' })).status).toBe(400);
expect(verifyJmapAuth).not.toHaveBeenCalled();
});
});
describe('the instance admin\'s switch', () => {
it('closes every route, with nothing checked, parked or redeemed', async () => {
const code = await parkedCode();
verifyJmapAuth.mockClear();
stalwartPasswordLogin.mockClear();
config.values = { jmapServerUrl: SERVER, desktopBrowserSignIn: false };
expect((await check(post('/api/auth/desktop-handoff/check', checkBody()))).status).toBe(403);
expect((await parkIt()).status).toBe(403);
expect(verifyJmapAuth).not.toHaveBeenCalled();
expect(stalwartPasswordLogin).not.toHaveBeenCalled();
expect((await redeemIt(code)).status).toBe(403);
});
});
describe('parking, after the yes', () => {
it('hands over tokens wherever the server can give them, and leaves this browser with no session', async () => {
const code = await parkedCode();
expect(verifyJmapAuth).not.toHaveBeenCalled();
expect([...cookieJar.keys()]).toEqual([]);
expect(heldInMemory()).not.toContain('secret');
const answer = await redeemIt(code);
const body = await answer.json();
expect(body).toMatchObject({ flow: 'tokens', password_login: true, username: 'a@example.org', access_token: 'access' });
expect(JSON.stringify(body)).not.toContain('secret');
expect(JSON.stringify(body)).not.toContain('"refresh"');
expect(cookieJar.get('jmap_rt_1')?.value).toBe('refresh');
});
it.each(['login_endpoint_missing', 'login_rejected', 'login_unreachable', 'token_exchange_failed'])('a password only as the last resort: %s', async (error) => {
stalwartPasswordLogin.mockResolvedValue({ ok: false, error });
const code = await parkedCode();
expect(verifyJmapAuth).toHaveBeenCalledOnce();
expect(await (await redeemIt(code)).json()).toEqual({ flow: 'password', server_url: SERVER, username: 'a@example.org', password: 'secret' });
});
it('a password that turns out wrong, on the way, parks nothing', async () => {
stalwartPasswordLogin.mockResolvedValue({ ok: false, error: 'invalid_credentials' });
const answer = await parkIt();
expect(answer.status).toBe(401);
expect(await answer.json()).toEqual({ error: 'invalid_credentials' });
expect(heldInMemory()).toBe('[]');
});
it('a wrong two-factor code gets no fallback to a password', async () => {
stalwartPasswordLogin.mockResolvedValue({ ok: false, error: 'login_rejected' });
expect((await parkIt({ totp: '000000' })).status).toBe(502);
expect(verifyJmapAuth).not.toHaveBeenCalled();
expect(heldInMemory()).toBe('[]');
});
it('refuses another origin', async () => {
expect((await park(post('/api/auth/desktop-handoff/park', parkBody(), 'https://evil.example'))).status).toBe(403);
expect(stalwartPasswordLogin).not.toHaveBeenCalled();
});
it.each([
['no challenge', { code_challenge: '' }],
['a bad challenge', { code_challenge: 'short' }],
['no state', { state: '' }],
['no password', { password: '' }],
])('refuses %s', async (_name, extra) => {
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody(extra)));
expect(answer.status).toBe(400);
expect(verifyJmapAuth).not.toHaveBeenCalled();
});
it('holds no password on an OAuth-only instance', async () => {
config.values = { jmapServerUrl: SERVER, oauthEnabled: true, oauthOnly: true };
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody()));
expect(answer.status).toBe(403);
expect(verifyJmapAuth).not.toHaveBeenCalled();
});
it('a wrong password parks nothing and says so', async () => {
verifyJmapAuth.mockRejectedValue(new JmapAuthVerificationError('no', 401, 401));
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody()));
expect(answer.status).toBe(401);
expect(await answer.json()).toEqual({ error: 'invalid_credentials' });
});
it('asks for the second factor when the server answers 402', async () => {
verifyJmapAuth.mockRejectedValue(new JmapAuthVerificationError('no', 401, 402));
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody()));
expect(await answer.json()).toEqual({ error: 'totp_required' });
});
it('over the login budget, nothing reaches the mail server', async () => {
reserveLoginAttempt.mockResolvedValue(null);
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody()));
expect(answer.status).toBe(429);
expect(verifyJmapAuth).not.toHaveBeenCalled();
expect((await parkIt(extra)).status).toBe(400);
expect(stalwartPasswordLogin).not.toHaveBeenCalled();
});
it('what was checked is what is parked: the body can\'t name another server for the app', async () => {
config.values = { jmapServerUrl: SERVER, jmapServers: [{ id: 'two', url: 'https://two.example', name: 'Two' }] };
const code = await parkedCode({ server_id: 'two', server_url: 'https://evil.example' });
expect(verifyJmapAuth.mock.calls[0][0]).toBe('https://two.example');
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect(await answer.json()).toMatchObject({ server_url: 'https://two.example' });
expect(stalwartPasswordLogin.mock.calls[0][0]).toMatchObject({ serverUrl: 'https://two.example' });
expect(await (await redeemIt(code)).json()).toMatchObject({ server_url: 'https://two.example' });
});
});
describe('the budget, with one address for a whole office', () => {
it('sign-ins that work never run out', async () => {
clientAddress = '198.51.100.7';
for (let i = 0; i < 25; i += 1) expect((await parkIt()).status, `sign-in ${i}`).toBe(200);
});
it('never goes to a server the instance does not know', async () => {
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody({ server_url: 'https://evil.example' })));
expect(answer.status).toBe(400);
expect(verifyJmapAuth).not.toHaveBeenCalled();
it('after ten failures it refuses before going upstream, so no code is spent, and says why', async () => {
clientAddress = '198.51.100.8';
stalwartPasswordLogin.mockResolvedValue({ ok: false, error: 'invalid_credentials' });
for (let i = 0; i < 10; i += 1) expect((await parkIt({ totp: '000000' })).status).toBe(401);
stalwartPasswordLogin.mockClear();
const answer = await parkIt({ totp: '123456' });
expect(answer.status).toBe(429);
expect(await answer.json()).toEqual({ error: 'too_many_attempts' });
expect(answer.headers.get('Retry-After')).toBeTruthy();
expect(stalwartPasswordLogin).not.toHaveBeenCalled();
});
it('a code is not live until the user confirms', async () => {
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody()));
const { code } = (await answer.json()) as { code: string };
const redeemed = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect(redeemed.status).toBe(400);
it('a bad code to redeem is what its budget counts, and a good one gives it back', async () => {
clientAddress = '198.51.100.9';
for (let i = 0; i < 12; i += 1) expect((await redeemIt(await parkedCode())).status).toBe(200);
for (let i = 0; i < 10; i += 1) expect((await redeemIt('f'.repeat(64))).status).toBe(400);
expect((await redeemIt('f'.repeat(64))).status).toBe(429);
});
});
describe('redeeming, in the app', () => {
it('a password goes to the page, once, and no cookie is written for it', async () => {
it('a code can be used once', async () => {
const code = await parkedCode();
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect(answer.status).toBe(200);
expect(answer.headers.get('Cache-Control')).toBe('no-store');
expect(await answer.json()).toEqual({ flow: 'password', server_url: SERVER, username: 'a@example.org', password: 'secret' });
expect([...cookieJar.keys()]).toEqual([]);
const again = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect((await redeemIt(code)).status).toBe(200);
const again = await redeemIt(code);
expect(again.status).toBe(400);
expect(await again.json()).toEqual({ error: 'invalid_code' });
});
it('a wrong verifier gets nothing, and spends the code', async () => {
const code = await parkedCode();
const wrong = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code, { code_verifier: 'w'.repeat(64) })));
const wrong = await redeemIt(code, { code_verifier: 'w'.repeat(64) });
expect(wrong.status).toBe(400);
expect(await wrong.json()).toEqual({ error: 'invalid_verifier' });
const right = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect(right.status).toBe(400);
expect((await redeemIt(code)).status).toBe(400);
expect([...cookieJar.keys()]).toEqual([]);
});
it('a late code is told so', async () => {
const code = await parkedCode();
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + 61_000);
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
const answer = await redeemIt(code);
expect(answer.status).toBe(400);
expect(await answer.json()).toEqual({ error: 'expired_code' });
});
it('a two-factor sign-in parks tokens, not the password, and the app gets its own cookie', async () => {
stalwartPasswordLogin.mockResolvedValue({
ok: true,
tokens: { access_token: 'access', refresh_token: 'refresh', expires_in: 3600 },
tokenEndpoint: `${SERVER}/auth/token`,
clientId: 'x',
});
const code = await parkedCode({ totp: '123456' });
expect(stalwartPasswordLogin.mock.calls[0][0]).toMatchObject({ serverUrl: SERVER, totp: '123456', trusted: true });
expect(verifyJmapAuth).not.toHaveBeenCalled();
expect([...cookieJar.keys()]).toEqual([]);
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
const body = await answer.json();
expect(body).toMatchObject({ flow: 'tokens', server_url: SERVER, access_token: 'access', remember: true });
expect(JSON.stringify(body)).not.toContain('refresh');
expect(JSON.stringify(body)).not.toContain('secret');
expect(cookieJar.get('jmap_rt_1')?.value).toBe('refresh');
expect(cookieJar.get('jmap_rt_1')?.options).toMatchObject({ httpOnly: true });
});
it('keeps the instance\'s strict cookies strict', async () => {
config.values = { jmapServerUrl: SERVER, cookieSameSite: 'strict' };
stalwartPasswordLogin.mockResolvedValue({ ok: true, tokens: { access_token: 'a', refresh_token: 'r', expires_in: 60 }, tokenEndpoint: 't', clientId: 'x' });
const code = await parkedCode({ totp: '123456' });
await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect(cookieJar.get('jmap_rt_1')?.options).toMatchObject({ sameSite: 'strict' });
await redeemIt(await parkedCode());
expect(cookieJar.get('jmap_rt_1')?.options).toMatchObject({ sameSite: 'strict', httpOnly: true });
});
it('a wrong code from the server\'s side parks nothing', async () => {
stalwartPasswordLogin.mockResolvedValue({ ok: false, error: 'invalid_credentials' });
const answer = await park(post('/api/auth/desktop-handoff/park', parkBody({ totp: '000000' })));
expect(answer.status).toBe(401);
});
it('a server off the device\'s list gets nothing written, and the code is gone', async () => {
stalwartPasswordLogin.mockResolvedValue({ ok: true, tokens: { access_token: 'a', refresh_token: 'r', expires_in: 60 }, tokenEndpoint: 't', clientId: 'x' });
const code = await parkedCode({ totp: '123456' });
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code, { allowed_servers: ['https://other.example'] })));
it('a server off the device\'s list gets nothing written, the token is revoked, and the code is gone', async () => {
const code = await parkedCode();
const answer = await redeemIt(code, { allowed_servers: ['https://other.example'] });
expect(answer.status).toBe(403);
expect(await answer.json()).toMatchObject({ code: 'blocked_by_policy' });
expect([...cookieJar.keys()]).toEqual([]);
const again = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
expect(again.status).toBe(400);
expect(revoked).toEqual(['refresh']);
expect((await redeemIt(code)).status).toBe(400);
});
it('a list that names the server lets it through', async () => {
const code = await parkedCode();
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code, { allowed_servers: [SERVER] })));
expect(answer.status).toBe(200);
expect((await redeemIt(await parkedCode(), { allowed_servers: [SERVER] })).status).toBe(200);
});
describe('a server of the user\'s own, on an instance that allows them', () => {
const OWN = 'https://1.1.1.1';
beforeEach(() => {
config.values = { jmapServerUrl: SERVER, allowCustomJmapEndpoint: true };
});
it('is refused when the device\'s rule says no: forced InstanceUrl, or AllowStandalone off', async () => {
const code = await parkedCode({ server_url: OWN });
const answer = await redeemIt(code, { custom_servers_allowed: false });
expect(answer.status).toBe(403);
expect(await answer.json()).toMatchObject({ code: 'blocked_by_policy' });
expect([...cookieJar.keys()]).toEqual([]);
});
it('is refused when a page says nothing about it', async () => {
const code = await parkedCode({ server_url: OWN });
const { custom_servers_allowed: _left, ...withoutRule } = redeemBody(code);
expect((await redeem(post('/api/auth/desktop-handoff/redeem', withoutRule))).status).toBe(403);
});
it('goes through when the device allows it', async () => {
expect((await redeemIt(await parkedCode({ server_url: OWN }))).status).toBe(200);
});
it('the instance\'s own server is no such thing', async () => {
expect((await redeemIt(await parkedCode(), { custom_servers_allowed: false })).status).toBe(200);
});
});
it('refuses another origin', async () => {
const code = await parkedCode();
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code), 'https://evil.example'));
expect(answer.status).toBe(403);
expect((await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code), 'https://evil.example'))).status).toBe(403);
});
});
describe('what stays behind', () => {
const ssoBundle = {
flow: 'desktop-tokens' as const,
server_url: SERVER,
server_id: null,
custom: false,
access_token: 'sso-access',
refresh_token: 'sso-refresh',
expires_in: 3600,
signed_in_at: 1,
};
const parkedSso = () => stashHandoff(ssoBundle, { challenge: CHALLENGE, state: 's', awaitConfirm: true });
const discardIt = (code: string) => discard(post('/api/auth/desktop-handoff/discard', { code }));
it('"Not now" takes the tokens out of the store and revokes the refresh token', async () => {
const code = await parkedSso();
expect(heldInMemory()).toContain('sso-refresh');
expect((await discardIt(code)).status).toBe(200);
expect(heldInMemory()).not.toContain('sso-refresh');
expect(heldInMemory()).not.toContain('sso-access');
expect(revoked).toEqual(['sso-refresh']);
expect((await redeemIt(code)).status).toBe(400);
});
it('a provider with no revocation endpoint: the store is still emptied', async () => {
discoverOAuth.mockResolvedValue({});
const code = await parkedSso();
expect((await discardIt(code)).status).toBe(200);
expect(heldInMemory()).not.toContain('sso-refresh');
expect(revoked).toEqual([]);
});
it('discards only the desktop\'s, and nothing twice', async () => {
const phone = await stashHandoff({ flow: 'password', server_url: SERVER, username: 'a', password: 'phone-secret' }, { challenge: CHALLENGE, state: 's' });
await discardIt(phone);
expect(heldInMemory()).toContain('phone-secret');
const code = await parkedSso();
await discardIt(code);
await discardIt(code);
expect(revoked).toEqual(['sso-refresh']);
});
it('a code no one knows gets nothing', async () => {
expect((await discardIt('nonsense')).status).toBe(400);
});
it('with nobody coming back, a timer wipes what was parked, at its real expiry', async () => {
vi.useFakeTimers();
await stashHandoff({ flow: 'desktop-password', server_url: SERVER, server_id: null, custom: false, username: 'a', password: 'timer-secret' }, { challenge: CHALLENGE, state: 's' });
await parkedSso();
expect(heldInMemory()).toContain('timer-secret');
vi.advanceTimersByTime(HANDOFF_TTL_MS + 2);
expect(heldInMemory()).not.toContain('timer-secret');
expect(heldInMemory()).toContain('sso-refresh');
vi.advanceTimersByTime(HANDOFF_CONFIRM_TTL_MS);
expect(heldInMemory()).not.toContain('sso-refresh');
});
});
@@ -310,12 +455,14 @@ describe('the two kinds of code stay apart', () => {
const code = await parkedCode();
const answer = await mobileRedeem(post('/api/auth/handoff/redeem', { code, code_verifier: VERIFIER }));
expect(answer.status).toBe(400);
expect(JSON.stringify(await answer.json())).not.toContain('secret');
const body = JSON.stringify(await answer.json());
expect(body).not.toContain('refresh');
expect(body).not.toContain('access');
});
it('the desktop redeem takes no phone code', async () => {
const code = await stashHandoff({ flow: 'password', server_url: SERVER, username: 'a', password: 'secret' }, { challenge: CHALLENGE, state: 's' });
const answer = await redeem(post('/api/auth/desktop-handoff/redeem', redeemBody(code)));
const answer = await redeemIt(code);
expect(answer.status).toBe(400);
expect(JSON.stringify(await answer.json())).not.toContain('secret');
});
+1
View File
@@ -32,6 +32,7 @@ export function createConfig(overrides: Partial<ConfigData> = {}): ConfigData {
loginShowSubtitle: true,
loginShowTotp: true,
loginShowTokenLogin: false,
desktopBrowserSignIn: true,
loginShowRememberMe: false,
loginShowVersion: true,
demoMode: false,
@@ -109,3 +109,43 @@ describe('mobile hand-off with a shared store', () => {
expect(await (await replica()).redeemHandoff(code, VERIFIER, T0 + 2)).toMatchObject({ ok: true });
});
});
describe('what a shared store holds after a sign-in stops being any use', () => {
const key = (code: string) => 'handoff:' + createHash('sha256').update(code).digest('hex');
const DESKTOP = { flow: 'desktop-tokens' as const, server_url: 'https://mail.example.org', server_id: null, custom: false, access_token: 'a', refresh_token: 'r', expires_in: 60, signed_in_at: 1 };
it('a record with a sign-in in it is gone from the store at its real expiry, and a late code is still told so', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(T0);
const { stashHandoff, redeemHandoff, HANDOFF_TTL_MS } = await replica();
const code = await stashHandoff(PASSWORD_BUNDLE, { challenge: CHALLENGE, state: 's' }, T0);
expect(await getStore().kv.get(key(code))).not.toBeNull();
vi.setSystemTime(T0 + HANDOFF_TTL_MS + 1);
expect(await getStore().kv.get(key(code))).toBeNull();
expect(await redeemHandoff(code, VERIFIER, T0 + HANDOFF_TTL_MS + 1)).toEqual({ ok: false, reason: 'expired' });
vi.useRealTimers();
});
it('a confirmed code stays no longer than its 60 seconds', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(T0);
const { stashHandoff, confirmHandoff, HANDOFF_TTL_MS } = await replica();
const code = await stashHandoff(DESKTOP, { challenge: CHALLENGE, state: 's', awaitConfirm: true }, T0);
expect(await confirmHandoff(code, T0)).toBe(true);
vi.setSystemTime(T0 + HANDOFF_TTL_MS + 1);
expect(await getStore().kv.get(key(code))).toBeNull();
vi.useRealTimers();
});
it('a discard takes the sign-in out at once, gives it back once, and only the desktop\'s', async () => {
const { stashHandoff, discardDesktopHandoff, redeemHandoff } = await replica();
const code = await stashHandoff(DESKTOP, { challenge: CHALLENGE, state: 's', awaitConfirm: true });
const other = await replica();
expect(await other.discardDesktopHandoff(code)).toMatchObject({ refresh_token: 'r' });
expect(await discardDesktopHandoff(code)).toBeNull();
expect((await redeemHandoff(code, VERIFIER)).ok).toBe(false);
const phone = await stashHandoff(PASSWORD_BUNDLE, { challenge: CHALLENGE, state: 's' });
expect(await discardDesktopHandoff(phone)).toBeNull();
expect((await redeemHandoff(phone, VERIFIER)).ok).toBe(true);
});
});
+16
View File
@@ -238,6 +238,7 @@ describe('/api/auth/sso/complete for the desktop app', () => {
expect(res.body).toEqual({
mobile_handoff_code: expect.stringMatching(/^[0-9a-f]{64}$/),
server_url: 'https://mail.example.org',
account: '',
mobile_redirect_uri: LISTENER,
mobile_state: 'd-1',
});
@@ -248,6 +249,21 @@ describe('/api/auth/sso/complete for the desktop app', () => {
expect((await redeemHandoff(res.body.mobile_handoff_code, VERIFIER)).ok).toBe(false);
});
it('names the account for the question: from the id token, or the server\'s session', async () => {
const jwt = (claims: object) => `x.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.y`;
exchangeCodeForTokens.mockResolvedValue({ access_token: 'at', refresh_token: 'rt', id_token: jwt({ email: 'alice@example.org' }), expires_in: 3600 });
pending({ mobile_redirect_uri: LISTENER, mobile_state: 'd-1', mobile_code_challenge: CHALLENGE });
expect((await complete()).body.account).toBe('alice@example.org');
const fetched = vi.fn(async () => new Response(JSON.stringify({ username: 'bob@example.org' }), { status: 200 }));
vi.stubGlobal('fetch', fetched);
exchangeCodeForTokens.mockResolvedValue({ access_token: 'at', refresh_token: 'rt', expires_in: 3600 });
pending({ mobile_redirect_uri: LISTENER, mobile_state: 'd-1', mobile_code_challenge: CHALLENGE });
expect((await complete()).body.account).toBe('bob@example.org');
expect(fetched).toHaveBeenCalledWith('https://mail.example.org/.well-known/jmap', expect.objectContaining({ headers: { Authorization: 'Bearer at' } }));
vi.unstubAllGlobals();
});
it('hands the refresh token itself to the app, which writes its own cookie', async () => {
exchangeCodeForTokens.mockResolvedValue({ access_token: 'at', refresh_token: 'rt', id_token: 'idt', expires_in: 3600 });
pending({ mobile_redirect_uri: LISTENER, mobile_state: 'd-1', mobile_code_challenge: CHALLENGE, server_id: 'second' });
+10 -1
View File
@@ -66,8 +66,9 @@ vi.mock('@/lib/auth/session-secret', () => ({
hasSessionSecret: () => true,
}));
const configValues = vi.hoisted(() => ({ desktopBrowserSignIn: true } as Record<string, unknown>));
vi.mock('@/lib/admin/config-manager', () => ({
configManager: { get: () => '' },
configManager: { get: (key: string) => (key in configValues ? configValues[key] : '') },
}));
function mockRequest(body: Record<string, unknown>): unknown {
@@ -217,6 +218,14 @@ describe('sso start for the desktop app', () => {
expect(encrypted.last).toMatchObject({ mobile_redirect_uri: LISTENER, mobile_state: 'd-1', mobile_code_challenge: CHALLENGE });
});
it('refuses it when the instance\'s admin turned it off', async () => {
configValues.desktopBrowserSignIn = false;
const { status } = await desktop({ mobile_code_challenge: CHALLENGE });
configValues.desktopBrowserSignIn = true;
expect(status).toBe(403);
expect(encrypted.last).toBeNull();
});
it('refuses it without a challenge: tokens would come back for a link', async () => {
const { status } = await desktop();
expect(status).toBe(400);
+3
View File
@@ -300,6 +300,9 @@ export const CONFIG_ENV_MAP: Record<string, { envVar: string; fileEnvVar?: strin
// password. For JMAP servers that hand out API tokens, such as Fastmail,
// whose API accepts no passwords at all.
loginShowTokenLogin: { envVar: 'LOGIN_SHOW_TOKEN_LOGIN', type: 'boolean', defaultValue: false },
// The desktop app's "Sign in with your browser". Turn off on a terminal server: another
// user there can bind a loopback port and send a link that asks for someone's sign-in.
desktopBrowserSignIn: { envVar: 'DESKTOP_BROWSER_SIGN_IN', type: 'boolean', defaultValue: true },
// Show the "Remember me" box on the login form. Off (the default) remembers
// every sign-in, as long as a SESSION_SECRET makes that possible.
loginShowRememberMe: { envVar: 'LOGIN_SHOW_REMEMBER_ME', type: 'boolean', defaultValue: false },
+33
View File
@@ -0,0 +1,33 @@
import { logger } from '@/lib/logger';
import type { ParkedHandoff } from '@/lib/auth/handoff-store';
import { discoverOAuth } from '@/lib/oauth/discovery';
import { buildOAuthParams, DEFAULT_CLIENT_ID, getDiscoveryValidator, getRequiredConfig } from '@/lib/oauth/token-exchange';
const REVOCATION_TIMEOUT_MS = 3000;
/**
* A refresh token that was minted and then not wanted: declined, or refused by the device's
* policy. Revoked where the provider has an endpoint for it (Stalwart has none, and there the
* token just stops being held). Never throws: nobody is waiting to hear about a failure.
*/
export async function revokeParkedTokens(parked: ParkedHandoff): Promise<void> {
if (parked.flow !== 'desktop-tokens' || !parked.refresh_token) return;
try {
const options = { fallbackClientId: DEFAULT_CLIENT_ID };
const { discoveryUrl } = getRequiredConfig(parked.server_id, options);
const metadata = await discoverOAuth(discoveryUrl, { validateEndpoint: getDiscoveryValidator(discoveryUrl) });
if (!metadata?.revocation_endpoint) return;
const params = buildOAuthParams({ token: parked.refresh_token, token_type_hint: 'refresh_token' }, parked.server_id, options);
// The body holds the refresh token: no redirect is followed with it.
const response = await fetch(metadata.revocation_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params.toString(),
signal: AbortSignal.timeout(REVOCATION_TIMEOUT_MS),
redirect: 'error',
});
if (!response.ok) logger.warn('Declined token revocation returned error', { status: response.status });
} catch (error) {
logger.warn('Declined token revocation failed', { error: error instanceof Error ? error.message : 'Unknown error' });
}
}
+63
View File
@@ -0,0 +1,63 @@
import { configManager } from '@/lib/admin/config-manager';
import { findServerById, findServerByUrl, parseJmapServers, resolveTrustedJmapUrl, type JmapServerEntry } from '@/lib/admin/jmap-servers';
import { IS_DESKTOP_BUILD } from '@/lib/desktop/flag';
import { isPublicHttpUrl } from '@/lib/security/url-guard';
/**
* What the desktop app's sign-in routes share (app/api/auth/desktop-handoff). The same
* pinning as the other sign-in routes, and the instance admin's switch: on a terminal
* server another local user can bind a loopback port, so the admin can turn the hand-off
* off there. A device's own `BrowserSignIn` doesn't reach this: it's about the app, and
* the other user's link opens in a browser.
*/
export interface DesktopHandoffRefusal {
error: string;
status: number;
}
export function desktopHandoffEnabled(): boolean {
return !IS_DESKTOP_BUILD && configManager.get<boolean>('desktopBrowserSignIn', true);
}
export type DesktopHandoffServer =
| { refusal: DesktopHandoffRefusal }
| {
entry: JmapServerEntry | undefined;
/** What's checked and parked, whatever the body said. */
resolved: string;
upstream: string;
trusted: boolean;
/** The user's own server, by `allowCustomJmapEndpoint`. A device's policy may refuse it. */
custom: boolean;
};
export async function resolveDesktopHandoffServer(serverUrl: string, serverId: unknown): Promise<DesktopHandoffServer> {
await configManager.ensureLoaded();
if (!desktopHandoffEnabled()) return { refusal: { error: 'disabled', status: 403 } };
if (configManager.get<boolean>('oauthEnabled', false) && configManager.get<boolean>('oauthOnly', false)) {
return { refusal: { error: 'oauth_only', status: 403 } };
}
const configured =
configManager.get<string>('jmapServerUrl', '') || process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL || '';
const list = parseJmapServers(configManager.get<unknown>('jmapServers', []));
const requested = typeof serverId === 'string' && serverId ? serverId : null;
const entry = findServerById(list, requested) || findServerByUrl(list, serverUrl) || undefined;
let resolved: string;
let trusted = true;
let custom = false;
if (entry) {
resolved = entry.url;
} else {
const pinned = resolveTrustedJmapUrl(serverUrl, configured, list);
if (pinned) {
resolved = pinned;
} else if (configManager.get<boolean>('allowCustomJmapEndpoint', false) && (await isPublicHttpUrl(serverUrl))) {
resolved = serverUrl;
trusted = false;
custom = true;
} else {
return { refusal: { error: 'invalid_server_url', status: 400 } };
}
}
return { entry, resolved, upstream: resolved.replace(/\/+$/, ''), trusted, custom };
}
+71 -7
View File
@@ -65,11 +65,23 @@ export function isHandoffCode(value: unknown): value is string {
* redeem route refuses them.
*/
export type DesktopHandoffBundle =
| { flow: 'desktop-password'; server_url: string; server_id: string | null; username: string; password: string }
| {
flow: 'desktop-password';
server_url: string;
server_id: string | null;
/** The user's own server, which a device's policy may refuse. */
custom: boolean;
username: string;
password: string;
}
| {
flow: 'desktop-tokens';
server_url: string;
server_id: string | null;
custom: boolean;
/** From a typed password, not a provider's page: a password account, as the user knows it. */
password_login?: boolean;
username?: string;
access_token: string;
refresh_token?: string;
id_token?: string;
@@ -103,8 +115,9 @@ function store(): Map<string, HandoffRecord> {
return g[STORE_KEY];
}
// Wipe sign-ins past their expiry and forget tombstones past theirs. Called
// on every operation, so memory stays bounded without a timer.
// Wipe sign-ins past their expiry and forget tombstones past theirs. Called on
// every operation, and by a timer at each record's expiry: a sign-in nobody asks
// about again must not stay in memory until someone happens to call in.
function sweep(now: number): void {
const codes = store();
for (const [code, record] of codes) {
@@ -113,6 +126,11 @@ function sweep(now: number): void {
}
}
function wipeWhenDue(expiresAt: number, now: number): void {
const timer = setTimeout(() => sweep(Date.now()), Math.max(expiresAt - now, 0) + 1);
timer.unref?.();
}
function s256(verifier: string): string {
return createHash('sha256').update(verifier, 'ascii').digest('base64url');
}
@@ -159,6 +177,8 @@ function redeemOutcome(record: HandoffRecord, bundle: ParkedHandoff | null, veri
// ─── shared store ──────────────────────────────────────────────────────────
const sharedKey = (code: string) => `handoff:${createHash('sha256').update(code).digest('hex')}`;
/** Holds no sign-in, only when it runs out. So a code past that, with its record gone, is told "expired". */
const issuedKey = (code: string) => `handoff-issued:${createHash('sha256').update(code).digest('hex')}`;
function seal(record: HandoffRecord): string {
return encryptPayload({ r: record }, 'handoff-store');
@@ -173,6 +193,8 @@ function open(sealed: string | null, now: number): HandoffRecord | null {
}
const ttl = (record: HandoffRecord, now: number) => Math.max(record.forgetAt - now, 0) + CLEANUP_MS;
/** A record with a sign-in in it stays no longer than the sign-in is good for. */
const secretTtl = (record: HandoffRecord, now: number) => Math.max(record.expiresAt - now, 1);
// ─── API ───────────────────────────────────────────────────────────────────
@@ -190,7 +212,8 @@ export async function stashHandoff(
if (isSharedMode()) {
// Each code is spent by a single redeem and dies on its own; the create
// budget bounds how many one client parks.
await getStore().kv.set(sharedKey(code), seal(record), { ttlMs: ttl(record, now) });
await getStore().kv.set(sharedKey(code), seal(record), { ttlMs: secretTtl(record, now) });
await getStore().kv.set(issuedKey(code), String(record.expiresAt), { ttlMs: ttl(record, now) });
return code;
}
sweep(now);
@@ -202,6 +225,7 @@ export async function stashHandoff(
codes.delete(oldest);
}
codes.set(code, record);
wipeWhenDue(record.expiresAt, now);
return code;
}
@@ -219,16 +243,44 @@ export async function confirmHandoff(code: string, now = Date.now()): Promise<bo
if (!record || !record.bundle || record.expiresAt <= now || record.confirmed) return undefined;
result.ok = true;
return seal(confirmed(record, now));
}, { ttlMs: HANDOFF_TTL_MS + TOMBSTONE_MS + CLEANUP_MS });
}, { ttlMs: HANDOFF_TTL_MS });
if (result.ok) await getStore().kv.set(issuedKey(code), String(now + HANDOFF_TTL_MS), { ttlMs: HANDOFF_TTL_MS + TOMBSTONE_MS + CLEANUP_MS });
return result.ok;
}
sweep(now);
const record = store().get(code);
if (!record || !record.bundle || record.confirmed) return false;
store().set(code, confirmed(record, now));
const live = confirmed(record, now);
store().set(code, live);
wipeWhenDue(live.expiresAt, now);
return true;
}
/**
* The user said no to the desktop app, or left. The sign-in goes now, and what it held comes
* back once, so a refresh token can be revoked. Only the desktop's: the phone's flow has its own.
*/
export async function discardDesktopHandoff(code: string, now = Date.now()): Promise<ParkedHandoff | null> {
const isDesktop = (bundle: ParkedHandoff | null) => bundle?.flow === 'desktop-password' || bundle?.flow === 'desktop-tokens';
if (isSharedMode()) {
let taken: ParkedHandoff | null = null;
await getStore().kv.update(sharedKey(code), (current) => {
taken = null;
const record = open(current, now);
if (!record || !isDesktop(record.bundle)) return undefined;
taken = record.bundle;
return seal({ ...record, bundle: null });
}, { ttlMs: TOMBSTONE_MS + CLEANUP_MS });
return taken as ParkedHandoff | null;
}
sweep(now);
const record = store().get(code);
if (!record || !isDesktop(record.bundle)) return null;
const taken = record.bundle;
record.bundle = null;
return taken;
}
/**
* Hand out the sign-in behind `code` when `verifier` matches its challenge.
* The code is spent by the attempt, whatever its outcome. `expires_in` of an
@@ -239,7 +291,10 @@ export async function redeemHandoff(code: string, verifier: string, now = Date.n
const kv = getStore().kv;
// Taken in one step: of two attempts, only one sees the sign-in.
const record = open(await kv.take(sharedKey(code)), now);
if (!record) return { ok: false, reason: 'invalid' };
if (!record) {
const until = await kv.get(issuedKey(code));
return { ok: false, reason: until !== null && Number(until) <= now ? 'expired' : 'invalid' };
}
const bundle = record.expiresAt > now ? record.bundle : null;
// A tombstone goes back, so a late attempt is told "expired". The code is
// spent already: if the tombstone can't be written, the answer stands.
@@ -269,12 +324,21 @@ export function resetHandoffStoreForTests(): void {
// filling the store or hammering the redeem route.
const createBudget = createFailureBudget({ name: 'handoff-create', clientMax: 10, globalMax: Infinity });
const redeemBudget = createFailureBudget({ name: 'handoff-redeem', clientMax: 10, globalMax: Infinity });
const desktopParkBudget = createFailureBudget({ name: 'desktop-handoff-park', clientMax: 10, globalMax: Infinity });
/** Count one parked sign-in for `client`; false when it is over its limit. */
export async function reserveHandoffCreate(client: string, now = Date.now()): Promise<boolean> {
return (await createBudget.reserve(client, now)) !== null;
}
/**
* One park for the desktop app, reserved before anything goes upstream: null when `client` is
* over. Only failures count, so everyone behind one office address can sign in.
*/
export function reserveDesktopHandoffPark(client: string, now = Date.now()): Promise<BudgetRefund | null> {
return desktopParkBudget.reserve(client, now);
}
/**
* Reserve one redeem attempt for `client`: null when it is over its limit,
* otherwise a refund to call when the redeem succeeded (only failures count).
+33 -2
View File
@@ -28,9 +28,40 @@ export async function requestMobileHandoffCodeUrl(opts: {
}
}
/** The desktop app's sign-in, before its question: is this password right? Nothing is kept. */
export async function checkDesktopSignIn(opts: {
serverUrl: string;
serverId?: string;
username: string;
password: string;
}): Promise<{ ok: true } | { error: string }> {
try {
const res = await apiFetch('/api/auth/desktop-handoff/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ server_url: opts.serverUrl, server_id: opts.serverId, username: opts.username, password: opts.password }),
});
if (res.ok) return { ok: true };
const data = (await res.json().catch(() => null)) as { error?: unknown } | null;
return { error: typeof data?.error === 'string' ? data.error : 'login_failed' };
} catch {
return { error: 'network_error' };
}
}
/** The tab with an SSO sign-in the user hasn't answered went, or said no: it's not kept. */
export function discardDesktopSignIn(code: string): void {
void apiFetch('/api/auth/desktop-handoff/discard', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
keepalive: true,
}).catch(() => {});
}
/**
* The desktop app's sign-in on this page: checks the password against the mail server and
* parks it (/api/auth/desktop-handoff/park). This browser gets no session out of it.
* The user said yes: parks the sign-in for the app (/api/auth/desktop-handoff/park), as
* tokens wherever the server can give them. This browser gets no session out of it.
*/
export async function parkDesktopSignIn(opts: {
challenge: string;
+10
View File
@@ -42,6 +42,16 @@ export function desktopHandoffTarget(raw: string | null | undefined): string {
return match && Number(match[1]) <= 65535 ? match[0] : '';
}
/** The port a desktop target names, for the question the page asks. */
export function desktopHandoffPort(target: string): string {
return DESKTOP_TARGET.exec(target)?.[1] ?? '';
}
/** "Not now": ends the app's flow at its listener, so it isn't left waiting. No code in it. */
export function desktopHandoffDeclineUrl(target: string, state: string): string {
return `${target}?${new URLSearchParams({ error: 'access_denied', state }).toString()}`;
}
/** Either kind of target, as the callback page reads it back. */
export function handoffTarget(raw: string | null | undefined): string {
return mobileHandoffTarget(raw) || desktopHandoffTarget(raw);
+1
View File
@@ -56,6 +56,7 @@ const configValidators = {
loginShowSubtitle: isBoolean,
loginShowTotp: isBoolean,
loginShowTokenLogin: isBoolean,
desktopBrowserSignIn: isBoolean,
loginShowRememberMe: isBoolean,
loginShowVersion: isBoolean,
demoMode: isBoolean,
+3
View File
@@ -36,6 +36,8 @@ export type DesktopBrowserSignInOutcome =
| { kind: 'invalid' }
| { kind: 'policy' }
| { kind: 'cancelled' }
/** The user said no in the browser. */
| { kind: 'denied' }
| { kind: 'timeout' }
| { kind: 'no_browser' }
| { kind: 'failed'; error: string };
@@ -75,6 +77,7 @@ export function cancelBrowserSignIn(): void {
function failure(error: string): DesktopBrowserSignInOutcome {
if (error === 'cancelled') return { kind: 'cancelled' };
if (error === 'denied') return { kind: 'denied' };
if (error === 'timeout') return { kind: 'timeout' };
if (error === 'no_browser') return { kind: 'no_browser' };
if (error === 'policy') return { kind: 'policy' };
+1
View File
@@ -46,6 +46,7 @@ export function shellLabels(t: (key: string, values?: Record<string, string>) =>
signInDone: t('desktop_browser_sign_in.page_done'),
signInFailed: t('desktop_browser_sign_in.page_failed'),
signInLinkUsed: t('desktop_browser_sign_in.page_link_used'),
signInDeclined: t('desktop_browser_sign_in.page_declined'),
signInPageTitle: t('desktop_browser_sign_in.page_title', { server: '{server}' }),
signInPageIntro: t('desktop_browser_sign_in.page_intro', { server: '{server}' }),
signInUsername: t('desktop_browser_sign_in.page_username'),
+1
View File
@@ -89,6 +89,7 @@ export function applyLiteConfig(raw: unknown, defaults?: { jmapServerUrl?: strin
loginShowSubtitle: bool(input.loginShowSubtitle, true),
loginShowTotp: bool(input.loginShowTotp, true),
loginShowTokenLogin: bool(input.loginShowTokenLogin, false),
desktopBrowserSignIn: false,
loginShowRememberMe: bool(input.loginShowRememberMe, false),
loginShowVersion: bool(input.loginShowVersion, true),
demoMode: bool(input.demoMode, false),
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "استغرق تسجيل الدخول في المتصفح وقتًا طويلًا. حاول مرة أخرى.",
"no_browser": "تعذر على Bulwark فتح المتصفح. حاول مرة أخرى أو سجّل الدخول هنا.",
"failed": "تعذر تسجيل الدخول عبر المتصفح. حاول مرة أخرى.",
"handoff_banner": "أنت تسجّل الدخول إلى تطبيق Bulwark على هذا الكمبيوتر. يبقى هذا المتصفح خارج Bulwark.",
"handoff_banner": "طلب برنامج على هذا الكمبيوتر تسجيل الدخول هذا لتطبيق Bulwark. يبقى هذا المتصفح خارج Bulwark. إذا لم تبدأ ذلك بنفسك، فأغلق علامة التبويب هذه.",
"consent_title": "هل تريد تسجيل الدخول إلى تطبيق Bulwark؟",
"consent_description": "سيذهب تسجيل دخول {username} إلى تطبيق Bulwark على هذا الكمبيوتر. تابع فقط إذا بدأت ذلك من التطبيق.",
"consent_description": "يطلب برنامج على هذا الكمبيوتر، على المنفذ {port}، تسجيل دخول {username}. تابع فقط إذا كنت قد ضغطت للتو على «تسجيل الدخول عبر المتصفح…» في تطبيق Bulwark هنا. وإلا فقد يحاول شخص ما الوصول إلى حسابك: اختر ليس الآن.",
"consent_confirm": "تسجيل الدخول إلى التطبيق",
"consent_cancel": "ليس الآن",
"page_done": "يمكنك إغلاق علامة التبويب هذه والعودة إلى Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "تسجيل الدخول",
"page_wrong_password": "لم يقبل الخادم اسم المستخدم وكلمة المرور هذين.",
"page_code_needed": "يحتاج هذا الحساب أيضًا إلى رمز المصادقة الثنائية. أدخل كلمة المرور مرة أخرى والرمز.",
"page_no_answer": "تعذر على Bulwark تسجيل الدخول. تحقق من إمكانية الوصول إلى الخادم وحاول مرة أخرى."
"page_no_answer": "تعذر على Bulwark تسجيل الدخول. تحقق من إمكانية الوصول إلى الخادم وحاول مرة أخرى.",
"declined": "رفضت في المتصفح، لذا لم يتم تسجيل الدخول.",
"too_many": "محاولات تسجيل دخول كثيرة جدًا من هذه الشبكة. انتظر بضع دقائق وحاول مرة أخرى.",
"page_declined": "لم يتم تسليم أي شيء. يمكنك إغلاق علامة التبويب هذه."
},
"desktop_updates": {
"title": "التحديثات",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "L’inici de sessió al navegador ha trigat massa. Torna-ho a provar.",
"no_browser": "Bulwark no ha pogut obrir el navegador. Torna-ho a provar o inicia la sessió aquí.",
"failed": "No s’ha pogut iniciar la sessió a través del navegador. Torna-ho a provar.",
"handoff_banner": "Estàs iniciant la sessió a l’aplicació Bulwark d’aquest ordinador. Aquest navegador continua sense sessió a Bulwark.",
"handoff_banner": "Un programa d’aquest ordinador ha demanat aquest inici de sessió per a l’aplicació Bulwark. Aquest navegador continua sense sessió a Bulwark. Si no ho has començat tu, tanca aquesta pestanya.",
"consent_title": "Vols iniciar la sessió a l’aplicació Bulwark?",
"consent_description": "L’inici de sessió de {username} va a l’aplicació Bulwark d’aquest ordinador. Continua només si ho has començat des de l’aplicació.",
"consent_description": "Un programa d’aquest ordinador, al port {port}, demana l’inici de sessió de {username}. Continua només si acabes de prémer «Inicia la sessió amb el navegador…» a l’aplicació Bulwark d’aquí. Si no, potser algú intenta entrar al teu compte: tria Ara no.",
"consent_confirm": "Inicia la sessió a l’aplicació",
"consent_cancel": "Ara no",
"page_done": "Pots tancar aquesta pestanya i tornar a Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Inicia la sessió",
"page_wrong_password": "El servidor no ha acceptat aquest nom d’usuari i aquesta contrasenya.",
"page_code_needed": "Aquest compte també necessita un codi de dos factors. Torna a escriure la contrasenya i el codi.",
"page_no_answer": "Bulwark no ha pogut iniciar la sessió. Comprova que el servidor sigui accessible i torna-ho a provar."
"page_no_answer": "Bulwark no ha pogut iniciar la sessió. Comprova que el servidor sigui accessible i torna-ho a provar.",
"declined": "Has dit que no al navegador, així que no s’ha iniciat cap sessió.",
"too_many": "Massa intents d’inici de sessió des d’aquesta xarxa. Espera uns minuts i torna-ho a provar.",
"page_declined": "No s’ha lliurat res. Pots tancar aquesta pestanya."
},
"desktop_updates": {
"title": "Actualitzacions",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Přihlášení v prohlížeči trvalo příliš dlouho. Zkuste to znovu.",
"no_browser": "Bulwark nemohl otevřít prohlížeč. Zkuste to znovu nebo se přihlaste zde.",
"failed": "Přihlášení přes prohlížeč se nezdařilo. Zkuste to znovu.",
"handoff_banner": "Přihlašujete se do aplikace Bulwark v tomto počítači. Tento prohlížeč zůstane z Bulwarku odhlášený.",
"handoff_banner": "Program v tomto počítači požádal o toto přihlášení pro aplikaci Bulwark. Tento prohlížeč zůstane z Bulwarku odhlášený. Pokud jste to nespustili vy, zavřete tuto kartu.",
"consent_title": "Přihlásit se do aplikace Bulwark?",
"consent_description": "Vaše přihlášení pro {username} půjde do aplikace Bulwark v tomto počítači. Pokračujte jen tehdy, pokud jste to spustili z aplikace.",
"consent_description": "Program v tomto počítači, na portu {port}, žádá o přihlášení pro {username}. Pokračujte, jen pokud jste právě klikli na „Přihlásit se v prohlížeči…“ v aplikaci Bulwark v tomto počítači. Pokud ne, možná se někdo snaží dostat do vašeho účtu: zvolte Teď ne.",
"consent_confirm": "Přihlásit se do aplikace",
"consent_cancel": "Teď ne",
"page_done": "Tuto kartu můžete zavřít a vrátit se do Bulwarku.",
@@ -6902,7 +6902,10 @@
"page_submit": "Přihlásit se",
"page_wrong_password": "Server toto uživatelské jméno a heslo nepřijal.",
"page_code_needed": "Tento účet potřebuje také dvoufázový kód. Zadejte znovu heslo a kód.",
"page_no_answer": "Bulwark se nemohl přihlásit. Zkontrolujte, zda je server dostupný, a zkuste to znovu."
"page_no_answer": "Bulwark se nemohl přihlásit. Zkontrolujte, zda je server dostupný, a zkuste to znovu.",
"declined": "V prohlížeči jste odmítli, takže k přihlášení nedošlo.",
"too_many": "Příliš mnoho pokusů o přihlášení z této sítě. Počkejte několik minut a zkuste to znovu.",
"page_declined": "Nic nebylo předáno. Tuto kartu můžete zavřít."
},
"desktop_updates": {
"title": "Aktualizace",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Login i browseren tog for lang tid. Prøv igen.",
"no_browser": "Bulwark kunne ikke åbne din browser. Prøv igen, eller log ind her.",
"failed": "Login via din browser lykkedes ikke. Prøv igen.",
"handoff_banner": "Du logger ind i Bulwark-appen på denne computer. Denne browser forbliver logget ud af Bulwark.",
"handoff_banner": "Et program på denne computer har bedt om dette login til Bulwark-appen. Denne browser forbliver logget ud af Bulwark. Hvis du ikke har startet dette, så luk denne fane.",
"consent_title": "Log ind i Bulwark-appen?",
"consent_description": "Dit login for {username} går til Bulwark-appen på denne computer. Fortsæt kun, hvis du startede dette fra appen.",
"consent_description": "Et program på denne computer, på port {port}, beder om login for {username}. Fortsæt kun, hvis du lige har trykket på \"Log ind med din browser…\" i Bulwark-appen her. Hvis ikke, prøver nogen måske at komme ind på din konto: vælg Ikke nu.",
"consent_confirm": "Log ind i appen",
"consent_cancel": "Ikke nu",
"page_done": "Du kan lukke denne fane og gå tilbage til Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Log ind",
"page_wrong_password": "Serveren accepterede ikke dette brugernavn og denne adgangskode.",
"page_code_needed": "Denne konto skal også bruge en tofaktorkode. Indtast din adgangskode igen og koden.",
"page_no_answer": "Bulwark kunne ikke logge ind. Tjek, at serveren kan nås, og prøv igen."
"page_no_answer": "Bulwark kunne ikke logge ind. Tjek, at serveren kan nås, og prøv igen.",
"declined": "Du sagde nej i din browser, så der blev ikke logget ind.",
"too_many": "For mange loginforsøg fra dette netværk. Vent et par minutter, og prøv igen.",
"page_declined": "Intet blev overdraget. Du kan lukke denne fane."
},
"desktop_updates": {
"title": "Opdateringer",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Die Anmeldung im Browser hat zu lange gedauert. Versuchen Sie es noch einmal.",
"no_browser": "Bulwark konnte Ihren Browser nicht öffnen. Versuchen Sie es noch einmal oder melden Sie sich hier an.",
"failed": "Die Anmeldung über Ihren Browser hat nicht geklappt. Versuchen Sie es noch einmal.",
"handoff_banner": "Sie melden sich bei der Bulwark-App auf diesem Computer an. Dieser Browser bleibt bei Bulwark abgemeldet.",
"handoff_banner": "Ein Programm auf diesem Computer hat diese Anmeldung für die Bulwark-App angefordert. Dieser Browser bleibt bei Bulwark abgemeldet. Wenn Sie das nicht gestartet haben, schließen Sie diesen Tab.",
"consent_title": "Bei der Bulwark-App anmelden?",
"consent_description": "Ihre Anmeldung für {username} geht an die Bulwark-App auf diesem Computer. Fahren Sie nur fort, wenn Sie dies aus der App gestartet haben.",
"consent_description": "Ein Programm auf diesem Computer, an Port {port}, fragt nach der Anmeldung für {username}. Fahren Sie nur fort, wenn Sie gerade in der Bulwark-App hier auf „Mit Ihrem Browser anmelden…“ geklickt haben. Wenn nicht, versucht vielleicht jemand, in Ihr Konto zu gelangen: Wählen Sie „Jetzt nicht“.",
"consent_confirm": "Bei der App anmelden",
"consent_cancel": "Jetzt nicht",
"page_done": "Sie können diesen Tab schließen und zu Bulwark zurückkehren.",
@@ -6902,7 +6902,10 @@
"page_submit": "Anmelden",
"page_wrong_password": "Der Server hat diesen Benutzernamen und dieses Passwort nicht akzeptiert.",
"page_code_needed": "Dieses Konto braucht außerdem einen Zwei-Faktor-Code. Geben Sie Ihr Passwort noch einmal und den Code ein.",
"page_no_answer": "Bulwark konnte sich nicht anmelden. Prüfen Sie, ob der Server erreichbar ist, und versuchen Sie es noch einmal."
"page_no_answer": "Bulwark konnte sich nicht anmelden. Prüfen Sie, ob der Server erreichbar ist, und versuchen Sie es noch einmal.",
"declined": "Sie haben im Browser abgelehnt, deshalb wurde nichts angemeldet.",
"too_many": "Zu viele Anmeldeversuche aus diesem Netzwerk. Warten Sie ein paar Minuten und versuchen Sie es noch einmal.",
"page_declined": "Es wurde nichts übergeben. Sie können diesen Tab schließen."
},
"desktop_updates": {
"title": "Updates",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "The browser sign-in took too long. Try again.",
"no_browser": "Bulwark could not open your browser. Try again, or sign in here.",
"failed": "Signing in through your browser did not work. Try again.",
"handoff_banner": "You are signing in to the Bulwark app on this computer. This browser stays signed out of Bulwark.",
"handoff_banner": "A program on this computer asked for this sign-in, for the Bulwark app. This browser stays signed out of Bulwark. If you didn't start this, close this tab.",
"consent_title": "Sign in to the Bulwark app?",
"consent_description": "Your sign-in for {username} goes to the Bulwark app on this computer. Continue only if you started this from the app.",
"consent_description": "A program on this computer, at port {port}, is asking for the sign-in for {username}. Continue only if you just pressed \"Sign in with your browser…\" in the Bulwark app here. If you didn't, someone may be trying to get into your account: choose Not now.",
"consent_confirm": "Sign in to the app",
"consent_cancel": "Not now",
"page_done": "You can close this tab and go back to Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Sign in",
"page_wrong_password": "The server did not accept this username and password.",
"page_code_needed": "This account also needs a two-factor code. Enter your password again and the code.",
"page_no_answer": "Bulwark could not sign in. Check that the server is reachable and try again."
"page_no_answer": "Bulwark could not sign in. Check that the server is reachable and try again.",
"declined": "You said no in your browser, so nothing was signed in.",
"too_many": "Too many sign-in attempts from this network. Wait a few minutes and try again.",
"page_declined": "Nothing was handed over. You can close this tab."
},
"desktop_updates": {
"title": "Updates",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "El inicio de sesión en el navegador tardó demasiado. Inténtalo de nuevo.",
"no_browser": "Bulwark no pudo abrir tu navegador. Inténtalo de nuevo o inicia sesión aquí.",
"failed": "No se pudo iniciar sesión a través de tu navegador. Inténtalo de nuevo.",
"handoff_banner": "Estás iniciando sesión en la aplicación Bulwark de este ordenador. Este navegador sigue sin sesión en Bulwark.",
"handoff_banner": "Un programa de este ordenador ha pedido este inicio de sesión para la aplicación Bulwark. Este navegador sigue sin sesión en Bulwark. Si no lo has iniciado tú, cierra esta pestaña.",
"consent_title": "¿Iniciar sesión en la aplicación Bulwark?",
"consent_description": "Tu inicio de sesión de {username} va a la aplicación Bulwark de este ordenador. Continúa solo si lo iniciaste desde la aplicación.",
"consent_description": "Un programa de este ordenador, en el puerto {port}, pide el inicio de sesión de {username}. Continúa solo si acabas de pulsar «Iniciar sesión con tu navegador…» en la aplicación Bulwark de aquí. Si no, puede que alguien intente entrar en tu cuenta: elige Ahora no.",
"consent_confirm": "Iniciar sesión en la aplicación",
"consent_cancel": "Ahora no",
"page_done": "Puedes cerrar esta pestaña y volver a Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Iniciar sesión",
"page_wrong_password": "El servidor no aceptó este nombre de usuario y esta contraseña.",
"page_code_needed": "Esta cuenta también necesita un código de dos factores. Escribe de nuevo tu contraseña y el código.",
"page_no_answer": "Bulwark no pudo iniciar sesión. Comprueba que el servidor esté accesible e inténtalo de nuevo."
"page_no_answer": "Bulwark no pudo iniciar sesión. Comprueba que el servidor esté accesible e inténtalo de nuevo.",
"declined": "Dijiste que no en tu navegador, así que no se inició ninguna sesión.",
"too_many": "Demasiados intentos de inicio de sesión desde esta red. Espera unos minutos e inténtalo de nuevo.",
"page_declined": "No se ha entregado nada. Puedes cerrar esta pestaña."
},
"desktop_updates": {
"title": "Actualizaciones",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Sisselogimine brauseris võttis liiga kaua aega. Proovi uuesti.",
"no_browser": "Bulwark ei saanud brauserit avada. Proovi uuesti või logi sisse siin.",
"failed": "Sisselogimine brauseri kaudu ei õnnestunud. Proovi uuesti.",
"handoff_banner": "Logid sisse selle arvuti Bulwarki rakendusse. See brauser jääb Bulwarkist välja logituks.",
"handoff_banner": "Selle arvuti programm küsis seda sisselogimist Bulwarki rakendusele. See brauser jääb Bulwarkist välja logituks. Kui sina seda ei alustanud, sulge see vaheleht.",
"consent_title": "Kas logida sisse Bulwarki rakendusse?",
"consent_description": "Konto {username} sisselogimine läheb selle arvuti Bulwarki rakendusele. Jätka ainult siis, kui alustasid seda rakendusest.",
"consent_description": "Selle arvuti programm pordil {port} küsib konto {username} sisselogimist. Jätka ainult siis, kui vajutasid just selle arvuti Bulwarki rakenduses nuppu „Logi sisse brauseriga…“. Kui mitte, võib keegi proovida sinu kontole pääseda: vali Mitte praegu.",
"consent_confirm": "Logi rakendusse sisse",
"consent_cancel": "Mitte praegu",
"page_done": "Võid selle vahelehe sulgeda ja Bulwarki naasta.",
@@ -6902,7 +6902,10 @@
"page_submit": "Logi sisse",
"page_wrong_password": "Server ei aktsepteerinud seda kasutajanime ja parooli.",
"page_code_needed": "See konto vajab ka kaheastmelise kinnituse koodi. Sisesta parool uuesti ja kood.",
"page_no_answer": "Bulwark ei saanud sisse logida. Kontrolli, kas server on kättesaadav, ja proovi uuesti."
"page_no_answer": "Bulwark ei saanud sisse logida. Kontrolli, kas server on kättesaadav, ja proovi uuesti.",
"declined": "Ütlesid brauseris ei, seega sisse ei logitud.",
"too_many": "Sellest võrgust on liiga palju sisselogimiskatseid. Oota paar minutit ja proovi uuesti.",
"page_declined": "Midagi ei antud üle. Võid selle vahelehe sulgeda."
},
"desktop_updates": {
"title": "Uuendused",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "ورود در مرورگر بیش از حد طول کشید. دوباره تلاش کنید.",
"no_browser": "Bulwark نتوانست مرورگر را باز کند. دوباره تلاش کنید یا اینجا وارد شوید.",
"failed": "ورود از طریق مرورگر انجام نشد. دوباره تلاش کنید.",
"handoff_banner": "شما در حال ورود به برنامه Bulwark روی این رایانه هستید. این مرورگر همچنان از Bulwark خارج می‌ماند.",
"handoff_banner": "برنامه‌ای روی این رایانه این ورود را برای برنامه Bulwark درخواست کرده است. این مرورگر همچنان از Bulwark خارج می‌ماند. اگر شما این کار را شروع نکرده‌اید، این زبانه را ببندید.",
"consent_title": "به برنامه Bulwark وارد می‌شوید؟",
"consent_description": "ورود {username} به برنامه Bulwark روی این رایانه می‌رود. فقط اگر این کار را از برنامه شروع کرده‌اید ادامه دهید.",
"consent_description": "برنامه‌ای روی این رایانه، در درگاه {port}، ورود {username} را درخواست می‌کند. فقط اگر همین الان «ورود با مرورگر…» را در برنامه Bulwark اینجا زده‌اید ادامه دهید. در غیر این صورت شاید کسی بخواهد وارد حساب شما شود: «اکنون نه» را انتخاب کنید.",
"consent_confirm": "ورود به برنامه",
"consent_cancel": "اکنون نه",
"page_done": "می‌توانید این زبانه را ببندید و به Bulwark برگردید.",
@@ -6902,7 +6902,10 @@
"page_submit": "ورود",
"page_wrong_password": "سرور این نام کاربری و گذرواژه را نپذیرفت.",
"page_code_needed": "این حساب به کد دومرحله‌ای هم نیاز دارد. گذرواژه و کد را دوباره وارد کنید.",
"page_no_answer": "Bulwark نتوانست وارد شود. بررسی کنید که سرور در دسترس باشد و دوباره تلاش کنید."
"page_no_answer": "Bulwark نتوانست وارد شود. بررسی کنید که سرور در دسترس باشد و دوباره تلاش کنید.",
"declined": "در مرورگر رد کردید، پس ورودی انجام نشد.",
"too_many": "تلاش‌های ورود از این شبکه بیش از حد است. چند دقیقه صبر کنید و دوباره تلاش کنید.",
"page_declined": "چیزی تحویل داده نشد. می‌توانید این زبانه را ببندید."
},
"desktop_updates": {
"title": "به‌روزرسانی‌ها",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "La connexion dans le navigateur a pris trop de temps. Réessayez.",
"no_browser": "Bulwark n’a pas pu ouvrir votre navigateur. Réessayez ou connectez-vous ici.",
"failed": "La connexion via votre navigateur n’a pas fonctionné. Réessayez.",
"handoff_banner": "Vous vous connectez à l’application Bulwark sur cet ordinateur. Ce navigateur reste déconnecté de Bulwark.",
"handoff_banner": "Un programme sur cet ordinateur a demandé cette connexion pour l’application Bulwark. Ce navigateur reste déconnecté de Bulwark. Si vous n’êtes pas à l’origine de cela, fermez cet onglet.",
"consent_title": "Se connecter à l’application Bulwark ?",
"consent_description": "Votre connexion pour {username} va à l’application Bulwark sur cet ordinateur. Continuez seulement si vous avez lancé cela depuis l’application.",
"consent_description": "Un programme sur cet ordinateur, au port {port}, demande la connexion de {username}. Continuez seulement si vous venez de cliquer sur « Se connecter avec votre navigateur… » dans l’application Bulwark ici. Sinon, quelqu’un essaie peut-être d’accéder à votre compte : choisissez Pas maintenant.",
"consent_confirm": "Se connecter à l’application",
"consent_cancel": "Pas maintenant",
"page_done": "Vous pouvez fermer cet onglet et revenir à Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Se connecter",
"page_wrong_password": "Le serveur n’a pas accepté ce nom d’utilisateur et ce mot de passe.",
"page_code_needed": "Ce compte demande aussi un code à deux facteurs. Saisissez à nouveau votre mot de passe et le code.",
"page_no_answer": "Bulwark n’a pas pu se connecter. Vérifiez que le serveur est joignable et réessayez."
"page_no_answer": "Bulwark n’a pas pu se connecter. Vérifiez que le serveur est joignable et réessayez.",
"declined": "Vous avez refusé dans votre navigateur : aucune connexion n’a été faite.",
"too_many": "Trop de tentatives de connexion depuis ce réseau. Attendez quelques minutes et réessayez.",
"page_declined": "Rien n’a été transmis. Vous pouvez fermer cet onglet."
},
"desktop_updates": {
"title": "Mises à jour",
+6 -3
View File
@@ -6887,9 +6887,9 @@
"timed_out": "ההתחברות בדפדפן נמשכה זמן רב מדי. נסו שוב.",
"no_browser": "Bulwark לא הצליח לפתוח את הדפדפן. נסו שוב או התחברו כאן.",
"failed": "ההתחברות דרך הדפדפן לא הצליחה. נסו שוב.",
"handoff_banner": "אתם מתחברים לאפליקציית Bulwark במחשב זה. הדפדפן הזה נשאר מנותק מ-Bulwark.",
"handoff_banner": "תוכנה במחשב זה ביקשה את ההתחברות הזו עבור אפליקציית Bulwark. הדפדפן הזה נשאר מנותק מ-Bulwark. אם לא אתם התחלתם את זה, סגרו את הכרטיסייה.",
"consent_title": "להתחבר לאפליקציית Bulwark?",
"consent_description": "ההתחברות של {username} תועבר לאפליקציית Bulwark במחשב זה. המשיכו רק אם התחלתם זאת מהאפליקציה.",
"consent_description": "תוכנה במחשב זה, בפורט {port}, מבקשת את ההתחברות של {username}. המשיכו רק אם לחצתם עכשיו על \"התחברות דרך הדפדפן…\" באפליקציית Bulwark כאן. אם לא, ייתכן שמישהו מנסה להיכנס לחשבון שלכם: בחרו \"לא עכשיו\".",
"consent_confirm": "התחברות לאפליקציה",
"consent_cancel": "לא עכשיו",
"page_done": "אפשר לסגור את הכרטיסייה הזו ולחזור ל-Bulwark.",
@@ -6903,7 +6903,10 @@
"page_submit": "התחברות",
"page_wrong_password": "השרת לא קיבל את שם המשתמש והסיסמה האלה.",
"page_code_needed": "החשבון הזה צריך גם קוד אימות דו-שלבי. הזינו שוב את הסיסמה ואת הקוד.",
"page_no_answer": "Bulwark לא הצליח להתחבר. בדקו שהשרת זמין ונסו שוב."
"page_no_answer": "Bulwark לא הצליח להתחבר. בדקו שהשרת זמין ונסו שוב.",
"declined": "סירבתם בדפדפן, ולכן לא בוצעה התחברות.",
"too_many": "יותר מדי ניסיונות התחברות מהרשת הזו. המתינו כמה דקות ונסו שוב.",
"page_declined": "שום דבר לא הועבר. אפשר לסגור את הכרטיסייה."
},
"desktop_updates": {
"title": "עדכונים",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "A böngészős bejelentkezés túl sokáig tartott. Próbálja újra.",
"no_browser": "A Bulwark nem tudta megnyitni a böngészőt. Próbálja újra, vagy jelentkezzen be itt.",
"failed": "A böngészőn keresztüli bejelentkezés nem sikerült. Próbálja újra.",
"handoff_banner": "A számítógépen lévő Bulwark alkalmazásba jelentkezik be. Ez a böngésző kijelentkezve marad a Bulwarkból.",
"handoff_banner": "A számítógépen egy program kérte ezt a bejelentkezést a Bulwark alkalmazáshoz. Ez a böngésző kijelentkezve marad a Bulwarkból. Ha nem Ön indította, zárja be ezt a lapot.",
"consent_title": "Bejelentkezik a Bulwark alkalmazásba?",
"consent_description": "A(z) {username} bejelentkezése a számítógépen lévő Bulwark alkalmazáshoz kerül. Csak akkor folytassa, ha az alkalmazásból indította.",
"consent_description": "A számítógépen egy program a(z) {port} porton a(z) {username} bejelentkezését kéri. Csak akkor folytassa, ha az imént nyomta meg a „Bejelentkezés a böngészővel…” gombot az itteni Bulwark alkalmazásban. Ha nem, lehet, hogy valaki be akar jutni a fiókjába: válassza a Most nem lehetőséget.",
"consent_confirm": "Bejelentkezés az alkalmazásba",
"consent_cancel": "Most nem",
"page_done": "Bezárhatja ezt a lapot, és visszatérhet a Bulwarkhoz.",
@@ -6902,7 +6902,10 @@
"page_submit": "Bejelentkezés",
"page_wrong_password": "A szerver nem fogadta el ezt a felhasználónevet és jelszót.",
"page_code_needed": "Ehhez a fiókhoz kétfaktoros kód is kell. Adja meg újra a jelszavát és a kódot.",
"page_no_answer": "A Bulwark nem tudott bejelentkezni. Ellenőrizze, hogy a szerver elérhető-e, és próbálja újra."
"page_no_answer": "A Bulwark nem tudott bejelentkezni. Ellenőrizze, hogy a szerver elérhető-e, és próbálja újra.",
"declined": "A böngészőben nemet mondott, így nem történt bejelentkezés.",
"too_many": "Túl sok bejelentkezési kísérlet erről a hálózatról. Várjon néhány percet, és próbálja újra.",
"page_declined": "Semmi nem került átadásra. Bezárhatja ezt a lapot."
},
"desktop_updates": {
"title": "Frissítések",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "L’accesso nel browser ha richiesto troppo tempo. Riprova.",
"no_browser": "Bulwark non è riuscito ad aprire il browser. Riprova o accedi qui.",
"failed": "L’accesso tramite il browser non è riuscito. Riprova.",
"handoff_banner": "Stai accedendo all’app Bulwark su questo computer. Questo browser resta disconnesso da Bulwark.",
"handoff_banner": "Un programma su questo computer ha chiesto questo accesso per l’app Bulwark. Questo browser resta disconnesso da Bulwark. Se non sei stato tu ad avviarlo, chiudi questa scheda.",
"consent_title": "Accedere all’app Bulwark?",
"consent_description": "Il tuo accesso per {username} va all’app Bulwark su questo computer. Continua solo se lo hai avviato dall’app.",
"consent_description": "Un programma su questo computer, alla porta {port}, chiede l’accesso per {username}. Continua solo se hai appena premuto «Accedi con il browser…» nell’app Bulwark qui. Altrimenti qualcuno potrebbe cercare di entrare nel tuo account: scegli Non ora.",
"consent_confirm": "Accedi all’app",
"consent_cancel": "Non ora",
"page_done": "Puoi chiudere questa scheda e tornare a Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Accedi",
"page_wrong_password": "Il server non ha accettato questo nome utente e questa password.",
"page_code_needed": "Questo account richiede anche un codice a due fattori. Inserisci di nuovo la password e il codice.",
"page_no_answer": "Bulwark non è riuscito ad accedere. Verifica che il server sia raggiungibile e riprova."
"page_no_answer": "Bulwark non è riuscito ad accedere. Verifica che il server sia raggiungibile e riprova.",
"declined": "Hai detto no nel browser, quindi non è stato effettuato alcun accesso.",
"too_many": "Troppi tentativi di accesso da questa rete. Attendi qualche minuto e riprova.",
"page_declined": "Non è stato consegnato nulla. Puoi chiudere questa scheda."
},
"desktop_updates": {
"title": "Aggiornamenti",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "ブラウザーでのサインインに時間がかかりすぎました。もう一度お試しください。",
"no_browser": "Bulwark はブラウザーを開けませんでした。もう一度試すか、ここでサインインしてください。",
"failed": "ブラウザー経由でサインインできませんでした。もう一度お試しください。",
"handoff_banner": "このコンピューターの Bulwark アプリにサインインしています。このブラウザーは Bulwark にサインインしません。",
"handoff_banner": "このコンピューターのプログラムが Bulwark アプリのためにこのサインインを求めました。このブラウザーは Bulwark にサインインしません。自分で始めたのでなければ、このタブを閉じてください。",
"consent_title": "Bulwark アプリにサインインしますか?",
"consent_description": "{username} のサインインは、このコンピューターの Bulwark アプリに渡されます。アプリから始めた場合のみ続行してください。",
"consent_description": "このコンピューターのポート {port} のプログラムが、{username} のサインインを求めています。ここの Bulwark アプリで「ブラウザーでサインイン…」を押したばかりの場合のみ続行してください。そうでない場合は、誰かがアカウントに入ろうとしている可能性があります。「今はしない」を選んでください。",
"consent_confirm": "アプリにサインイン",
"consent_cancel": "今はしない",
"page_done": "このタブを閉じて Bulwark に戻れます。",
@@ -6902,7 +6902,10 @@
"page_submit": "サインイン",
"page_wrong_password": "サーバーはこのユーザー名とパスワードを受け付けませんでした。",
"page_code_needed": "このアカウントには 2 要素認証コードも必要です。パスワードをもう一度入力し、コードも入力してください。",
"page_no_answer": "Bulwark はサインインできませんでした。サーバーに接続できるか確認して、もう一度お試しください。"
"page_no_answer": "Bulwark はサインインできませんでした。サーバーに接続できるか確認して、もう一度お試しください。",
"declined": "ブラウザーで断ったため、サインインしていません。",
"too_many": "このネットワークからのサインインの試行が多すぎます。数分待ってからもう一度お試しください。",
"page_declined": "何も渡していません。このタブを閉じてかまいません。"
},
"desktop_updates": {
"title": "アップデート",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "브라우저 로그인이 너무 오래 걸렸습니다. 다시 시도하세요.",
"no_browser": "Bulwark에서 브라우저를 열 수 없습니다. 다시 시도하거나 여기에서 로그인하세요.",
"failed": "브라우저를 통한 로그인에 실패했습니다. 다시 시도하세요.",
"handoff_banner": "이 컴퓨터의 Bulwark 앱에 로그인하고 있습니다. 이 브라우저는 Bulwark에 로그인되지 않습니다.",
"handoff_banner": "이 컴퓨터의 프로그램이 Bulwark 앱을 위해 이 로그인을 요청했습니다. 이 브라우저는 Bulwark에 로그인되지 않습니다. 직접 시작하지 않았다면 이 탭을 닫으세요.",
"consent_title": "Bulwark 앱에 로그인할까요?",
"consent_description": "{username}의 로그인 정보가 이 컴퓨터의 Bulwark 앱으로 전달됩니다. 앱에서 시작한 경우에만 계속하세요.",
"consent_description": "이 컴퓨터의 포트 {port}에 있는 프로그램이 {username}의 로그인을 요청하고 있습니다. 이 컴퓨터의 Bulwark 앱에서 방금 \"브라우저로 로그인…\"을 눌렀을 때만 계속하세요. 그렇지 않다면 누군가 계정에 들어가려는 것일 수 있습니다. \"나중에\"를 선택하세요.",
"consent_confirm": "앱에 로그인",
"consent_cancel": "나중에",
"page_done": "이 탭을 닫고 Bulwark로 돌아가도 됩니다.",
@@ -6902,7 +6902,10 @@
"page_submit": "로그인",
"page_wrong_password": "서버가 이 사용자 이름과 비밀번호를 받아들이지 않았습니다.",
"page_code_needed": "이 계정에는 2단계 인증 코드도 필요합니다. 비밀번호와 코드를 다시 입력하세요.",
"page_no_answer": "Bulwark에서 로그인할 수 없습니다. 서버에 연결할 수 있는지 확인하고 다시 시도하세요."
"page_no_answer": "Bulwark에서 로그인할 수 없습니다. 서버에 연결할 수 있는지 확인하고 다시 시도하세요.",
"declined": "브라우저에서 거절하여 로그인하지 않았습니다.",
"too_many": "이 네트워크에서 로그인 시도가 너무 많습니다. 몇 분 기다린 후 다시 시도하세요.",
"page_declined": "아무것도 전달되지 않았습니다. 이 탭을 닫아도 됩니다."
},
"desktop_updates": {
"title": "업데이트",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Pieteikšanās pārlūkā aizņēma pārāk ilgu laiku. Mēģiniet vēlreiz.",
"no_browser": "Bulwark nevarēja atvērt pārlūku. Mēģiniet vēlreiz vai piesakieties šeit.",
"failed": "Pieteikšanās caur pārlūku neizdevās. Mēģiniet vēlreiz.",
"handoff_banner": "Jūs piesakāties Bulwark lietotnē šajā datorā. Šis pārlūks paliek izrakstīts no Bulwark.",
"handoff_banner": "Programma šajā datorā pieprasīja šo pieteikšanos Bulwark lietotnei. Šis pārlūks paliek izrakstīts no Bulwark. Ja to nesākāt jūs, aizveriet šo cilni.",
"consent_title": "Pieteikties Bulwark lietotnē?",
"consent_description": "Jūsu pieteikšanās kontam {username} tiek nodota Bulwark lietotnei šajā datorā. Turpiniet tikai tad, ja to sākāt no lietotnes.",
"consent_description": "Programma šajā datorā, portā {port}, prasa pieteikšanos kontam {username}. Turpiniet tikai tad, ja tikko nospiedāt “Pieteikties ar pārlūku…” Bulwark lietotnē šajā datorā. Ja nē, iespējams, kāds mēģina piekļūt jūsu kontam: izvēlieties Ne tagad.",
"consent_confirm": "Pieteikties lietotnē",
"consent_cancel": "Ne tagad",
"page_done": "Varat aizvērt šo cilni un atgriezties Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Pieteikties",
"page_wrong_password": "Serveris nepieņēma šo lietotājvārdu un paroli.",
"page_code_needed": "Šim kontam vajag arī divu faktoru kodu. Ievadiet paroli vēlreiz un kodu.",
"page_no_answer": "Bulwark nevarēja pieteikties. Pārbaudiet, vai serveris ir sasniedzams, un mēģiniet vēlreiz."
"page_no_answer": "Bulwark nevarēja pieteikties. Pārbaudiet, vai serveris ir sasniedzams, un mēģiniet vēlreiz.",
"declined": "Jūs pārlūkā atteicāt, tāpēc pieteikšanās nenotika.",
"too_many": "Pārāk daudz pieteikšanās mēģinājumu no šī tīkla. Pagaidiet dažas minūtes un mēģiniet vēlreiz.",
"page_declined": "Nekas netika nodots. Varat aizvērt šo cilni."
},
"desktop_updates": {
"title": "Atjauninājumi",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Хөтчөөр нэвтрэх хэт удаан үргэлжилсэн. Дахин оролдоно уу.",
"no_browser": "Bulwark хөтчийг нээж чадсангүй. Дахин оролдох эсвэл энд нэвтэрнэ үү.",
"failed": "Хөтчөөр нэвтэрч чадсангүй. Дахин оролдоно уу.",
"handoff_banner": "Та энэ компьютер дээрх Bulwark апп руу нэвтэрч байна. Энэ хөтөч Bulwark-д нэвтрэхгүй хэвээр үлдэнэ.",
"handoff_banner": "Энэ компьютерийн програм Bulwark апп-д зориулж энэ нэвтрэлтийг хүссэн. Энэ хөтөч Bulwark-д нэвтрэхгүй хэвээр үлдэнэ. Та эхлүүлээгүй бол энэ табыг хаана уу.",
"consent_title": "Bulwark апп руу нэвтрэх үү?",
"consent_description": "{username}-ийн нэвтрэлт энэ компьютер дээрх Bulwark апп руу очно. Зөвхөн аппаас эхлүүлсэн бол үргэлжлүүлнэ үү.",
"consent_description": "Энэ компьютерийн {port} порт дээрх програм {username}-ийн нэвтрэлтийг хүсэж байна. Та дөнгөж сая энд байгаа Bulwark апп дээр \"Хөтчөөрөө нэвтрэх…\" дарсан бол л үргэлжлүүлнэ үү. Үгүй бол хэн нэгэн таны бүртгэлд орох гэж оролдож магадгүй: \"Одоо биш\"-ийг сонгоно уу.",
"consent_confirm": "Апп руу нэвтрэх",
"consent_cancel": "Одоо биш",
"page_done": "Энэ табыг хааж Bulwark руу буцаж болно.",
@@ -6902,7 +6902,10 @@
"page_submit": "Нэвтрэх",
"page_wrong_password": "Сервер энэ хэрэглэгчийн нэр, нууц үгийг хүлээн авсангүй.",
"page_code_needed": "Энэ бүртгэлд хоёр шатлалт код бас хэрэгтэй. Нууц үг болон кодоо дахин оруулна уу.",
"page_no_answer": "Bulwark нэвтэрч чадсангүй. Сервер холбогдох боломжтой эсэхийг шалгаад дахин оролдоно уу."
"page_no_answer": "Bulwark нэвтэрч чадсангүй. Сервер холбогдох боломжтой эсэхийг шалгаад дахин оролдоно уу.",
"declined": "Та хөтөч дээр татгалзсан тул нэвтрээгүй.",
"too_many": "Энэ сүлжээнээс хэт олон удаа нэвтрэхийг оролдсон байна. Хэдэн минут хүлээгээд дахин оролдоно уу.",
"page_declined": "Юу ч шилжүүлээгүй. Энэ табыг хааж болно."
},
"desktop_updates": {
"title": "Шинэчлэлт",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Innloggingen i nettleseren tok for lang tid. Prøv igjen.",
"no_browser": "Bulwark kunne ikke åpne nettleseren. Prøv igjen, eller logg inn her.",
"failed": "Innlogging via nettleseren virket ikke. Prøv igjen.",
"handoff_banner": "Du logger inn i Bulwark-appen på denne datamaskinen. Denne nettleseren forblir logget ut av Bulwark.",
"handoff_banner": "Et program på denne datamaskinen ba om denne innloggingen for Bulwark-appen. Denne nettleseren forblir logget ut av Bulwark. Hvis du ikke startet dette, lukk denne fanen.",
"consent_title": "Logge inn i Bulwark-appen?",
"consent_description": "Innloggingen din for {username} går til Bulwark-appen på denne datamaskinen. Fortsett bare hvis du startet dette fra appen.",
"consent_description": "Et program på denne datamaskinen, på port {port}, ber om innloggingen for {username}. Fortsett bare hvis du nettopp trykket på «Logg inn med nettleseren…» i Bulwark-appen her. Hvis ikke, prøver kanskje noen å komme inn på kontoen din: velg Ikke nå.",
"consent_confirm": "Logg inn i appen",
"consent_cancel": "Ikke nå",
"page_done": "Du kan lukke denne fanen og gå tilbake til Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Logg inn",
"page_wrong_password": "Serveren godtok ikke dette brukernavnet og passordet.",
"page_code_needed": "Denne kontoen trenger også en tofaktorkode. Skriv inn passordet på nytt og koden.",
"page_no_answer": "Bulwark kunne ikke logge inn. Sjekk at serveren kan nås, og prøv igjen."
"page_no_answer": "Bulwark kunne ikke logge inn. Sjekk at serveren kan nås, og prøv igjen.",
"declined": "Du sa nei i nettleseren, så ingenting ble logget inn.",
"too_many": "For mange innloggingsforsøk fra dette nettverket. Vent noen minutter og prøv igjen.",
"page_declined": "Ingenting ble overlevert. Du kan lukke denne fanen."
},
"desktop_updates": {
"title": "Oppdateringer",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Inloggen in de browser duurde te lang. Probeer het opnieuw.",
"no_browser": "Bulwark kon je browser niet openen. Probeer het opnieuw of log hier in.",
"failed": "Inloggen via je browser is niet gelukt. Probeer het opnieuw.",
"handoff_banner": "Je logt in bij de Bulwark-app op deze computer. Deze browser blijft uitgelogd bij Bulwark.",
"handoff_banner": "Een programma op deze computer heeft om deze aanmelding gevraagd voor de Bulwark-app. Deze browser blijft uitgelogd bij Bulwark. Heb je dit niet gestart, sluit dan dit tabblad.",
"consent_title": "Inloggen bij de Bulwark-app?",
"consent_description": "Je aanmelding voor {username} gaat naar de Bulwark-app op deze computer. Ga alleen verder als je dit vanuit de app hebt gestart.",
"consent_description": "Een programma op deze computer, op poort {port}, vraagt om de aanmelding van {username}. Ga alleen verder als je zojuist op \"Inloggen met je browser…\" hebt geklikt in de Bulwark-app hier. Zo niet, dan probeert iemand misschien in je account te komen: kies Niet nu.",
"consent_confirm": "Inloggen bij de app",
"consent_cancel": "Niet nu",
"page_done": "Je kunt dit tabblad sluiten en teruggaan naar Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Inloggen",
"page_wrong_password": "De server heeft deze gebruikersnaam en dit wachtwoord niet geaccepteerd.",
"page_code_needed": "Dit account heeft ook een tweefactorcode nodig. Voer je wachtwoord opnieuw in en de code.",
"page_no_answer": "Bulwark kon niet inloggen. Controleer of de server bereikbaar is en probeer het opnieuw."
"page_no_answer": "Bulwark kon niet inloggen. Controleer of de server bereikbaar is en probeer het opnieuw.",
"declined": "Je hebt in je browser nee gezegd, dus er is niet ingelogd.",
"too_many": "Te veel inlogpogingen vanaf dit netwerk. Wacht een paar minuten en probeer het opnieuw.",
"page_declined": "Er is niets overgedragen. Je kunt dit tabblad sluiten."
},
"desktop_updates": {
"title": "Updates",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Logowanie w przeglądarce trwało zbyt długo. Spróbuj ponownie.",
"no_browser": "Bulwark nie może otworzyć przeglądarki. Spróbuj ponownie lub zaloguj się tutaj.",
"failed": "Logowanie przez przeglądarkę nie powiodło się. Spróbuj ponownie.",
"handoff_banner": "Logujesz się w aplikacji Bulwark na tym komputerze. Ta przeglądarka pozostaje wylogowana z Bulwark.",
"handoff_banner": "Program na tym komputerze poprosił o to logowanie dla aplikacji Bulwark. Ta przeglądarka pozostaje wylogowana z Bulwark. Jeśli to nie Ty, zamknij tę kartę.",
"consent_title": "Zalogować się w aplikacji Bulwark?",
"consent_description": "Twoje logowanie dla {username} trafi do aplikacji Bulwark na tym komputerze. Kontynuuj tylko wtedy, gdy rozpoczęto je w aplikacji.",
"consent_description": "Program na tym komputerze, na porcie {port}, prosi o logowanie dla {username}. Kontynuuj tylko wtedy, gdy przed chwilą kliknięto „Zaloguj się w przeglądarce…” w aplikacji Bulwark na tym komputerze. Jeśli nie, ktoś może próbować dostać się na Twoje konto: wybierz Nie teraz.",
"consent_confirm": "Zaloguj się w aplikacji",
"consent_cancel": "Nie teraz",
"page_done": "Możesz zamknąć tę kartę i wrócić do Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Zaloguj się",
"page_wrong_password": "Serwer nie przyjął tej nazwy użytkownika i hasła.",
"page_code_needed": "To konto wymaga też kodu dwuskładnikowego. Wpisz ponownie hasło i kod.",
"page_no_answer": "Bulwark nie może się zalogować. Sprawdź, czy serwer jest dostępny, i spróbuj ponownie."
"page_no_answer": "Bulwark nie może się zalogować. Sprawdź, czy serwer jest dostępny, i spróbuj ponownie.",
"declined": "Odmówiono w przeglądarce, więc nic nie zostało zalogowane.",
"too_many": "Zbyt wiele prób logowania z tej sieci. Poczekaj kilka minut i spróbuj ponownie.",
"page_declined": "Nic nie zostało przekazane. Możesz zamknąć tę kartę."
},
"desktop_updates": {
"title": "Aktualizacje",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "A entrada no navegador demorou demasiado. Tente novamente.",
"no_browser": "O Bulwark não conseguiu abrir o navegador. Tente novamente ou entre aqui.",
"failed": "Não foi possível entrar através do navegador. Tente novamente.",
"handoff_banner": "Está a entrar na aplicação Bulwark neste computador. Este navegador continua sem sessão no Bulwark.",
"handoff_banner": "Um programa neste computador pediu esta sessão para a aplicação Bulwark. Este navegador continua sem sessão no Bulwark. Se não foi você que iniciou isto, feche este separador.",
"consent_title": "Entrar na aplicação Bulwark?",
"consent_description": "A sua sessão de {username} vai para a aplicação Bulwark neste computador. Continue só se tiver iniciado isto na aplicação.",
"consent_description": "Um programa neste computador, na porta {port}, está a pedir a sessão de {username}. Continue só se acabou de carregar em «Entrar com o navegador…» na aplicação Bulwark aqui. Caso contrário, alguém pode estar a tentar entrar na sua conta: escolha Agora não.",
"consent_confirm": "Entrar na aplicação",
"consent_cancel": "Agora não",
"page_done": "Pode fechar este separador e voltar ao Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Entrar",
"page_wrong_password": "O servidor não aceitou este nome de utilizador e esta palavra-passe.",
"page_code_needed": "Esta conta também precisa de um código de dois fatores. Introduza novamente a palavra-passe e o código.",
"page_no_answer": "O Bulwark não conseguiu entrar. Verifique se o servidor está acessível e tente novamente."
"page_no_answer": "O Bulwark não conseguiu entrar. Verifique se o servidor está acessível e tente novamente.",
"declined": "Disse que não no navegador, por isso não foi iniciada nenhuma sessão.",
"too_many": "Demasiadas tentativas de entrada a partir desta rede. Aguarde alguns minutos e tente novamente.",
"page_declined": "Nada foi entregue. Pode fechar este separador."
},
"desktop_updates": {
"title": "Atualizações",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Conectarea în browser a durat prea mult. Încercați din nou.",
"no_browser": "Bulwark nu a putut deschide browserul. Încercați din nou sau conectați-vă aici.",
"failed": "Conectarea prin browser nu a reușit. Încercați din nou.",
"handoff_banner": "Vă conectați la aplicația Bulwark de pe acest computer. Acest browser rămâne deconectat de la Bulwark.",
"handoff_banner": "Un program de pe acest computer a cerut această conectare pentru aplicația Bulwark. Acest browser rămâne deconectat de la Bulwark. Dacă nu ați pornit dvs. acest lucru, închideți această filă.",
"consent_title": "Vă conectați la aplicația Bulwark?",
"consent_description": "Conectarea pentru {username} merge la aplicația Bulwark de pe acest computer. Continuați doar dacă ați pornit acest lucru din aplicație.",
"consent_description": "Un program de pe acest computer, la portul {port}, cere conectarea pentru {username}. Continuați doar dacă tocmai ați apăsat „Conectați-vă cu browserul…” în aplicația Bulwark de aici. Dacă nu, poate cineva încearcă să intre în contul dvs.: alegeți Nu acum.",
"consent_confirm": "Conectați-vă la aplicație",
"consent_cancel": "Nu acum",
"page_done": "Puteți închide această filă și reveni la Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Conectați-vă",
"page_wrong_password": "Serverul nu a acceptat acest nume de utilizator și această parolă.",
"page_code_needed": "Acest cont are nevoie și de un cod cu doi factori. Introduceți din nou parola și codul.",
"page_no_answer": "Bulwark nu s-a putut conecta. Verificați dacă serverul este accesibil și încercați din nou."
"page_no_answer": "Bulwark nu s-a putut conecta. Verificați dacă serverul este accesibil și încercați din nou.",
"declined": "Ați refuzat în browser, așa că nu s-a făcut nicio conectare.",
"too_many": "Prea multe încercări de conectare din această rețea. Așteptați câteva minute și încercați din nou.",
"page_declined": "Nu s-a transmis nimic. Puteți închide această filă."
},
"desktop_updates": {
"title": "Actualizări",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Вход через браузер занял слишком много времени. Попробуйте ещё раз.",
"no_browser": "Bulwark не смог открыть браузер. Попробуйте ещё раз или войдите здесь.",
"failed": "Не удалось войти через браузер. Попробуйте ещё раз.",
"handoff_banner": "Вы входите в приложение Bulwark на этом компьютере. В этом браузере вход в Bulwark не выполняется.",
"handoff_banner": "Программа на этом компьютере запросила этот вход для приложения Bulwark. В этом браузере вход в Bulwark не выполняется. Если это начали не вы, закройте вкладку.",
"consent_title": "Войти в приложение Bulwark?",
"consent_description": "Ваш вход для {username} будет передан приложению Bulwark на этом компьютере. Продолжайте, только если начали это из приложения.",
"consent_description": "Программа на этом компьютере, на порту {port}, запрашивает вход для {username}. Продолжайте, только если вы только что нажали «Войти через браузер…» в приложении Bulwark на этом компьютере. Если нет, возможно, кто-то пытается попасть в вашу учётную запись: выберите «Не сейчас».",
"consent_confirm": "Войти в приложение",
"consent_cancel": "Не сейчас",
"page_done": "Можно закрыть эту вкладку и вернуться в Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Войти",
"page_wrong_password": "Сервер не принял это имя пользователя и пароль.",
"page_code_needed": "Для этой учётной записи также нужен двухфакторный код. Введите пароль ещё раз и код.",
"page_no_answer": "Bulwark не смог войти. Проверьте, доступен ли сервер, и попробуйте ещё раз."
"page_no_answer": "Bulwark не смог войти. Проверьте, доступен ли сервер, и попробуйте ещё раз.",
"declined": "Вы отказали в браузере, поэтому вход не выполнен.",
"too_many": "Слишком много попыток входа из этой сети. Подождите несколько минут и попробуйте ещё раз.",
"page_declined": "Ничего не передано. Можно закрыть эту вкладку."
},
"desktop_updates": {
"title": "Обновления",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Prihlásenie v prehliadači trvalo príliš dlho. Skúste to znova.",
"no_browser": "Bulwark nemohol otvoriť prehliadač. Skúste to znova alebo sa prihláste tu.",
"failed": "Prihlásenie cez prehliadač sa nepodarilo. Skúste to znova.",
"handoff_banner": "Prihlasujete sa do aplikácie Bulwark v tomto počítači. Tento prehliadač zostane z Bulwarku odhlásený.",
"handoff_banner": "Program v tomto počítači požiadal o toto prihlásenie pre aplikáciu Bulwark. Tento prehliadač zostane z Bulwarku odhlásený. Ak ste to nespustili vy, zavrite túto kartu.",
"consent_title": "Prihlásiť sa do aplikácie Bulwark?",
"consent_description": "Vaše prihlásenie pre {username} pôjde do aplikácie Bulwark v tomto počítači. Pokračujte, len ak ste to spustili z aplikácie.",
"consent_description": "Program v tomto počítači, na porte {port}, žiada o prihlásenie pre {username}. Pokračujte, len ak ste práve klikli na „Prihlásiť sa v prehliadači…“ v aplikácii Bulwark v tomto počítači. Ak nie, možno sa niekto snaží dostať do vášho účtu: zvoľte Teraz nie.",
"consent_confirm": "Prihlásiť sa do aplikácie",
"consent_cancel": "Teraz nie",
"page_done": "Túto kartu môžete zavrieť a vrátiť sa do Bulwarku.",
@@ -6902,7 +6902,10 @@
"page_submit": "Prihlásiť sa",
"page_wrong_password": "Server toto používateľské meno a heslo neprijal.",
"page_code_needed": "Tento účet potrebuje aj dvojfaktorový kód. Zadajte znova heslo a kód.",
"page_no_answer": "Bulwark sa nemohol prihlásiť. Skontrolujte, či je server dostupný, a skúste to znova."
"page_no_answer": "Bulwark sa nemohol prihlásiť. Skontrolujte, či je server dostupný, a skúste to znova.",
"declined": "V prehliadači ste odmietli, takže k prihláseniu nedošlo.",
"too_many": "Príliš veľa pokusov o prihlásenie z tejto siete. Počkajte niekoľko minút a skúste to znova.",
"page_declined": "Nič nebolo odovzdané. Túto kartu môžete zavrieť."
},
"desktop_updates": {
"title": "Aktualizácie",
+6 -3
View File
@@ -6894,9 +6894,9 @@
"timed_out": "การลงชื่อเข้าใช้ในเบราว์เซอร์ใช้เวลานานเกินไป ลองอีกครั้ง",
"no_browser": "Bulwark เปิดเบราว์เซอร์ไม่ได้ ลองอีกครั้งหรือลงชื่อเข้าใช้ที่นี่",
"failed": "ลงชื่อเข้าใช้ผ่านเบราว์เซอร์ไม่สำเร็จ ลองอีกครั้ง",
"handoff_banner": "คุณกำลังลงชื่อเข้าใช้แอป Bulwark บนคอมพิวเตอร์เครื่องนี้ เบราว์เซอร์นี้จะยังไม่ได้ลงชื่อเข้าใช้ Bulwark",
"handoff_banner": "โปรแกรมบนคอมพิวเตอร์เครื่องนี้ขอการลงชื่อเข้าใช้นี้สำหรับแอป Bulwark เบราว์เซอร์นี้จะยังไม่ได้ลงชื่อเข้าใช้ Bulwark หากคุณไม่ได้เริ่มเอง ให้ปิดแท็บนี้",
"consent_title": "ลงชื่อเข้าใช้แอป Bulwark หรือไม่",
"consent_description": "การลงชื่อเข้าใช้ของ {username} จะส่งไปยังแอป Bulwark บนคอมพิวเตอร์เครื่องนี้ ดำเนินการต่อเฉพาะเมื่อคุณเริ่มจากแอปเท่านั้น",
"consent_description": "โปรแกรมบนคอมพิวเตอร์เครื่องนี้ที่พอร์ต {port} กำลังขอการลงชื่อเข้าใช้ของ {username} ดำเนินการต่อเฉพาะเมื่อคุณเพิ่งกด \"ลงชื่อเข้าใช้ด้วยเบราว์เซอร์…\" ในแอป Bulwark บนเครื่องนี้ หากไม่ได้กด อาจมีคนพยายามเข้าบัญชีของคุณ ให้เลือก ไม่ใช่ตอนนี้",
"consent_confirm": "ลงชื่อเข้าใช้แอป",
"consent_cancel": "ไม่ใช่ตอนนี้",
"page_done": "คุณปิดแท็บนี้และกลับไปที่ Bulwark ได้",
@@ -6910,7 +6910,10 @@
"page_submit": "ลงชื่อเข้าใช้",
"page_wrong_password": "เซิร์ฟเวอร์ไม่ยอมรับชื่อผู้ใช้และรหัสผ่านนี้",
"page_code_needed": "บัญชีนี้ต้องใช้รหัสสองปัจจัยด้วย ป้อนรหัสผ่านอีกครั้งพร้อมรหัส",
"page_no_answer": "Bulwark ลงชื่อเข้าใช้ไม่ได้ ตรวจสอบว่าเข้าถึงเซิร์ฟเวอร์ได้แล้วลองอีกครั้ง"
"page_no_answer": "Bulwark ลงชื่อเข้าใช้ไม่ได้ ตรวจสอบว่าเข้าถึงเซิร์ฟเวอร์ได้แล้วลองอีกครั้ง",
"declined": "คุณปฏิเสธในเบราว์เซอร์ จึงไม่มีการลงชื่อเข้าใช้",
"too_many": "มีการพยายามลงชื่อเข้าใช้จากเครือข่ายนี้มากเกินไป รอสักครู่แล้วลองอีกครั้ง",
"page_declined": "ไม่มีการส่งมอบสิ่งใด คุณปิดแท็บนี้ได้"
},
"desktop_updates": {
"title": "การอัปเดต",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Tarayıcıda oturum açma çok uzun sürdü. Yeniden deneyin.",
"no_browser": "Bulwark tarayıcınızı açamadı. Yeniden deneyin veya burada oturum açın.",
"failed": "Tarayıcınız üzerinden oturum açılamadı. Yeniden deneyin.",
"handoff_banner": "Bu bilgisayardaki Bulwark uygulamasında oturum açıyorsunuz. Bu tarayıcı Bulwark’ta oturum kapalı kalır.",
"handoff_banner": "Bu bilgisayardaki bir program bu oturum açmayı Bulwark uygulaması için istedi. Bu tarayıcı Bulwark’ta oturum kapalı kalır. Bunu siz başlatmadıysanız bu sekmeyi kapatın.",
"consent_title": "Bulwark uygulamasında oturum açılsın mı?",
"consent_description": "{username} için oturum açma bilginiz bu bilgisayardaki Bulwark uygulamasına gider. Yalnızca bunu uygulamadan başlattıysanız devam edin.",
"consent_description": "Bu bilgisayardaki bir program, {port} bağlantı noktasında, {username} için oturum açma bilgisini istiyor. Yalnızca buradaki Bulwark uygulamasında az önce \"Tarayıcınızla oturum açın…\" düğmesine bastıysanız devam edin. Basmadıysanız biri hesabınıza girmeye çalışıyor olabilir: Şimdi değil seçeneğini seçin.",
"consent_confirm": "Uygulamada oturum aç",
"consent_cancel": "Şimdi değil",
"page_done": "Bu sekmeyi kapatıp Bulwark’a dönebilirsiniz.",
@@ -6902,7 +6902,10 @@
"page_submit": "Oturum aç",
"page_wrong_password": "Sunucu bu kullanıcı adını ve parolayı kabul etmedi.",
"page_code_needed": "Bu hesap ayrıca iki aşamalı kod istiyor. Parolanızı ve kodu yeniden girin.",
"page_no_answer": "Bulwark oturum açamadı. Sunucunun erişilebilir olduğunu denetleyin ve yeniden deneyin."
"page_no_answer": "Bulwark oturum açamadı. Sunucunun erişilebilir olduğunu denetleyin ve yeniden deneyin.",
"declined": "Tarayıcınızda hayır dediniz, bu yüzden oturum açılmadı.",
"too_many": "Bu ağdan çok fazla oturum açma denemesi yapıldı. Birkaç dakika bekleyip yeniden deneyin.",
"page_declined": "Hiçbir şey aktarılmadı. Bu sekmeyi kapatabilirsiniz."
},
"desktop_updates": {
"title": "Güncellemeler",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "Вхід через браузер тривав надто довго. Спробуйте ще раз.",
"no_browser": "Bulwark не зміг відкрити браузер. Спробуйте ще раз або увійдіть тут.",
"failed": "Не вдалося увійти через браузер. Спробуйте ще раз.",
"handoff_banner": "Ви входите в застосунок Bulwark на цьому комп’ютері. У цьому браузері вхід у Bulwark не виконується.",
"handoff_banner": "Програма на цьому комп’ютері запитала цей вхід для застосунку Bulwark. У цьому браузері вхід у Bulwark не виконується. Якщо це почали не ви, закрийте вкладку.",
"consent_title": "Увійти в застосунок Bulwark?",
"consent_description": "Ваш вхід для {username} буде передано застосунку Bulwark на цьому комп’ютері. Продовжуйте, лише якщо почали це із застосунку.",
"consent_description": "Програма на цьому комп’ютері, на порту {port}, запитує вхід для {username}. Продовжуйте, лише якщо ви щойно натиснули «Увійти через браузер…» у застосунку Bulwark на цьому комп’ютері. Якщо ні, можливо, хтось намагається потрапити у ваш обліковий запис: виберіть «Не зараз».",
"consent_confirm": "Увійти в застосунок",
"consent_cancel": "Не зараз",
"page_done": "Можна закрити цю вкладку й повернутися до Bulwark.",
@@ -6902,7 +6902,10 @@
"page_submit": "Увійти",
"page_wrong_password": "Сервер не прийняв це ім’я користувача й пароль.",
"page_code_needed": "Для цього облікового запису також потрібен двофакторний код. Введіть пароль ще раз і код.",
"page_no_answer": "Bulwark не зміг увійти. Перевірте, чи доступний сервер, і спробуйте ще раз."
"page_no_answer": "Bulwark не зміг увійти. Перевірте, чи доступний сервер, і спробуйте ще раз.",
"declined": "Ви відмовили в браузері, тому вхід не виконано.",
"too_many": "Забагато спроб входу з цієї мережі. Зачекайте кілька хвилин і спробуйте ще раз.",
"page_declined": "Нічого не передано. Можна закрити цю вкладку."
},
"desktop_updates": {
"title": "Оновлення",
+6 -3
View File
@@ -6898,9 +6898,9 @@
"timed_out": "Đăng nhập trong trình duyệt mất quá nhiều thời gian. Hãy thử lại.",
"no_browser": "Bulwark không thể mở trình duyệt. Hãy thử lại hoặc đăng nhập tại đây.",
"failed": "Không đăng nhập được qua trình duyệt. Hãy thử lại.",
"handoff_banner": "Bạn đang đăng nhập vào ứng dụng Bulwark trên máy tính này. Trình duyệt này vẫn chưa đăng nhập Bulwark.",
"handoff_banner": "Một chương trình trên máy tính này đã yêu cầu đăng nhập này cho ứng dụng Bulwark. Trình duyệt này vẫn chưa đăng nhập Bulwark. Nếu không phải bạn bắt đầu, hãy đóng tab này.",
"consent_title": "Đăng nhập vào ứng dụng Bulwark?",
"consent_description": "Thông tin đăng nhập của {username} sẽ được chuyển đến ứng dụng Bulwark trên máy tính này. Chỉ tiếp tục nếu bạn bắt đầu việc này từ ứng dụng.",
"consent_description": "Một chương trình trên máy tính này, tại cổng {port}, đang yêu cầu thông tin đăng nhập của {username}. Chỉ tiếp tục nếu bạn vừa nhấn \"Đăng nhập bằng trình duyệt…\" trong ứng dụng Bulwark tại đây. Nếu không, có thể ai đó đang cố vào tài khoản của bạn: hãy chọn Để sau.",
"consent_confirm": "Đăng nhập vào ứng dụng",
"consent_cancel": "Để sau",
"page_done": "Bạn có thể đóng tab này và quay lại Bulwark.",
@@ -6914,7 +6914,10 @@
"page_submit": "Đăng nhập",
"page_wrong_password": "Máy chủ không chấp nhận tên người dùng và mật khẩu này.",
"page_code_needed": "Tài khoản này cũng cần mã hai yếu tố. Hãy nhập lại mật khẩu và mã.",
"page_no_answer": "Bulwark không thể đăng nhập. Hãy kiểm tra xem máy chủ có truy cập được không rồi thử lại."
"page_no_answer": "Bulwark không thể đăng nhập. Hãy kiểm tra xem máy chủ có truy cập được không rồi thử lại.",
"declined": "Bạn đã từ chối trong trình duyệt nên không có đăng nhập nào.",
"too_many": "Có quá nhiều lần thử đăng nhập từ mạng này. Hãy đợi vài phút rồi thử lại.",
"page_declined": "Không có gì được chuyển giao. Bạn có thể đóng tab này."
},
"desktop_updates": {
"title": "Cập nhật",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "瀏覽器登入耗時過長。請再試一次。",
"no_browser": "Bulwark 無法開啟瀏覽器。請再試一次,或在此登入。",
"failed": "透過瀏覽器登入失敗。請再試一次。",
"handoff_banner": "你正在登入這台電腦上的 Bulwark 應用程式。此瀏覽器不會登入 Bulwark。",
"handoff_banner": "這台電腦上的一個程式為 Bulwark 應用程式要求了這次登入。此瀏覽器不會登入 Bulwark。如果不是你發起的,請關閉此分頁。",
"consent_title": "要登入 Bulwark 應用程式嗎?",
"consent_description": "{username} 的登入資訊將交給這台電腦上的 Bulwark 應用程式。只有從應用程式發起時才繼續。",
"consent_description": "這台電腦上連接埠 {port} 的一個程式正在要求 {username} 的登入資訊。只有在你剛剛按下這裡 Bulwark 應用程式中的「使用瀏覽器登入…」時才繼續。否則可能有人想進入你的帳戶:請選擇「暫不」。",
"consent_confirm": "登入應用程式",
"consent_cancel": "暫不",
"page_done": "你可以關閉此分頁並返回 Bulwark。",
@@ -6902,7 +6902,10 @@
"page_submit": "登入",
"page_wrong_password": "伺服器不接受此使用者名稱和密碼。",
"page_code_needed": "此帳戶還需要雙重驗證碼。請重新輸入密碼和驗證碼。",
"page_no_answer": "Bulwark 無法登入。請檢查伺服器是否可連線,然後再試一次。"
"page_no_answer": "Bulwark 無法登入。請檢查伺服器是否可連線,然後再試一次。",
"declined": "你在瀏覽器中拒絕了,因此沒有登入。",
"too_many": "來自此網路的登入嘗試過多。請等幾分鐘後再試一次。",
"page_declined": "沒有交出任何內容。你可以關閉此分頁。"
},
"desktop_updates": {
"title": "更新",
+6 -3
View File
@@ -6886,9 +6886,9 @@
"timed_out": "浏览器登录用时过长。请重试。",
"no_browser": "Bulwark 无法打开浏览器。请重试,或在此登录。",
"failed": "通过浏览器登录失败。请重试。",
"handoff_banner": "你正在登录这台电脑上的 Bulwark 应用。此浏览器不会登录 Bulwark。",
"handoff_banner": "这台电脑上的一个程序为 Bulwark 应用请求了此次登录。此浏览器不会登录 Bulwark。如果不是你发起的,请关闭此标签页。",
"consent_title": "要登录 Bulwark 应用吗?",
"consent_description": "{username} 的登录信息将交给这台电脑上的 Bulwark 应用。只有从应用中发起时才继续。",
"consent_description": "这台电脑上端口 {port} 的一个程序正在请求 {username} 的登录信息。只有在你刚刚点击了这里 Bulwark 应用中的“使用浏览器登录…”时才继续。否则可能有人想进入你的账户:请选择“暂不”。",
"consent_confirm": "登录应用",
"consent_cancel": "暂不",
"page_done": "你可以关闭此标签页并返回 Bulwark。",
@@ -6902,7 +6902,10 @@
"page_submit": "登录",
"page_wrong_password": "服务器不接受此用户名和密码。",
"page_code_needed": "此账户还需要双重验证代码。请重新输入密码和代码。",
"page_no_answer": "Bulwark 无法登录。请检查服务器是否可访问,然后重试。"
"page_no_answer": "Bulwark 无法登录。请检查服务器是否可访问,然后重试。",
"declined": "你在浏览器中拒绝了,因此没有登录。",
"too_many": "来自此网络的登录尝试过多。请等几分钟后重试。",
"page_declined": "没有交出任何内容。你可以关闭此标签页。"
},
"desktop_updates": {
"title": "更新",
+2
View File
@@ -119,6 +119,8 @@ export const LITE_API_STRING_ALLOWLIST = [
"/api/auth/handoff/create",
"/api/auth/handoff/confirm",
// The desktop app's sign-in on an instance: no bridge in a browser, and IS_LITE guards.
"/api/auth/desktop-handoff/check",
"/api/auth/desktop-handoff/discard",
"/api/auth/desktop-handoff/park",
"/api/auth/desktop-handoff/redeem",
"/api/auth/totp-token-exchange",
@@ -0,0 +1,66 @@
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import { JMAPClient } from '@/lib/jmap/client';
import { generateAccountId } from '@/lib/account-utils';
import { useAuthStore } from '../auth-store';
import { useAccountStore } from '../account-store';
const SERVER = 'https://mail.example.com';
const OPTIONS = { remember: true, rememberPassword: true, allowedServers: null, customServersAllowed: true };
/**
* What the desktop app becomes after a sign-in in the browser. A typed password stays a
* password account (#1432): its settings are there, and sign-out doesn't go to a provider.
*/
describe('loginWithDesktopHandoff', () => {
let redeemAnswer: unknown;
let redeemBody: Record<string, unknown>;
beforeEach(() => {
vi.restoreAllMocks();
sessionStorage.clear();
localStorage.clear();
window.history.pushState({}, '', '/en/login');
useAccountStore.setState({ accounts: [], activeAccountId: null, defaultAccountId: null });
useAuthStore.setState({ isAuthenticated: false, isLoading: false, error: null, serverUrl: null, username: null, client: null, activeAccountId: null });
vi.spyOn(JMAPClient.prototype, 'connect').mockResolvedValue(undefined as never);
vi.spyOn(JMAPClient.prototype, 'getUsername').mockReturnValue('session-name@example.com');
vi.spyOn(JMAPClient.prototype, 'getSessionUsername').mockReturnValue('session-name@example.com');
vi.spyOn(JMAPClient.prototype, 'getIdentities').mockResolvedValue([{ id: 'i', name: 'Alice', email: 'alice@example.com' }] as never);
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input).includes('/api/auth/desktop-handoff/redeem')) {
redeemBody = JSON.parse(String(init?.body));
return new Response(JSON.stringify(redeemAnswer), { status: 200 });
}
return new Response('{}', { status: 200 });
}));
});
afterEach(() => {
vi.unstubAllGlobals();
});
const account = () => useAccountStore.getState().getActiveAccount();
it('tokens from a typed password are a password account, under the name typed', async () => {
redeemAnswer = { flow: 'tokens', server_url: SERVER, access_token: 'a', expires_in: 3600, remember: true, password_login: true, username: 'alice' };
expect(await useAuthStore.getState().loginWithDesktopHandoff('c', 'v', OPTIONS)).toBe('ok');
expect(account()).toMatchObject({ authMode: 'oauth', providerSession: false, username: 'alice' });
// A short login name has the same id as the password sign-in, so what was kept for it comes back.
expect(account()?.id).toBe(generateAccountId('alice', SERVER));
expect(account()?.id).not.toBe(generateAccountId('alice@example.com', SERVER));
expect(useAuthStore.getState().username).toBe('alice');
expect(account()?.serverIdentifiers?.length).toBeGreaterThan(0);
});
it('a provider\'s sign-in stays a provider session, under the address the server gives', async () => {
redeemAnswer = { flow: 'tokens', server_url: SERVER, access_token: 'a', expires_in: 3600, remember: true };
expect(await useAuthStore.getState().loginWithDesktopHandoff('c', 'v', OPTIONS)).toBe('ok');
expect(account()).toMatchObject({ authMode: 'oauth', providerSession: true, username: 'alice@example.com' });
});
it('sends the device\'s rules with the code', async () => {
redeemAnswer = { flow: 'tokens', server_url: SERVER, access_token: 'a', expires_in: 3600, remember: true };
await useAuthStore.getState().loginWithDesktopHandoff('c', 'v', { ...OPTIONS, allowedServers: ['https://a.example'], customServersAllowed: false });
expect(redeemBody).toMatchObject({ code: 'c', code_verifier: 'v', allowed_servers: ['https://a.example'], custom_servers_allowed: false });
});
});
+33 -9
View File
@@ -114,7 +114,7 @@ interface AuthState {
* The desktop app on an instance: the one-time code from its browser sign-in, with the
* verifier it kept. `blocked` is the device's own list of servers saying no.
*/
loginWithDesktopHandoff: (code: string, verifier: string, options: { remember: boolean; rememberPassword: boolean; allowedServers: string[] | null }) => Promise<'ok' | 'blocked' | 'failed'>;
loginWithDesktopHandoff: (code: string, verifier: string, options: { remember: boolean; rememberPassword: boolean; allowedServers: string[] | null; customServersAllowed: boolean }) => Promise<'ok' | 'blocked' | 'failed'>;
loginDemo: () => Promise<boolean>;
/**
* Obtain a usable access token for `accountId`, or the active account.
@@ -1637,20 +1637,33 @@ function notifySignedIn(state: { activeAccountId: string | null; username: strin
async function adoptProviderSession(
set: (state: Partial<AuthState>) => void,
get: () => AuthState,
session: { serverUrl: string; accessToken: string; expiresIn: number; remember: boolean | undefined; slot: number },
session: {
serverUrl: string;
accessToken: string;
expiresIn: number;
remember: boolean | undefined;
slot: number;
/**
* Tokens from a typed password, not a provider's page: the account the user knows, under
* the name they typed. It has the same id as any other password sign-in with that name, so
* what its last sign-out kept comes back, and its password settings stay (#1432).
*/
typedUsername?: string;
},
): Promise<void> {
const { serverUrl: ssoServerUrl, accessToken: access_token, expiresIn: expires_in, remember, slot } = session;
const typed = session.typedUsername ? toAsciiEmail(session.typedUsername) : '';
const accountStore = useAccountStore.getState();
let boundAccountId: string | undefined;
const client = JMAPClient.withBearer(ssoServerUrl, access_token, '', () => get().refreshAccessToken({ accountId: boundAccountId }));
const client = JMAPClient.withBearer(ssoServerUrl, access_token, typed, () => get().refreshAccessToken({ accountId: boundAccountId }));
await client.connect();
const jmapUsername = client.getUsername();
const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), jmapUsername);
const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), typed || jmapUsername);
// For SSO/OIDC, the JMAP session account name may be the
// preferred_username claim rather than the real email address.
// Prefer the email from the primary identity when available.
const username = primaryIdentity?.email || jmapUsername;
const username = typed || primaryIdentity?.email || jmapUsername;
initializeFeatureStores(client);
const accountId = generateAccountId(username, ssoServerUrl);
@@ -1681,7 +1694,11 @@ async function adoptProviderSession(
// The refresh-token cookie was written to `slot` by /api/auth/sso/complete.
// Force the stored cookieSlot to match - see loginWithOAuth above for the
// re-add and concurrent-tab cases this guards against.
accountStore.updateAccount(accountId, { cookieSlot: slot, providerSession: true });
accountStore.updateAccount(accountId, { cookieSlot: slot, providerSession: !typed });
if (typed) {
const serverIdentifiers = buildServerIdentifiers(client.getSessionUsername(), primaryIdentity?.email, ssoServerUrl);
if (serverIdentifiers.length > 0) accountStore.updateAccount(accountId, { serverIdentifiers });
}
accountStore.setActiveAccount(accountId);
await syncStalwartAuthContext(ssoServerUrl, username, client.getAuthHeader(), slot);
@@ -2409,7 +2426,7 @@ export const useAuthStore = create<AuthState>()(
}
},
loginWithDesktopHandoff: async (code, verifier, { remember, rememberPassword, allowedServers }) => {
loginWithDesktopHandoff: async (code, verifier, { remember, rememberPassword, allowedServers, customServersAllowed }) => {
if (IS_LITE) return 'failed';
set({ isLoading: true, error: null, isRateLimited: false, rateLimitUntil: null });
try {
@@ -2417,7 +2434,7 @@ export const useAuthStore = create<AuthState>()(
const res = await apiFetch('/api/auth/desktop-handoff/redeem', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, code_verifier: verifier, slot, remember, allowed_servers: allowedServers }),
body: JSON.stringify({ code, code_verifier: verifier, slot, remember, allowed_servers: allowedServers, custom_servers_allowed: customServersAllowed }),
}).then((answer) => noteSessionAnswer(answer, slot));
if (!res.ok) {
const refusal = (await res.json().catch(() => null)) as { error?: string } | null;
@@ -2429,7 +2446,14 @@ export const useAuthStore = create<AuthState>()(
// A password the browser checked a moment ago, down the same path as a typed one.
return (await get().login(parked.server_url, parked.username, parked.password, undefined, rememberPassword)) ? 'ok' : 'failed';
}
await adoptProviderSession(set, get, { serverUrl: parked.server_url, accessToken: parked.access_token, expiresIn: parked.expires_in, remember: parked.remember, slot });
await adoptProviderSession(set, get, {
serverUrl: parked.server_url,
accessToken: parked.access_token,
expiresIn: parked.expires_in,
remember: parked.remember,
slot,
...(parked.password_login ? { typedUsername: parked.username } : {}),
});
return 'ok';
} catch (error) {
debug.error('Desktop hand-off login error:', error);