From b8cb12174c5152e746682cad1c3b52d04c52e5d9 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:45:13 +0100 Subject: [PATCH 01/59] fix: bring office editing back after sign-in when the first status check was refused #1518 --- .../files/__tests__/wopi-base-path.test.tsx | 5 +- hooks/__tests__/use-wopi-status.test.ts | 140 ++++++++++++++++++ hooks/use-wopi-status.ts | 57 ++++--- 3 files changed, 182 insertions(+), 20 deletions(-) create mode 100644 hooks/__tests__/use-wopi-status.test.ts diff --git a/components/files/__tests__/wopi-base-path.test.tsx b/components/files/__tests__/wopi-base-path.test.tsx index c1facd996..0e2296298 100644 --- a/components/files/__tests__/wopi-base-path.test.tsx +++ b/components/files/__tests__/wopi-base-path.test.tsx @@ -2,6 +2,7 @@ import { render, renderHook, waitFor, cleanup } from '@testing-library/react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { useWopiStatus } from '@/hooks/use-wopi-status'; import { WopiEditor } from '@/components/files/wopi-editor'; +import { useAuthStore } from '@/stores/auth-store'; // Behind a reverse proxy at a sub-path (e.g. /webmail) a bare // fetch('/api/...') reaches the mail server instead of the webmail and comes @@ -26,9 +27,9 @@ afterEach(() => { describe('WOPI requests under a sub-path mount', () => { it('probes the editor status under the mount prefix', async () => { + useAuthStore.setState({ isAuthenticated: true, client: {} as never }); renderHook(() => useWopiStatus(true)); - await waitFor(() => expect(fetchMock).toHaveBeenCalled()); - expect(fetchMock.mock.calls[0][0]).toBe('/webmail/api/wopi/status'); + await waitFor(() => expect(fetchMock).toHaveBeenCalledWith('/webmail/api/wopi/status', undefined)); }); it('launches the editor under the mount prefix', async () => { diff --git a/hooks/__tests__/use-wopi-status.test.ts b/hooks/__tests__/use-wopi-status.test.ts new file mode 100644 index 000000000..6e80b974f --- /dev/null +++ b/hooks/__tests__/use-wopi-status.test.ts @@ -0,0 +1,140 @@ +import { renderHook, waitFor, cleanup } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach, afterEach, type Mock } from 'vitest'; + +// /api/wopi/status needs the sign-in context cookie. The mail and files views +// can mount before it exists, so a 401 there says nothing about the editor and +// must not leave office editing off until the next page load (#1518). + +const ENABLED = { enabled: true, editExtensions: ['docx', 'odt'], viewExtensions: ['pdf'], newExtensions: ['docx'] }; + +const answer = (status: number, body: unknown = {}) => ({ ok: status >= 200 && status < 300, status, json: async () => body }); + +let fetchMock: Mock<(url: string, init?: RequestInit) => Promise>; +let useWopiStatus: typeof import('@/hooks/use-wopi-status').useWopiStatus; +let useAuthStore: typeof import('@/stores/auth-store').useAuthStore; + +const signIn = (client: object) => useAuthStore.setState({ isAuthenticated: true, client: client as never }); + +beforeEach(async () => { + fetchMock = vi.fn(); + // Only the status route counts: the auth store asks for other things on import. + vi.stubGlobal('fetch', (url: string, init?: RequestInit) => ( + url.includes('/api/wopi/status') ? fetchMock(url, init) : Promise.resolve(answer(404)) + )); + // The hook shares its answer through module state, like a page load does. + vi.resetModules(); + ({ useWopiStatus } = await import('@/hooks/use-wopi-status')); + ({ useAuthStore } = await import('@/stores/auth-store')); + useAuthStore.setState({ isAuthenticated: false, client: null }); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('useWopiStatus', () => { + it('asks nothing before sign-in, and asks once sign-in is done', async () => { + fetchMock.mockResolvedValue(answer(200, ENABLED)); + const { result } = renderHook(() => useWopiStatus(true)); + + await Promise.resolve(); + expect(fetchMock).not.toHaveBeenCalled(); + + signIn({}); + await waitFor(() => expect(result.current?.enabled).toBe(true)); + expect(result.current?.editExtensions).toContain('docx'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('asks nothing while the persisted flag says signed in but no client is connected yet', async () => { + fetchMock.mockResolvedValue(answer(200, ENABLED)); + useAuthStore.setState({ isAuthenticated: true, client: null }); + renderHook(() => useWopiStatus(true)); + + await Promise.resolve(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('turns editing on when a 401 is followed by the real client taking over', async () => { + // A local copy is on screen before the restore writes the context cookie. + fetchMock.mockResolvedValueOnce(answer(401)).mockResolvedValue(answer(200, ENABLED)); + signIn({ kind: 'local copy' }); + const { result } = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(result.current).not.toBeNull()); + expect(result.current?.enabled).toBe(false); + + signIn({ kind: 'real' }); + await waitFor(() => expect(result.current?.enabled).toBe(true)); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('does not share a 401 still in flight with the client that took over', async () => { + let finishFirst: (value: unknown) => void = () => {}; + fetchMock + .mockReturnValueOnce(new Promise((resolve) => { finishFirst = resolve; })) + .mockResolvedValue(answer(200, ENABLED)); + signIn({ kind: 'local copy' }); + const { result } = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1)); + + signIn({ kind: 'real' }); + await waitFor(() => expect(result.current?.enabled).toBe(true)); + finishFirst(answer(401)); + + // The late refusal does not take the answer back, for this view or the next. + await new Promise((resolve) => setTimeout(resolve)); + expect(result.current?.enabled).toBe(true); + const next = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(next.result.current?.enabled).toBe(true)); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it.each([401, 500, 502])('asks again on the next mount after a %i', async (status) => { + fetchMock.mockResolvedValueOnce(answer(status)).mockResolvedValue(answer(200, ENABLED)); + signIn({}); + const first = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(first.result.current).not.toBeNull()); + expect(first.result.current?.enabled).toBe(false); + + const second = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(second.result.current?.enabled).toBe(true)); + }); + + it('keeps a real answer for the page, across views and account switches', async () => { + fetchMock.mockResolvedValue(answer(200, ENABLED)); + signIn({ account: 'a' }); + const first = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(first.result.current?.enabled).toBe(true)); + + const second = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(second.result.current?.enabled).toBe(true)); + signIn({ account: 'b' }); + await waitFor(() => expect(useAuthStore.getState().client).toEqual({ account: 'b' })); + await new Promise((resolve) => setTimeout(resolve)); + + expect(first.result.current?.enabled).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('keeps a real "no editor" answer too, so mail views do not keep asking', async () => { + fetchMock.mockResolvedValue(answer(200, { enabled: false })); + signIn({}); + const first = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(first.result.current?.enabled).toBe(false)); + + const second = renderHook(() => useWopiStatus(true)); + await waitFor(() => expect(second.result.current?.enabled).toBe(false)); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('asks nothing while the caller has it switched off', async () => { + fetchMock.mockResolvedValue(answer(200, ENABLED)); + signIn({}); + const { result } = renderHook(() => useWopiStatus(false)); + + await Promise.resolve(); + expect(fetchMock).not.toHaveBeenCalled(); + expect(result.current).toBeNull(); + }); +}); diff --git a/hooks/use-wopi-status.ts b/hooks/use-wopi-status.ts index 4d6dd014a..c3b575edf 100644 --- a/hooks/use-wopi-status.ts +++ b/hooks/use-wopi-status.ts @@ -3,11 +3,12 @@ import { useEffect, useState } from "react"; import { IS_LITE } from "@/lib/lite"; import { apiFetch } from "@/lib/browser-navigation"; +import { useAuthStore } from "@/stores/auth-store"; /** * Whether a WOPI document editor is configured for this deployment and which - * file extensions it handles (#425). Fetched once per page load and shared - * across consumers via a module-level promise. + * file extensions it handles (#425). The answer is the same for every account, + * so the first real one is kept for the page load and shared across consumers. */ export interface WopiStatus { enabled: boolean; @@ -19,41 +20,61 @@ export interface WopiStatus { const DISABLED: WopiStatus = { enabled: false, editExtensions: [], viewExtensions: [], newExtensions: [] }; -let statusPromise: Promise | null = null; +let known: WopiStatus | null = null; +let pending: Promise | null = null; +let pendingClient: unknown = null; -function fetchWopiStatus(): Promise { +function fetchWopiStatus(client: unknown): Promise { // The WOPI bridge is a server feature; the static build never has an editor. if (IS_LITE) return Promise.resolve(DISABLED); - if (!statusPromise) { - statusPromise = apiFetch("/api/wopi/status") - .then((res) => (res.ok ? res.json() : DISABLED)) - .then((data) => ({ + if (known) return Promise.resolve(known); + // A request sent for an earlier client may be refused for lack of the sign-in + // context this one brought, so only the same client shares it. + if (pending && pendingClient === client) return pending; + + const request: Promise = apiFetch("/api/wopi/status") + .then((res) => { + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return res.json(); + }) + .then((data) => { + known = { enabled: !!data?.enabled, editExtensions: Array.isArray(data?.editExtensions) ? data.editExtensions : [], viewExtensions: Array.isArray(data?.viewExtensions) ? data.viewExtensions : [], newExtensions: Array.isArray(data?.newExtensions) ? data.newExtensions : [], - })) - .catch(() => { - statusPromise = null; // allow a retry on the next mount - return DISABLED; - }); - } - return statusPromise; + }; + return known; + }) + // A refusal or an outage says nothing about the editor (#1518): show no + // editor for now and ask again on the next mount or client. + .catch(() => DISABLED) + .finally(() => { + if (pending === request) pending = null; + }); + pending = request; + pendingClient = client; + return request; } export function useWopiStatus(enabled: boolean): WopiStatus | null { const [status, setStatus] = useState(null); + // The route needs the sign-in context cookie, which is written before the + // store holds a connected client. `isAuthenticated` alone comes back from + // storage on load, and a local copy's client gives way to the real one once + // the restore wrote the cookie, so this follows the client itself (#1518). + const client = useAuthStore((state) => (state.isAuthenticated ? state.client : null)); useEffect(() => { - if (!enabled) return; + if (!enabled || !client) return; let cancelled = false; - fetchWopiStatus().then((s) => { + fetchWopiStatus(client).then((s) => { if (!cancelled) setStatus(s); }); return () => { cancelled = true; }; - }, [enabled]); + }, [enabled, client]); return status; } From 7040a6a04948eae49cf73d30c35c66ee9421fa35 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:06:21 +0100 Subject: [PATCH 02/59] fix: reply and forward from the account holding the message in Pro tabs #1511 --- components/mail/mail-app.tsx | 2 + .../pro-email-reply-account.test.tsx | 137 ++++++++++++++++++ components/pro/pro-email-tab-body.tsx | 21 ++- 3 files changed, 155 insertions(+), 5 deletions(-) create mode 100644 components/pro/__tests__/pro-email-reply-account.test.tsx diff --git a/components/mail/mail-app.tsx b/components/mail/mail-app.tsx index 9c69bd96e..d24d4e61d 100644 --- a/components/mail/mail-app.tsx +++ b/components/mail/mail-app.tsx @@ -3172,6 +3172,8 @@ export function MailApp({ linkSegments: routeSegments }: MailAppProps = {}) { attachments: [payload.attachment], headers: labelSourceHeaders(email.headers), originalFrom: email.from, + // The login holding the message, whose blob this attachment is. + accountId: email.sourceClientAccountId ?? viewingAccountId ?? undefined, }, }); setComposerMode('forward'); diff --git a/components/pro/__tests__/pro-email-reply-account.test.tsx b/components/pro/__tests__/pro-email-reply-account.test.tsx new file mode 100644 index 000000000..d0d514717 --- /dev/null +++ b/components/pro/__tests__/pro-email-reply-account.test.tsx @@ -0,0 +1,137 @@ +import { render, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import React from 'react'; + +/** + * A reply, forward or forward-as-attachment from a Pro message view names the + * login holding the message. The composer defaults its From to that account and + * copies the original's parts from it; without the login it takes the message + * for the active account's, so the reply goes out from the wrong account, or + * fails on a blobId that account doesn't have (#1511). + */ + +const viewerProps = vi.hoisted(() => ({ current: null as Record | null })); + +vi.mock('@/components/email/email-viewer', () => ({ + EmailViewer: (props: Record) => { + viewerProps.current = props; + return null; + }, +})); +vi.mock('@/components/error', () => ({ + ErrorBoundary: ({ children }: { children: React.ReactNode }) => React.createElement(React.Fragment, null, children), + EmailViewerErrorFallback: () => null, +})); +vi.mock('next-intl', () => ({ useTranslations: () => (key: string) => key })); +vi.mock('@/stores/toast-store', () => ({ toast: { error: () => {}, success: () => {} } })); +vi.mock('@/hooks/use-pro-multi-account-identities', async (importOriginal) => ({ + ...await importOriginal(), + useProMultiAccountIdentities: () => ({ enabled: true, groups: [], allIdentities: [] }), +})); + +const { openComposeTab } = vi.hoisted(() => ({ openComposeTab: vi.fn() })); + +function selectorStore(state: T) { + const hook = (sel?: (s: T) => unknown) => (typeof sel === 'function' ? sel(state) : state); + hook.getState = () => state; + return hook; +} + +const auth = vi.hoisted(() => ({ + state: { client: null as unknown, activeAccountId: 'login-a', getClientForAccount: () => undefined }, +})); +vi.mock('@/stores/auth-store', () => ({ useAuthStore: selectorStore(auth.state) })); + +const MESSAGE = vi.hoisted(() => ({ + id: 'eaaaaab', + blobId: 'blob-of-message', + threadId: 't1', + mailboxIds: { inbox: true }, + keywords: { $seen: true }, + from: [{ email: 'sender@example.com', name: 'Sender' }], + to: [{ email: 'b@example.org' }], + subject: 'Hello', + receivedAt: '2026-01-01T00:00:00Z', + bodyValues: { '1': { value: '' } }, + textBody: [], + htmlBody: [{ partId: '1', type: 'text/html' }], + attachments: [{ blobId: 'blob-of-logo', name: 'logo.png', type: 'image/png', size: 10, cid: 'logo', disposition: 'inline' }], +})); + +vi.mock('@/stores/email-store', () => ({ + resolveEmailBlobContext: (_email: unknown, client: unknown) => ({ client, clientAccountId: auth.state.activeAccountId }), + useEmailStore: selectorStore({ + fetchEmailContent: async () => MESSAGE, + deleteEmail: async () => {}, + markAsRead: async () => {}, + toggleStar: async () => {}, + moveToMailbox: async () => {}, + setEmailKeywordsLocal: () => {}, + mailboxes: [], + emails: [], + selectedEmail: null, + }), +})); +vi.mock('@/stores/identity-store', () => ({ useIdentityStore: selectorStore({ identities: [] }) })); +vi.mock('@/stores/settings-store', () => ({ useSettingsStore: selectorStore({ emailDownloadTemplate: '' }) })); +vi.mock('@/stores/pro-tab-store', () => ({ + useProTabStore: selectorStore({ openComposeTab, closeTab: () => {}, updateTabTitle: () => {} }), +})); + +import { ProEmailView } from '../pro-email-tab-body'; + +const ACTIONS = ['onReply', 'onReplyAll', 'onForward', 'onForwardAsAttachment'] as const; + +async function open(props: { clientAccountId?: string; accountId?: string; override?: boolean }) { + const client = { getEmail: vi.fn().mockResolvedValue(MESSAGE), getUsername: () => 'b@example.org', getAccountId: () => 'jmap-b' }; + const { override = true, ...rest } = props; + if (!override) auth.state.client = client; + const view = render(); + await waitFor(() => expect(viewerProps.current?.email).toBeTruthy()); + return { ...view, client }; +} + +function composeFrom(action: typeof ACTIONS[number]) { + openComposeTab.mockClear(); + (viewerProps.current![action] as () => void)(); + expect(openComposeTab).toHaveBeenCalledTimes(1); + return openComposeTab.mock.calls[0][0].replyTo as Record; +} + +describe('compose actions of a Pro message view', () => { + beforeEach(() => { + viewerProps.current = null; + openComposeTab.mockClear(); + auth.state.activeAccountId = 'login-a'; + auth.state.client = null; + }); + + it.each(ACTIONS)('%s of another login names that login', async (action) => { + await open({ clientAccountId: 'login-b' }); + + expect(composeFrom(action).accountId).toBe('login-b'); + }); + + it.each(ACTIONS)('%s of a shared folder of another login names the login, not the owner', async (action) => { + await open({ clientAccountId: 'login-b', accountId: 'jmap-team' }); + + expect(composeFrom(action).accountId).toBe('login-b'); + }); + + it.each(ACTIONS)('%s of the active login names the active login', async (action) => { + await open({ override: false }); + + expect(composeFrom(action).accountId).toBe('login-a'); + }); + + it('keeps naming the login the message was read in after the active account changes', async () => { + // A message of b isn't foreign while b is active, so it carries no stamp. + auth.state.activeAccountId = 'login-b'; + const { rerender, client } = await open({ clientAccountId: 'login-b' }); + + auth.state.activeAccountId = 'login-a'; + rerender(); + + expect(composeFrom('onReply').accountId).toBe('login-b'); + }); +}); diff --git a/components/pro/pro-email-tab-body.tsx b/components/pro/pro-email-tab-body.tsx index 024742440..bc8d0fbfc 100644 --- a/components/pro/pro-email-tab-body.tsx +++ b/components/pro/pro-email-tab-body.tsx @@ -111,7 +111,17 @@ export function stampProSource(email: Email, source: EmailBlobContext, loginId: return { ...email, sourceClientAccountId: login, sourceAccountId: account }; } -function buildReplyContext(email: Email): ProReplyContext { +/** + * The login holding the message, for ProReplyContext.accountId: the composer + * defaults its From to that account and copies the original's parts from it + * (#1104, #1511). email.accountId can't say: it is for display, and a message + * read through client.getEmail() has none. + */ +function replyLogin(email: Email, source: EmailWriteSource): string | undefined { + return email.sourceClientAccountId ?? source.clientAccountId; +} + +function buildReplyContext(email: Email, source: EmailWriteSource): ProReplyContext { return { from: email.from, replyToAddresses: email.replyTo, @@ -122,7 +132,7 @@ function buildReplyContext(email: Email): ProReplyContext { subject: email.subject, ...getQuoteBodies(email), receivedAt: email.receivedAt, - accountId: email.accountId, + accountId: replyLogin(email, source), attachments: email.attachments, messageId: email.messageId, inReplyTo: email.inReplyTo, @@ -285,7 +295,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId, if (!email) return; openComposeTab({ mode: 'reply', - replyTo: buildReplyContext(email), + replyTo: buildReplyContext(email, writeSource), sourceEmailId: email.id, sourceEmailSource: writeSource, initialDraftText: draftText, @@ -305,7 +315,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId, if (!email) return; openComposeTab({ mode: 'replyAll', - replyTo: buildReplyContext(email), + replyTo: buildReplyContext(email, writeSource), sourceEmailId: email.id, sourceEmailSource: writeSource, title: buildReplySubject(email.subject || t('email_composer.new_message'), t('email_composer.prefix.reply')), @@ -316,7 +326,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId, if (!email) return; openComposeTab({ mode: 'forward', - replyTo: buildReplyContext(email), + replyTo: buildReplyContext(email, writeSource), sourceEmailId: email.id, sourceEmailSource: writeSource, title: buildForwardSubject(email.subject || t('email_composer.new_message'), t('email_composer.prefix.forward')), @@ -355,6 +365,7 @@ export function ProEmailView({ emailId, client: clientOverride, clientAccountId, attachments: [payload.attachment], headers: labelSourceHeaders(email.headers), originalFrom: email.from, + accountId: replyLogin(email, writeSource), }, sourceEmailId: email.id, sourceEmailSource: writeSource, From 514a9ba1d9b95eaf86bfbd7141ac125668aefd6b Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Tue, 3 Nov 2026 22:08:18 +0100 Subject: [PATCH 03/59] fix: keep the quote when typing in a reply as its inline images load --- .../rich-text-editor-quote-caret.test.tsx | 72 +++++++++++++++++++ components/email/quoted-html.ts | 16 +++++ components/email/rich-text-editor.tsx | 4 +- 3 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 components/email/__tests__/rich-text-editor-quote-caret.test.tsx diff --git a/components/email/__tests__/rich-text-editor-quote-caret.test.tsx b/components/email/__tests__/rich-text-editor-quote-caret.test.tsx new file mode 100644 index 000000000..37de365d6 --- /dev/null +++ b/components/email/__tests__/rich-text-editor-quote-caret.test.tsx @@ -0,0 +1,72 @@ +import { act, render, waitFor } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import React from 'react'; +import type { Editor } from '@tiptap/core'; + +import { RichTextEditor } from '../rich-text-editor'; +import { serializeEditorContent } from '../quoted-html'; + +// A reply's quoted inline images load while the caret already waits in the +// body, and swapping them in re-sets the editor's content. That threw the caret +// onto the quote as a node, where the first key typed replaced the whole quote +// and the reply went out without the original or its images, or below the quote. + +const PLACEHOLDER = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; +const IMAGE = 'data:image/png;base64,iVBORw0KGgo='; +const body = (src: string, below: string) => `

On Tuesday, C wrote:

Original text

logo
${below}`; + +async function openReply(below: string) { + let editor: Editor | null = null; + const element = (content: string) => ( + {}} onEditorReady={(ed) => { editor = ed as unknown as Editor; }} /> + ); + const view = render(element(body(PLACEHOLDER, below))); + await waitFor(() => expect(editor).not.toBeNull()); + const ed = editor as unknown as Editor; + // Where focus('start') puts it; focus itself waits for a frame. + act(() => { ed.commands.setTextSelection(1); }); + return { editor: ed, setContent: (content: string) => view.rerender(element(content)) }; +} + +const type = (editor: Editor, text: string) => act(() => { editor.view.dispatch(editor.state.tr.insertText(text)); }); + +describe.each([ + ['with a line below the quote', '

'], + ['with the quote at the very end', ''], +])('typing in a reply once its inline images have loaded, %s', (_name, below) => { + it('goes above the quote and keeps it and its image', async () => { + const { editor, setContent } = await openReply(below); + + setContent(body(IMAGE, below)); + type(editor, 'My answer'); + + const sent = serializeEditorContent(editor); + expect(editor.state.doc.child(0).textContent).toBe('My answer'); + expect(sent).toContain('Original text'); + expect(sent).toContain(IMAGE); + }); + + it('carries on where the user was already typing', async () => { + const { editor, setContent } = await openReply(below); + type(editor, 'Hel'); + + setContent(body(IMAGE, `${below}`).replace('

', '

Hel

')); + type(editor, 'lo'); + + expect(editor.state.doc.child(0).textContent).toBe('Hello'); + expect(serializeEditorContent(editor)).toContain('Original text'); + }); +}); + +describe('a body replaced by a shorter one', () => { + it('leaves the caret inside it', async () => { + const { editor, setContent } = await openReply('

A long line below the quote

'); + act(() => { editor.commands.setTextSelection(editor.state.doc.content.size - 2); }); + + setContent('

Short

'); + type(editor, '!'); + + expect(editor.state.doc.textContent).toContain('Short'); + expect(editor.state.doc.textContent).toContain('!'); + }); +}); diff --git a/components/email/quoted-html.ts b/components/email/quoted-html.ts index d1aa476df..1cef8c354 100644 --- a/components/email/quoted-html.ts +++ b/components/email/quoted-html.ts @@ -23,6 +23,22 @@ const QUOTED_REMOTE_ALLOWED_ATTR = "data-quoted-remote"; // Atom blocks typing must never replace just because they were left selected. const ATOM_BLOCKS = new Set(["quotedHtml", "signatureBlock"]); +/** + * Replacing the editor's content throws the caret to where the old selection + * maps to: the quote as a node, where the next key typed replaces the whole + * quote, or the line below it. There is no focus event for the guard below to + * catch: a reply's inline images finish loading while the caret already waits + * in the body. It goes back to where it was, or to the start if that is gone. + */ +export function restoreCaretAfterContentSync(editor: Editor, caret: number): void { + const { doc } = editor.state; + const near = Selection.near(doc.resolve(Math.min(caret, doc.content.size))); + const target = near instanceof TextSelection ? near : Selection.atStart(doc); + if (target instanceof TextSelection && !target.eq(editor.state.selection)) { + editor.view.dispatch(editor.state.tr.setSelection(target)); + } +} + // Reusable style for the quote bar when quoting email text (like in a reply). const QUOTE_BAR_STYLE = "border-left:2px solid #c5c5c5;padding-left:12px;margin-top:8px;"; diff --git a/components/email/rich-text-editor.tsx b/components/email/rich-text-editor.tsx index 1eb7decca..3448897cd 100644 --- a/components/email/rich-text-editor.tsx +++ b/components/email/rich-text-editor.tsx @@ -24,7 +24,7 @@ import { TableRow } from "@tiptap/extension-table-row"; import { TableHeader } from "@tiptap/extension-table-header"; import { TableCell } from "@tiptap/extension-table-cell"; import { ReplyQuoteCollapse } from "@/components/email/reply-quote-collapse"; -import { QuotedHtml, serializeEditorContent } from "@/components/email/quoted-html"; +import { QuotedHtml, restoreCaretAfterContentSync, serializeEditorContent } from "@/components/email/quoted-html"; import { keepLoadedParagraphSpacing, paragraphStyleWithoutSpacing, trailingParagraphBreakRule } from "@/components/email/paragraph-breaks"; import { SignatureBlock } from "@/components/email/signature-block"; import { styledBlockAttributes } from "@/components/email/styled-block-attributes"; @@ -614,7 +614,9 @@ export function RichTextEditor({ if (!editor) return; const loaded = keepLoadedParagraphSpacing(content); if (loaded !== serializeEditorContent(editor)) { + const caret = editor.state.selection.from; editor.commands.setContent(loaded, { emitUpdate: false }); + restoreCaretAfterContentSync(editor, caret); } }, [content, editor]); From e74248b37bcfbe7b1ebf7dcc53f2cabbc7bea4b7 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:37:40 +0100 Subject: [PATCH 04/59] feat: edit attachments in their own program from the desktop app and take the saved file back into mail --- app/(main)/[locale]/layout.tsx | 2 + .../__tests__/edited-files-host.test.tsx | 221 ++++++++++++++ components/desktop/edited-files-host.tsx | 189 ++++++++++++ .../__tests__/reader-attachments.test.tsx | 18 ++ components/email/email-composer.tsx | 48 ++++ components/email/email-viewer.tsx | 17 ++ components/email/reader-attachments.tsx | 12 + components/email/thread-conversation-view.tsx | 26 ++ components/icons/index.ts | 1 + components/settings/app-lock-settings.tsx | 5 + hooks/__tests__/use-composer-edits.test.tsx | 271 ++++++++++++++++++ hooks/use-composer-edits.ts | 217 ++++++++++++++ hooks/use-edit-attachment.ts | 50 ++++ .../__tests__/edit-attachments.test.ts | 267 +++++++++++++++++ lib/desktop/__tests__/os-commands.test.ts | 11 + lib/desktop/edit-attachments.ts | 175 +++++++++++ lib/desktop/mail-notifications.ts | 2 + lib/desktop/os-commands.ts | 5 + lib/desktop/types.ts | 66 +++++ lib/popout/open.ts | 6 + locales/ar/common.json | 35 +++ locales/ca/common.json | 35 +++ locales/cs/common.json | 35 +++ locales/da/common.json | 35 +++ locales/de/common.json | 35 +++ locales/en/common.json | 35 +++ locales/es/common.json | 35 +++ locales/et/common.json | 35 +++ locales/fa/common.json | 35 +++ locales/fr/common.json | 35 +++ locales/he/common.json | 35 +++ locales/hu/common.json | 35 +++ locales/it/common.json | 35 +++ locales/ja/common.json | 35 +++ locales/ko/common.json | 35 +++ locales/lv/common.json | 35 +++ locales/mn/common.json | 35 +++ locales/nb/common.json | 35 +++ locales/nl/common.json | 35 +++ locales/pl/common.json | 35 +++ locales/pt/common.json | 35 +++ locales/ro/common.json | 35 +++ locales/ru/common.json | 35 +++ locales/sk/common.json | 35 +++ locales/th/common.json | 35 +++ locales/tr/common.json | 35 +++ locales/uk/common.json | 35 +++ locales/vi/common.json | 35 +++ locales/zh-TW/common.json | 35 +++ locales/zh/common.json | 35 +++ 50 files changed, 2659 insertions(+) create mode 100644 components/desktop/__tests__/edited-files-host.test.tsx create mode 100644 components/desktop/edited-files-host.tsx create mode 100644 hooks/__tests__/use-composer-edits.test.tsx create mode 100644 hooks/use-composer-edits.ts create mode 100644 hooks/use-edit-attachment.ts create mode 100644 lib/desktop/__tests__/edit-attachments.test.ts create mode 100644 lib/desktop/edit-attachments.ts diff --git a/app/(main)/[locale]/layout.tsx b/app/(main)/[locale]/layout.tsx index b672dd854..ebd3dc38a 100644 --- a/app/(main)/[locale]/layout.tsx +++ b/app/(main)/[locale]/layout.tsx @@ -31,6 +31,7 @@ import { OfflineHost } from "@/components/offline/offline-host"; import { DeviceWipeHost } from "@/components/offline/device-wipe-host"; import { NotificationActionsHost } from "@/components/providers/notification-actions-host"; import { DesktopOsHost } from "@/components/desktop/desktop-os-host"; +import { EditedFilesHost } from "@/components/desktop/edited-files-host"; import { DevicePolicyHost } from "@/components/device/device-policy-host"; import { PushNotificationPrompt } from "@/components/push-notification-prompt"; import { AccountArchiveRestorePrompt } from "@/components/account-archive-prompt"; @@ -92,6 +93,7 @@ export default async function LocaleLayout({ + {!IS_LITE && } {!IS_LITE && } diff --git a/components/desktop/__tests__/edited-files-host.test.tsx b/components/desktop/__tests__/edited-files-host.test.tsx new file mode 100644 index 000000000..7e28bb6bf --- /dev/null +++ b/components/desktop/__tests__/edited-files-host.test.tsx @@ -0,0 +1,221 @@ +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const policy = vi.hoisted(() => ({ decided: true, allowed: true })); +const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() })); +const openMailLink = vi.hoisted(() => vi.fn()); +const handOffDraft = vi.hoisted(() => vi.fn()); +const openDraftWindow = vi.hoisted(() => vi.fn()); +const saveBlobAs = vi.hoisted(() => vi.fn(() => true)); +const signOutGates = vi.hoisted(() => [] as ((account: string) => Promise)[]); +const accounts = vi.hoisted(() => ({ list: [{ id: 'acct', cookieSlot: 2 }] as { id: string; cookieSlot: number }[], active: 'acct' as string | null })); + +vi.mock('next-intl', () => ({ useTranslations: () => (key: string) => key })); +vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) })); +vi.mock('@/stores/toast-store', () => ({ toast })); +vi.mock('@/lib/device-policy', () => ({ canDownload: () => policy.allowed, canExport: () => true })); +vi.mock('@/lib/offline/offline-mode', () => ({ scopeDecided: () => policy.decided })); +vi.mock('@/lib/desktop/mail-links', () => ({ openMailLink })); +vi.mock('@/lib/launch-handoff', () => ({ handOffDraft })); +vi.mock('@/lib/popout/open', () => ({ openDraftWindow })); +vi.mock('@/lib/download-guard', () => ({ saveBlobAs })); +vi.mock('@/lib/org/account-subjects', () => ({ useAccountSubjects: { subscribe: () => () => {} } })); +vi.mock('@/stores/policy-store', () => ({ usePolicyStore: { subscribe: () => () => {} } })); +vi.mock('@/lib/sign-out-cleanup', () => ({ + addSignOutGate: (gate: (account: string) => Promise) => { + signOutGates.push(gate); + return () => {}; + }, + onBeforeSignOut: () => () => {}, + onFullSignOut: () => {}, +})); +vi.mock('@/stores/account-store', () => { + const useAccountStore = (select: (s: { accounts: typeof accounts.list }) => unknown) => select({ accounts: accounts.list }); + useAccountStore.getState = () => ({ accounts: accounts.list }); + return { useAccountStore }; +}); +vi.mock('@/stores/auth-store', () => { + const useAuthStore = (select: (s: { activeAccountId: string | null }) => unknown) => select({ activeAccountId: accounts.active }); + return { useAuthStore }; +}); + +import { EditedFilesHost } from '../edited-files-host'; +import { resetEditSessions, takeFilesForReply, useEditSessions } from '@/lib/desktop/edit-attachments'; + +const session = (over: Record = {}) => ({ + id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"mail","emailId":"e1","ownerAccountId":"owner"}', changed: true, version: 1, claimed: false, ...over, +}); + +let bridge: { edit: Record>; dialogs: { confirm: ReturnType }; os: { notify: ReturnType } }; + +function show(...sessions: ReturnType[]) { + bridge.edit.list.mockResolvedValue(sessions); + useEditSessions.setState({ sessions }); + return render(); +} + +beforeEach(() => { + policy.decided = true; + policy.allowed = true; + accounts.list = [{ id: 'acct', cookieSlot: 2 }]; + accounts.active = 'acct'; + signOutGates.length = 0; + vi.clearAllMocks(); + saveBlobAs.mockReturnValue(true); + bridge = { + edit: { + canEdit: vi.fn(() => true), + begin: vi.fn(), + open: vi.fn(), + reopen: vi.fn(), + list: vi.fn(async () => []), + read: vi.fn(async () => ({ ok: true, name: 'a.docx', type: 'x/y', data: new Uint8Array([1]), hash: 'h' })), + taken: vi.fn(async () => {}), + discard: vi.fn(async () => {}), + clear: vi.fn(async () => {}), + setSource: vi.fn(), + claim: vi.fn(), + onChange: vi.fn(() => () => {}), + }, + dialogs: { confirm: vi.fn(async () => 0) }, + os: { notify: vi.fn(async () => ({ shown: true, playSound: false })) }, + }; + (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop = { version: 1, ...bridge }; + resetEditSessions(); +}); + +afterEach(() => { + cleanup(); + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; +}); + +describe('which offers show', () => { + it('a saved file nobody holds', () => { + show(session()); + expect(screen.getByTestId('edited-file')).toBeTruthy(); + }); + + it('nothing for an unchanged file or one a composer holds', () => { + show(session({ changed: false }), session({ id: 's2', claimed: true })); + expect(screen.queryByTestId('edited-file')).toBeNull(); + }); + + it('nothing for an account that is not signed in here', () => { + show(session({ account: 'someone-else' })); + expect(screen.queryByTestId('edited-file')).toBeNull(); + expect(bridge.os.notify).not.toHaveBeenCalled(); + }); + + it('nothing in a browser', () => { + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; + useEditSessions.setState({ sessions: [session()] }); + render(); + expect(screen.queryByTestId('edited-file')).toBeNull(); + }); + + it('says it once per file on the OS, whatever the number of saves', async () => { + const { rerender } = show(session()); + await waitFor(() => expect(bridge.os.notify).toHaveBeenCalledTimes(1)); + act(() => useEditSessions.setState({ sessions: [session({ version: 2 })] })); + rerender(); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(bridge.os.notify).toHaveBeenCalledTimes(1); + }); +}); + +describe('a message\'s attachment', () => { + it('attaches to a reply on that message, with that login', async () => { + show(session()); + fireEvent.click(screen.getByText('reply')); + await waitFor(() => expect(openMailLink).toHaveBeenCalled()); + const [link, options] = openMailLink.mock.calls[0]; + expect(link).toEqual({ kind: 'message', id: 'e1', slot: 2, ownerAccountId: 'owner', reply: true }); + expect(options).toEqual({ replyText: '' }); + const parked = takeFilesForReply('e1'); + expect(parked.map((f) => f.name)).toEqual(['a.docx']); + // Only the composer's having it makes it taken. + expect(bridge.edit.taken).not.toHaveBeenCalled(); + }); + + it('saves a copy through the guard, and only a saved copy counts as taken', async () => { + show(session()); + fireEvent.click(screen.getByText('save_copy')); + await waitFor(() => expect(saveBlobAs).toHaveBeenCalled()); + expect(saveBlobAs.mock.calls[0]).toEqual([expect.any(File), 'a.docx', { kind: 'attachment', subject: 'acct' }]); + expect(bridge.edit.taken).toHaveBeenCalledWith('s1', 'h'); + }); + + it('a save the guard refuses stays an offer', async () => { + saveBlobAs.mockReturnValue(false); + show(session()); + fireEvent.click(screen.getByText('save_copy')); + await waitFor(() => expect(saveBlobAs).toHaveBeenCalled()); + expect(bridge.edit.taken).not.toHaveBeenCalled(); + }); +}); + +describe('other sources', () => { + it('a closed draft opens in its window, where its chip offers the update', () => { + show(session({ source: '{"kind":"draft","draftId":"d1","ownerAccountId":"owner"}' })); + expect(screen.queryByText('reply')).toBeNull(); + fireEvent.click(screen.getByText('open_draft')); + expect(openDraftWindow).toHaveBeenCalledWith({ draftId: 'd1', localAccountId: 'acct', ownerAccountId: 'owner' }); + }); + + it('a file whose message went can start a new one', async () => { + show(session({ source: '{"kind":"file"}' })); + expect(screen.queryByText('reply')).toBeNull(); + expect(screen.queryByText('open_draft')).toBeNull(); + fireEvent.click(screen.getByText('new_message')); + await waitFor(() => expect(handOffDraft).toHaveBeenCalled()); + expect(handOffDraft.mock.calls[0][0].files[0].name).toBe('a.docx'); + }); +}); + +describe('discarding', () => { + it('asks first, with keeping as the default', async () => { + bridge.dialogs.confirm.mockResolvedValueOnce(1); + show(session()); + fireEvent.click(screen.getByRole('button', { name: 'discard a.docx' })); + await waitFor(() => expect(bridge.dialogs.confirm).toHaveBeenCalled()); + expect(bridge.dialogs.confirm.mock.calls[0][0]).toMatchObject({ defaultId: 1 }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(bridge.edit.discard).not.toHaveBeenCalled(); + + bridge.dialogs.confirm.mockResolvedValueOnce(0); + fireEvent.click(screen.getByRole('button', { name: 'discard a.docx' })); + await waitFor(() => expect(bridge.edit.discard).toHaveBeenCalledWith('s1')); + }); +}); + +describe('the organisation', () => { + it('saying no ends a session and its copy, and says so', async () => { + policy.allowed = false; + show(session()); + await waitFor(() => expect(bridge.edit.discard).toHaveBeenCalledWith('s1')); + expect(toast.error).toHaveBeenCalledWith('removed_policy'); + }); + + it('not having said yet deletes nothing, and reads nothing either', async () => { + policy.decided = false; + show(session()); + fireEvent.click(screen.getByText('save_copy')); + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('blocked_policy')); + expect(bridge.edit.discard).not.toHaveBeenCalled(); + expect(bridge.edit.read).not.toHaveBeenCalled(); + }); +}); + +describe('signing out', () => { + it('asks only with edits nobody took, in the account going', async () => { + show(session({ account: 'acct' }), session({ id: 's2', account: 'other', changed: false })); + expect(signOutGates).toHaveLength(1); + bridge.dialogs.confirm.mockResolvedValueOnce(1); + await expect(signOutGates[0]('acct')).resolves.toBe(false); + bridge.dialogs.confirm.mockResolvedValueOnce(0); + await expect(signOutGates[0]('acct')).resolves.toBe(true); + bridge.dialogs.confirm.mockClear(); + await expect(signOutGates[0]('other')).resolves.toBe(true); + expect(bridge.dialogs.confirm).not.toHaveBeenCalled(); + }); +}); diff --git a/components/desktop/edited-files-host.tsx b/components/desktop/edited-files-host.tsx new file mode 100644 index 000000000..68395f322 --- /dev/null +++ b/components/desktop/edited-files-host.tsx @@ -0,0 +1,189 @@ +"use client"; + +import { useEffect, useMemo, useRef, useState } from "react"; +import { useTranslations } from "next-intl"; +import { FilePen, X } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { useRouter } from "@/i18n/navigation"; +import { getDesktopBridge } from "@/lib/desktop/bridge"; +import { editForbidden, followEditSessions, getEditBridge, parkFilesForReply, parseEditSource, readEditedFile, useEditSessions } from "@/lib/desktop/edit-attachments"; +import { openMailLink } from "@/lib/desktop/mail-links"; +import type { DesktopEditSession } from "@/lib/desktop/types"; +import { saveBlobAs } from "@/lib/download-guard"; +import { handOffDraft } from "@/lib/launch-handoff"; +import { useAccountSubjects } from "@/lib/org/account-subjects"; +import { openDraftWindow } from "@/lib/popout/open"; +import { addSignOutGate } from "@/lib/sign-out-cleanup"; +import { useAccountStore } from "@/stores/account-store"; +import { useAuthStore } from "@/stores/auth-store"; +import { usePolicyStore } from "@/stores/policy-store"; +import { toast } from "@/stores/toast-store"; + +function useSignedInAccounts(): Set { + const accounts = useAccountStore((s) => s.accounts); + const active = useAuthStore((s) => s.activeAccountId); + return useMemo(() => new Set([...accounts.map((a) => a.id), ...(active ? [active] : [])]), [accounts, active]); +} + +/** + * Attachments opened with Edit and saved in their program, with what can be done with them. + * A composer offers its own files on the chip, so this has what no composer holds. It stays + * until the user has decided: a save may come at any time, also while the app was closed. + * Only for accounts signed in here: someone else signing in doesn't see these. + * Main window only, and nothing at all in a browser. + */ +export function EditedFilesHost() { + const t = useTranslations("desktopEdit"); + const router = useRouter(); + const tRef = useRef(t); + tRef.current = t; + const sessions = useEditSessions((s) => s.sessions); + const accounts = useSignedInAccounts(); + const [busy, setBusy] = useState(null); + const available = !!getEditBridge(); + + useEffect(() => { + if (available) followEditSessions(); + }, [available]); + + const offers = useMemo(() => sessions.filter((s) => s.changed && !s.claimed && accounts.has(s.account)), [sessions, accounts]); + + // Whoever is in the other program sees this. Once per file, not at every save. + const toldRef = useRef(new Set()); + useEffect(() => { + const os = getDesktopBridge()?.os; + for (const session of offers) { + if (toldRef.current.has(session.id)) continue; + toldRef.current.add(session.id); + void os?.notify({ + id: `edit-${session.id}`, + title: tRef.current("changed_title", { name: session.name }), + body: tRef.current("changed_body"), + context: JSON.stringify({ editedFile: true }), + }).catch(() => {}); + } + }, [offers]); + + // The organisation's no ends a session, also one with a file open and edits in it. + useEffect(() => { + const bridge = getEditBridge(); + if (!bridge) return; + const enforce = () => { + for (const session of useEditSessions.getState().sessions) { + if (!editForbidden(session.account)) continue; + void bridge.discard(session.id); + toast.error(tRef.current("removed_policy", { name: session.name })); + } + }; + enforce(); + const stops = [usePolicyStore.subscribe(enforce), useAccountSubjects.subscribe(enforce), useEditSessions.subscribe(enforce)]; + return () => stops.forEach((stop) => stop()); + }, []); + + // Edits nobody took: asks before a sign-out the user started. A wipe doesn't. + useEffect(() => { + if (!getEditBridge()) return; + return addSignOutGate(async (accountId) => { + const waiting = useEditSessions.getState().sessions.filter((s) => s.account === accountId && s.changed); + const dialogs = getDesktopBridge()?.dialogs; + if (waiting.length === 0 || !dialogs) return true; + const buttons = [tRef.current("signout_confirm"), tRef.current("cancel")]; + const choice = await dialogs.confirm({ + type: "warning", + message: tRef.current("signout_title"), + detail: tRef.current("signout_detail"), + buttons, + defaultId: 1, + }); + return choice === 0; + }); + }, []); + + if (!available || offers.length === 0) return null; + + const withFile = async (session: DesktopEditSession, then: (file: File, hash: string) => void) => { + setBusy(session.id); + try { + const outcome = await readEditedFile(session); + if (outcome.ok) then(outcome.file, outcome.hash); + else if (outcome.reason === "policy") toast.error(t("blocked_policy")); + else if (outcome.reason === "busy") toast.error(t("read_busy", { name: session.name })); + else if (outcome.reason !== "locked") toast.error(t("read_failed", { name: session.name })); + } catch (error) { + console.error("Could not read an edited file:", error); + toast.error(t("read_failed", { name: session.name })); + } finally { + setBusy(null); + } + }; + + const attachToReply = (session: DesktopEditSession, emailId: string, ownerAccountId: string | undefined) => withFile(session, (file) => { + parkFilesForReply(emailId, [file]); + const slot = useAccountStore.getState().accounts.find((a) => a.id === session.account)?.cookieSlot; + openMailLink( + { kind: "message", id: emailId, ...(slot !== undefined ? { slot } : {}), ownerAccountId, reply: true }, + { replyText: "" }, + (path) => router.push(path), + ); + }); + + const saveCopy = (session: DesktopEditSession) => withFile(session, (file, hash) => { + if (saveBlobAs(file, file.name, { kind: "attachment", subject: session.account })) void getEditBridge()?.taken(session.id, hash); + }); + + const discard = async (session: DesktopEditSession) => { + const bridge = getDesktopBridge(); + const choice = await bridge?.dialogs?.confirm({ + type: "warning", + message: t("discard_title", { name: session.name }), + detail: t("discard_detail"), + buttons: [t("discard_confirm"), t("cancel")], + defaultId: 1, + }); + if (choice === 0) await getEditBridge()?.discard(session.id); + }; + + return ( +
+ {offers.map((session) => { + const source = parseEditSource(session.source); + return ( +
+
+
+
+ {source.kind === "mail" && ( + + )} + {source.kind === "draft" && source.draftId && ( + + )} + {(source.kind === "file" || (source.kind === "draft" && !source.draftId)) && ( + + )} + +
+
+ ); + })} +
+ ); +} diff --git a/components/email/__tests__/reader-attachments.test.tsx b/components/email/__tests__/reader-attachments.test.tsx index 67c6913e7..9bb922889 100644 --- a/components/email/__tests__/reader-attachments.test.tsx +++ b/components/email/__tests__/reader-attachments.test.tsx @@ -55,6 +55,24 @@ describe('the right-click menu in the desktop app', () => { expect(popup.mock.calls[0][0].map((item) => item.label)).toEqual(['open']); }); + it('Edit shows when the file can be edited and runs the action', async () => { + const onEdit = vi.fn(); + const { props, popup } = await openMenu((items) => items.find((i) => i.label === 'edit')?.id ?? null, { onEdit, canEdit: () => true }); + const labels = popup.mock.calls[0][0].flatMap((i: { label?: string }) => (i.label ? [i.label] : [])); + expect(labels).toEqual(['open', 'save_as', 'edit', 'copy']); + await waitFor(() => expect(onEdit).toHaveBeenCalledWith(props.attachments[0])); + }); + + it('Edit stays out for a file it cannot take', async () => { + const { popup } = await openMenu(() => null, { onEdit: vi.fn(), canEdit: () => false }); + expect(popup.mock.calls[0][0].map((i: { label?: string }) => i.label)).not.toContain('edit'); + }); + + it('Edit stays out with downloads off, whatever else says yes', async () => { + const { popup } = await openMenu(() => null, { onEdit: vi.fn(), canEdit: () => true, downloadsOff: true }); + expect(popup.mock.calls[0][0].map((i: { label?: string }) => i.label)).not.toContain('edit'); + }); + it('a browser keeps its own menu', async () => { window.bulwarkDesktop = undefined; renderBar([file('1', 'report.pdf')], { onCopyFile: vi.fn() }); diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx index 03d657ade..beb816e70 100644 --- a/components/email/email-composer.tsx +++ b/components/email/email-composer.tsx @@ -15,6 +15,7 @@ import { Input } from "@/components/ui/input"; import { X, Paperclip, + FilePen, Send, Save, Check, @@ -178,6 +179,7 @@ import { noteOpenDraft } from "@/lib/desktop/window-restore"; import type { RescuedDraft } from "@/lib/popout/channel"; import { toUnicodeEmail } from "@/lib/idn"; import { setComposerFileTarget } from "@/lib/desktop/window-files"; +import { useComposerEdits } from "@/hooks/use-composer-edits"; // A Pro tab, message or folder dragged across a composer tab is on its way to // the pane or the split edge: those drags belong to the shell. There is no shell @@ -480,6 +482,8 @@ interface EmailComposerProps { type ComposerAttachment = { file?: File; + // The desktop app's Edit: which session's file this is. See useComposerEdits. + editSessionId?: string; // Login whose server holds `blobId`, set for parts of the original message // on a forward - the message may go out through another account, which // cannot resolve them. See rehomeForeignBlobs. @@ -580,6 +584,7 @@ export function EmailComposer({ const tQuote = useTranslations('quote_header'); const tViewer = useTranslations('email_viewer'); const tClassification = useTranslations('classification'); + const tEdit = useTranslations('desktopEdit'); const tProofreading = useTranslations('proofreading'); const tOfflineDrafts = useTranslations('offlineDrafts'); const tOffline = useTranslations('offline'); @@ -2745,6 +2750,22 @@ export function EmailComposer({ const [composerRootEl, setComposerRootEl] = useState(null); // The desktop app: files dropped or pasted anywhere on the window come here, if this one's on screen. + const loadAttachmentForEdit = useCallback(async (att: ComposerAttachment): Promise => { + if (att.file) return att.file; + if (!composerClient || !att.blobId) throw new Error('No content for this attachment'); + return composerClient.fetchBlob(att.blobId, att.name, att.type); + }, [composerClient]); + const composerEdits = useComposerEdits({ + attachments, + setAttachments, + addFiles, + load: loadAttachmentForEdit, + account: composerAccountId ?? '', + draftId, + ownerAccountId: draftAccountId, + repliesTo: mode === 'reply' || mode === 'replyAll' ? sourceEmailId : undefined, + ready: !!client, + }); useEffect(() => setComposerFileTarget( (files) => void addFiles(files), () => !!composerRootEl?.isConnected && composerRootEl.getClientRects().length > 0, @@ -3707,6 +3728,9 @@ export function EmailComposer({ } = {}) => { if (isSendingRef.current) return; + // Saved in another program and not on this message yet: not silently the older one. + if (!(await composerEdits.confirmSend())) return; + if (attachmentsRef.current.some(att => att.uploading)) { isSendingRef.current = true; setIsSending(true); @@ -4242,6 +4266,7 @@ export function EmailComposer({ } } + composerEdits.finish(); setTo([]); setCc([]); setBcc([]); @@ -4483,6 +4508,7 @@ export function EmailComposer({ attachment.abortController?.abort(); } setShowCloseDialog(false); + composerEdits.finish(); if (saveTimeoutRef.current) { clearTimeout(saveTimeoutRef.current); } @@ -5391,6 +5417,28 @@ export function EmailComposer({ ) : (
{label}
)} + {composerEdits.hasUpdate(att) && !att.uploading && ( + + )} + {!att.uploading && !att.error && composerEdits.canEdit(att.name) && ( + + )} + {blobClient && attachment.blobId && !phishingMarked && canEditAttachment(attachment.name) && ( + + )} ); diff --git a/components/icons/index.ts b/components/icons/index.ts index 91c72ea58..2068d465e 100644 --- a/components/icons/index.ts +++ b/components/icons/index.ts @@ -87,6 +87,7 @@ export { IconDatabase as Database, IconDownload as Download, IconEdit as EditIcon, + IconFilePencil as FilePen, IconDots as Ellipsis, IconEraser as Eraser, IconExternalLink as ExternalLink, diff --git a/components/settings/app-lock-settings.tsx b/components/settings/app-lock-settings.tsx index bdc126f30..d68ac012c 100644 --- a/components/settings/app-lock-settings.tsx +++ b/components/settings/app-lock-settings.tsx @@ -39,6 +39,7 @@ function useLockFacts() { /** The app lock's section on the General page: it has to exist on any server. */ export function AppLockSettings() { const t = useTranslations("appLock"); + const tEdit = useTranslations("desktopEdit"); const { appName } = useConfig(); const { on, required, timeout, update } = useLockFacts(); const [pending, setPending] = useState(null); @@ -178,6 +179,10 @@ export function AppLockSettings() { )} + {on && getDesktopBridge()?.edit && ( +

{tEdit("lock_note")}

+ )} + ({ allowed: true })); +const toastError = vi.hoisted(() => vi.fn()); + +vi.mock('next-intl', () => ({ useTranslations: () => (key: string) => key })); +vi.mock('@/stores/toast-store', () => ({ toast: { error: toastError, success: vi.fn() } })); +vi.mock('@/hooks/use-device-policy', () => ({ + useDevicePolicy: () => ({ noDownloads: !policy.allowed, noExport: false }), +})); +vi.mock('@/lib/device-policy', () => ({ + canDownload: () => policy.allowed, + canExport: () => true, + deviceSubjectOf: () => null, +})); +vi.mock('@/lib/offline/offline-mode', () => ({ scopeDecided: () => true })); +vi.mock('@/stores/auth-store', () => ({ useAuthStore: { getState: () => ({ activeAccountId: 'acct' }) } })); + +import { useComposerEdits, type EditableAttachment } from '../use-composer-edits'; +import { parkFilesForReply, readEditedFile, resetEditSessions, useEditSessions } from '@/lib/desktop/edit-attachments'; + +function fakeBridge() { + return { + canEdit: vi.fn((name: string) => !name.endsWith('.exe')), + begin: vi.fn(async () => ({ ok: true as const, ticket: 't1' })), + open: vi.fn(async () => ({ ok: true as const, id: 's1' })), + reopen: vi.fn(async () => ({ ok: true as const, id: 's1' })), + list: vi.fn(async () => []), + read: vi.fn(async () => ({ ok: true as const, name: 'a.docx', type: 'x/y', data: new Uint8Array([1, 2]), hash: 'h2' })), + taken: vi.fn(async () => {}), + discard: vi.fn(async () => {}), + clear: vi.fn(async () => {}), + setSource: vi.fn(), + claim: vi.fn(), + onChange: vi.fn(() => () => {}), + }; +} + +let bridge: ReturnType; +let confirm: ReturnType; + +const session = (over: Partial<{ id: string; name: string; source: string; changed: boolean; claimed: boolean }> = {}) => ({ + id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"draft","draftId":"d1"}', changed: false, version: 0, claimed: true, ...over, +}); + +interface Setup { + start: EditableAttachment[]; + draftId?: string | null; + repliesTo?: string; + /** What the composer's upload does with a file. */ + upload?: (file: File) => Partial; +} + +function setup({ start, draftId = 'd1', repliesTo, upload = () => ({ blobId: 'new-blob' }) }: Setup) { + const load = vi.fn(async () => new Blob(['x'])); + bridge.list.mockResolvedValue(useEditSessions.getState().sessions as never); + return renderHook(() => { + const [attachments, setAttachments] = useState(start); + const addFiles = async (files: File[]) => { + setAttachments((list) => [...list, ...files.map((file) => ({ file, name: file.name, type: file.type, uploading: false, ...upload(file) }))]); + }; + const edits = useComposerEdits({ attachments, setAttachments, addFiles, load, account: 'acct', draftId, repliesTo, ready: true }); + return { attachments, setAttachments, edits }; + }); +} + +beforeEach(() => { + policy.allowed = true; + bridge = fakeBridge(); + confirm = vi.fn(async () => 0); + (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop = { version: 1, edit: bridge, dialogs: { confirm } }; + resetEditSessions(); + toastError.mockClear(); +}); + +afterEach(() => { + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; +}); + +describe('updating a chip', () => { + const chip: EditableAttachment = { name: 'a.docx', type: 'x/y', blobId: 'old-blob', editSessionId: 's1' }; + + it('takes the old file off only once the new one is up, and marks that version as taken', async () => { + useEditSessions.setState({ sessions: [session({ changed: true })] }); + const { result } = setup({ start: [chip] }); + expect(result.current.edits.hasUpdate(result.current.attachments[0])).toBe(true); + await act(() => result.current.edits.update(result.current.attachments[0])); + await waitFor(() => expect(result.current.attachments).toHaveLength(1)); + const [only] = result.current.attachments; + expect(only.blobId).toBe('new-blob'); + expect(only.file?.name).toBe('a.docx'); + await waitFor(() => expect(only.editSessionId ?? result.current.attachments[0].editSessionId).toBe('s1')); + await waitFor(() => expect(bridge.taken).toHaveBeenCalledWith('s1', 'h2')); + // Stays held by the composer throughout: it's the same session. + expect(bridge.discard).not.toHaveBeenCalled(); + }); + + it('keeps the old file and the offer when the upload fails', async () => { + useEditSessions.setState({ sessions: [session({ changed: true })] }); + const { result } = setup({ start: [chip], upload: () => ({ error: true }) }); + await act(() => result.current.edits.update(result.current.attachments[0])); + await waitFor(() => expect(result.current.attachments).toHaveLength(1)); + expect(result.current.attachments[0].blobId).toBe('old-blob'); + expect(result.current.edits.hasUpdate(result.current.attachments[0])).toBe(true); + expect(bridge.taken).not.toHaveBeenCalled(); + }); + + it('says so when the program still holds the file', async () => { + bridge.read.mockResolvedValueOnce({ ok: false, reason: 'busy' } as never); + useEditSessions.setState({ sessions: [session({ changed: true })] }); + const { result } = setup({ start: [chip] }); + await act(() => result.current.edits.update(result.current.attachments[0])); + expect(toastError).toHaveBeenCalledWith('read_busy'); + expect(result.current.attachments[0].blobId).toBe('old-blob'); + }); + + it('refuses when the organisation has said no since', async () => { + policy.allowed = false; + useEditSessions.setState({ sessions: [session({ changed: true })] }); + const { result } = setup({ start: [chip] }); + await act(() => result.current.edits.update(result.current.attachments[0])); + expect(bridge.read).not.toHaveBeenCalled(); + expect(toastError).toHaveBeenCalledWith('blocked_policy'); + expect(result.current.attachments).toHaveLength(1); + }); +}); + +describe('starting from a chip', () => { + it('fetches a server part, and the chip takes the session on', async () => { + const { result } = setup({ start: [{ name: 'a.docx', type: 'x/y', blobId: 'b1' }] }); + await act(() => result.current.edits.startEdit(result.current.attachments[0])); + expect(bridge.begin).toHaveBeenCalledWith('blob:acct:b1'); + await waitFor(() => expect(result.current.attachments[0].editSessionId).toBe('s1')); + expect(bridge.claim).toHaveBeenCalledWith('s1', true); + const [, file] = bridge.open.mock.calls[0] as unknown as [string, { source: string }]; + expect(JSON.parse(file.source)).toEqual({ kind: 'draft', draftId: 'd1' }); + }); + + it('a chip with a session goes back to that session', async () => { + const { result } = setup({ start: [{ name: 'a.docx', type: 'x/y', blobId: 'b1', editSessionId: 's1' }] }); + await act(() => result.current.edits.startEdit(result.current.attachments[0])); + expect(bridge.begin).toHaveBeenCalledWith('session:s1'); + }); + + it('offers it only for what the shell and the organisation allow', () => { + const { result } = setup({ start: [] }); + expect(result.current.edits.canEdit('a.docx')).toBe(true); + expect(result.current.edits.canEdit('a.exe')).toBe(false); + }); + + it('offers nothing under a policy', () => { + policy.allowed = false; + const { result } = setup({ start: [] }); + expect(result.current.edits.canEdit('a.docx')).toBe(false); + }); +}); + +describe('holding sessions', () => { + it('claims what is on a chip, follows the draft id, and lets go when it closes, which is no end', async () => { + const { result, rerender, unmount } = setup({ start: [{ name: 'a.docx', type: 'x/y', blobId: 'b', editSessionId: 's1' }] }); + expect(bridge.claim).toHaveBeenCalledWith('s1', true); + expect(bridge.setSource).toHaveBeenCalledWith('s1', JSON.stringify({ kind: 'draft', draftId: 'd1' })); + rerender(); + expect(result.current.attachments).toHaveLength(1); + unmount(); + expect(bridge.claim).toHaveBeenLastCalledWith('s1', false); + expect(bridge.discard).not.toHaveBeenCalled(); + }); + + it('a chip taken off: an unchanged copy goes, an edited one stays for the offers', async () => { + useEditSessions.setState({ sessions: [session({ id: 's1' }), session({ id: 's2', name: 'b.docx', changed: true })] }); + const { result } = setup({ start: [ + { name: 'a.docx', type: 'x/y', blobId: 'b', editSessionId: 's1' }, + { name: 'b.docx', type: 'x/y', blobId: 'c', editSessionId: 's2' }, + ] }); + act(() => result.current.setAttachments([])); + await waitFor(() => expect(bridge.discard).toHaveBeenCalledWith('s1')); + expect(bridge.discard).not.toHaveBeenCalledWith('s2'); + expect(bridge.setSource).toHaveBeenCalledWith('s2', JSON.stringify({ kind: 'file' })); + }); + + it('a draft opened again finds its session by id and name', async () => { + useEditSessions.setState({ sessions: [session({ claimed: false, changed: true })] }); + const { result } = setup({ start: [{ name: 'other.pdf', type: 'x/y', blobId: 'z' }, { name: 'a.docx', type: 'x/y', blobId: 'b' }] }); + await waitFor(() => expect(result.current.attachments[1].editSessionId).toBe('s1')); + expect(result.current.attachments[0].editSessionId).toBeUndefined(); + expect(result.current.edits.hasUpdate(result.current.attachments[1])).toBe(true); + }); + + it('another draft leaves it alone', async () => { + useEditSessions.setState({ sessions: [session({ claimed: false, source: '{"kind":"draft","draftId":"other"}' })] }); + const { result } = setup({ start: [{ name: 'a.docx', type: 'x/y', blobId: 'b' }] }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(result.current.attachments[0].editSessionId).toBeUndefined(); + }); +}); + +describe('sending', () => { + const chip: EditableAttachment = { name: 'a.docx', type: 'x/y', blobId: 'b', editSessionId: 's1' }; + + it('goes on without a question when nothing waits', async () => { + useEditSessions.setState({ sessions: [session()] }); + const { result } = setup({ start: [chip] }); + await expect(result.current.edits.confirmSend()).resolves.toBe(true); + expect(confirm).not.toHaveBeenCalled(); + }); + + it('asks before an older version goes out, with going back as the default', async () => { + useEditSessions.setState({ sessions: [session({ changed: true })] }); + const { result } = setup({ start: [chip] }); + confirm.mockResolvedValueOnce(1); + await expect(result.current.edits.confirmSend()).resolves.toBe(false); + expect(confirm.mock.calls[0][0]).toMatchObject({ buttons: ['send_stale_send', 'send_stale_back'], defaultId: 1 }); + confirm.mockResolvedValueOnce(0); + await expect(result.current.edits.confirmSend()).resolves.toBe(true); + }); + + it('sent or discarded: an unchanged copy goes, edits nobody took stay and lose their draft', async () => { + useEditSessions.setState({ sessions: [session({ id: 's1' }), session({ id: 's2', name: 'b.docx', changed: true })] }); + const { result } = setup({ start: [chip, { name: 'b.docx', type: 'x/y', blobId: 'c', editSessionId: 's2' }] }); + act(() => result.current.edits.finish()); + expect(bridge.discard).toHaveBeenCalledWith('s1'); + expect(bridge.discard).not.toHaveBeenCalledWith('s2'); + expect(bridge.claim).toHaveBeenCalledWith('s2', false); + expect(bridge.setSource).toHaveBeenCalledWith('s2', JSON.stringify({ kind: 'file' })); + }); +}); + +describe('a reply from an offer', () => { + it('takes the waiting file, and the session comes with it', async () => { + const outcome = await readEditedFile({ id: 's1', account: 'acct' }); + if (!outcome.ok) throw new Error('refused'); + parkFilesForReply('e1', [outcome.file]); + const { result } = setup({ start: [], repliesTo: 'e1', draftId: null }); + await waitFor(() => expect(result.current.attachments.map((a) => a.name)).toEqual(['a.docx'])); + await waitFor(() => expect(result.current.attachments[0].editSessionId).toBe('s1')); + await waitFor(() => expect(bridge.taken).toHaveBeenCalledWith('s1', 'h2')); + expect(bridge.claim).toHaveBeenCalledWith('s1', true); + }); + + it('a version counts as taken only once it is up', async () => { + const outcome = await readEditedFile({ id: 's1', account: 'acct' }); + if (!outcome.ok) throw new Error('refused'); + parkFilesForReply('e1', [outcome.file]); + const { result } = setup({ start: [], repliesTo: 'e1', draftId: null, upload: () => ({ uploading: true }) }); + await waitFor(() => expect(result.current.attachments[0]?.editSessionId).toBe('s1')); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(bridge.taken).not.toHaveBeenCalled(); + act(() => result.current.setAttachments((list) => list.map((att) => ({ ...att, uploading: false, blobId: 'up' })))); + await waitFor(() => expect(bridge.taken).toHaveBeenCalledWith('s1', 'h2')); + }); + + it('a reply to another message leaves it waiting', async () => { + parkFilesForReply('e1', [new File(['x'], 'a.docx')]); + const { result } = setup({ start: [], repliesTo: 'e2', draftId: null }); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(result.current.attachments).toEqual([]); + }); +}); + +describe('in a browser', () => { + it('nothing happens at all', () => { + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; + const { result } = setup({ start: [{ name: 'a.docx', type: 'x/y', blobId: 'b' }] }); + expect(result.current.edits.canEdit('a.docx')).toBe(false); + expect(result.current.attachments[0].editSessionId).toBeUndefined(); + expect(() => result.current.edits.finish()).not.toThrow(); + }); +}); diff --git a/hooks/use-composer-edits.ts b/hooks/use-composer-edits.ts new file mode 100644 index 000000000..9350e96a1 --- /dev/null +++ b/hooks/use-composer-edits.ts @@ -0,0 +1,217 @@ +"use client"; + +import { useCallback, useEffect, useRef, type Dispatch, type SetStateAction } from "react"; +import { useTranslations } from "next-intl"; +import { editFileInfo, followEditSessions, getEditBridge, parseEditSource, readEditedFile, takeFilesForReply, useEditSessions, type EditSource } from "@/lib/desktop/edit-attachments"; +import { getDesktopBridge } from "@/lib/desktop/bridge"; +import { useEditAttachment } from "@/hooks/use-edit-attachment"; +import { toast } from "@/stores/toast-store"; + +/** What this needs from a composer's attachment. */ +export interface EditableAttachment { + file?: File; + name: string; + type: string; + blobId?: string; + uploading?: boolean; + error?: boolean; + /** The Edit session this chip's file belongs to. Kept through every state change of the chip. */ + editSessionId?: string; +} + +interface Options { + attachments: A[]; + setAttachments: Dispatch>; + addFiles: (files: File[]) => Promise; + load: (attachment: A) => Promise; + /** The local account the draft goes through. */ + account: string; + draftId: string | null; + ownerAccountId?: string; + /** The message a reply answers: a file waiting for that reply lands here. */ + repliesTo?: string; + /** Only once the composer can upload. */ + ready: boolean; +} + +/** + * A composer's part of Edit: its chips start sessions and hold them, so the offer to update + * sits on the chip rather than in the main window. A session goes when the draft is sent or + * discarded, unless it has edits nobody took: those stay, for the user to decide on. + */ +export function useComposerEdits({ attachments, setAttachments, addFiles, load, account, draftId, ownerAccountId, repliesTo, ready }: Options) { + const t = useTranslations("desktopEdit"); + const { canEdit, edit } = useEditAttachment(account); + const available = getEditBridge() !== null; + const sessions = useEditSessions((s) => s.sessions); + const instanceRef = useRef(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`); + const heldRef = useRef(new Set()); + const takenRef = useRef(new WeakSet()); + const latest = useRef({ attachments, sessions }); + latest.current = { attachments, sessions }; + + useEffect(() => { + if (available) followEditSessions(); + }, [available]); + + // A file the user sent into a reply from an offer. + const repliedRef = useRef(false); + useEffect(() => { + if (!available || !ready || repliedRef.current || !repliesTo) return; + repliedRef.current = true; + const files = takeFilesForReply(repliesTo); + if (files.length > 0) void addFiles(files); + }, [available, ready, repliesTo, addFiles]); + + // A file read back from a session: its chip takes the session on, and once it's up the + // version it holds is no longer a change. + useEffect(() => { + if (!available) return; + const untagged = attachments.some((att) => !att.editSessionId && editFileInfo(att.file)); + if (untagged) { + setAttachments((list) => list.map((att) => { + const info = att.editSessionId ? undefined : editFileInfo(att.file); + return info ? { ...att, editSessionId: info.id } : att; + })); + } + for (const att of attachments) { + const info = editFileInfo(att.file); + if (!info || !att.file || !att.blobId || att.uploading || att.error || takenRef.current.has(att.file)) continue; + takenRef.current.add(att.file); + void getEditBridge()?.taken(info.id, info.hash); + } + }, [available, attachments, setAttachments]); + + // A draft opened again finds its sessions by the draft's id and the file's name. + useEffect(() => { + if (!available || !draftId) return; + const mine = sessions.filter((session) => { + const source = parseEditSource(session.source); + return source.kind === "draft" && source.draftId === draftId && !session.claimed; + }); + if (mine.length === 0) return; + setAttachments((list) => { + let changed = false; + const next = list.map((att) => { + if (att.editSessionId) return att; + const match = mine.find((session) => session.name === att.name && !list.some((other) => other.editSessionId === session.id)); + if (!match) return att; + changed = true; + return { ...att, editSessionId: match.id }; + }); + return changed ? next : list; + }); + }, [available, draftId, sessions, setAttachments]); + + // Holds what's on a chip. One taken off a chip goes unless it has edits, which stay in the offers. + const heldIds = attachments.flatMap((att) => (att.editSessionId ? [att.editSessionId] : [])); + const heldKey = [...new Set(heldIds)].sort().join("\n"); + useEffect(() => { + const bridge = getEditBridge(); + if (!bridge) return; + const now = new Set(heldKey ? heldKey.split("\n") : []); + for (const id of now) { + if (!heldRef.current.has(id)) bridge.claim(id, true); + } + for (const id of heldRef.current) { + if (now.has(id)) continue; + bridge.claim(id, false); + const session = latest.current.sessions.find((s) => s.id === id); + if (session?.changed) bridge.setSource(id, JSON.stringify({ kind: "file" } satisfies EditSource)); + else if (session) void bridge.discard(id); + } + heldRef.current = now; + }, [heldKey]); + + // Follows the draft's id, which changes with every save. + useEffect(() => { + const bridge = getEditBridge(); + if (!bridge || !heldKey) return; + const source = JSON.stringify({ kind: "draft", draftId, ownerAccountId } satisfies EditSource); + for (const id of heldKey.split("\n")) bridge.setSource(id, source); + }, [heldKey, draftId, ownerAccountId]); + + // Closing the composer isn't an end: the draft may be opened again. + useEffect(() => () => { + const bridge = getEditBridge(); + for (const id of heldRef.current) bridge?.claim(id, false); + heldRef.current = new Set(); + }, []); + + const sessionOf = useCallback((att: A) => (att.editSessionId ? sessions.find((s) => s.id === att.editSessionId) : undefined), [sessions]); + + /** Whether this chip has saved edits to take. */ + const hasUpdate = useCallback((att: A) => sessionOf(att)?.changed === true, [sessionOf]); + + const startEdit = useCallback(async (att: A) => { + const key = att.editSessionId + ? `session:${att.editSessionId}` + : att.blobId ? `blob:${account}:${att.blobId}` : `composer:${instanceRef.current}:${att.name}`; + const result = await edit({ + key, + name: att.name, + type: att.type, + account, + source: { kind: "draft", draftId, ownerAccountId }, + load: () => load(att), + }); + if (result.ok) { + setAttachments((list) => list.map((item) => ( + (att.file ? item.file === att.file : item.blobId === att.blobId) ? { ...item, editSessionId: result.id } : item + ))); + } + }, [account, draftId, edit, load, ownerAccountId, setAttachments]); + + /** The edited file goes up first. Only then does the old one come off, so a failed upload loses nothing. */ + const update = useCallback(async (att: A) => { + const id = att.editSessionId; + if (!id) return; + const outcome = await readEditedFile({ id, account }); + if (!outcome.ok) { + toast.error(t(outcome.reason === "busy" ? "read_busy" : outcome.reason === "policy" ? "blocked_policy" : "read_failed", { name: att.name })); + return; + } + const { file } = outcome; + await addFiles([file]); + setAttachments((list) => { + const added = list.find((item) => item.file === file); + if (added?.blobId && !added.error) return list.filter((item) => item.file === file || item.editSessionId !== id); + return list.filter((item) => item.file !== file); + }); + }, [account, addFiles, setAttachments, t]); + + /** Edits on the way out in an older version: asks first. False: don't send. */ + const confirmSend = useCallback(async (): Promise => { + const { attachments: list, sessions: all } = latest.current; + const stale = list.flatMap((att) => { + const session = att.editSessionId ? all.find((s) => s.id === att.editSessionId) : undefined; + return session?.changed ? [session] : []; + }); + const dialogs = getDesktopBridge()?.dialogs; + if (stale.length === 0 || !dialogs) return true; + const choice = await dialogs.confirm({ + type: "warning", + message: t("send_stale_title", { name: stale[0].name }), + detail: t("send_stale_detail"), + buttons: [t("send_stale_send"), t("send_stale_back")], + defaultId: 1, + }); + return choice === 0; + }, [t]); + + /** The draft was sent or discarded. Reads no state of the component: this can run after it has gone. */ + const finish = useCallback(() => { + const bridge = getEditBridge(); + if (!bridge) return; + const { attachments: list, sessions: all } = latest.current; + const ids = new Set(list.flatMap((att) => (att.editSessionId ? [att.editSessionId] : []))); + for (const id of ids) { + heldRef.current.delete(id); + bridge.claim(id, false); + if (all.find((s) => s.id === id)?.changed) bridge.setSource(id, JSON.stringify({ kind: "file" } satisfies EditSource)); + else void bridge.discard(id); + } + }, []); + + return { canEdit, startEdit, hasUpdate, update, confirmSend, finish }; +} diff --git a/hooks/use-edit-attachment.ts b/hooks/use-edit-attachment.ts new file mode 100644 index 000000000..d6bb71d0a --- /dev/null +++ b/hooks/use-edit-attachment.ts @@ -0,0 +1,50 @@ +"use client"; + +import { useCallback } from "react"; +import { useTranslations } from "next-intl"; +import { canEditFile, editAllowed, startAttachmentEdit, type EditStartResult, type StartEditInput } from "@/lib/desktop/edit-attachments"; +import { deviceSubjectOf } from "@/lib/device-policy"; +import { useDevicePolicy } from "@/hooks/use-device-policy"; +import { useAuthStore } from "@/stores/auth-store"; +import { toast } from "@/stores/toast-store"; + +const FAILURE_KEYS: Partial["reason"], string>> = { + policy: "blocked_policy", + "no-app": "no_app", + type: "blocked_type", + "too-large": "too_large", + full: "too_many", +}; + +/** The local account a message or a draft belongs to, where a copy of its file is filed. */ +export function editAccountOf(email: { sourceClientAccountId?: string | null } | null | undefined): string { + return deviceSubjectOf(email) ?? useAuthStore.getState().activeAccountId ?? ""; +} + +/** + * Edit, for whatever shows an attachment: whether to offer it, and starting it with the app's + * words for how it went. `account` is the local account the attachment belongs to; the + * hook follows that account's policy, so the item goes as soon as the answer turns to no. + */ +export function useEditAttachment(account: string) { + const t = useTranslations("desktopEdit"); + const devices = useDevicePolicy(account || null); + const offered = !devices.noDownloads && !devices.noExport; + const canEdit = useCallback((name: string | null | undefined) => ( + offered && !!account && canEditFile(name) && editAllowed(account) + ), [offered, account]); + const edit = useCallback(async (input: StartEditInput): Promise => { + let result: EditStartResult; + try { + result = await startAttachmentEdit(input); + } catch (error) { + console.error("Could not open an attachment for editing:", error); + result = { ok: false, reason: "failed" }; + } + if (result.ok) toast.success(t("opened", { name: input.name })); + // Locked: the lock screen is what's saying it. + else if (result.reason !== "locked") toast.error(t(FAILURE_KEYS[result.reason] ?? "failed")); + return result; + }, [t]); + return { canEdit, edit }; +} diff --git a/lib/desktop/__tests__/edit-attachments.test.ts b/lib/desktop/__tests__/edit-attachments.test.ts new file mode 100644 index 000000000..5201f9bcc --- /dev/null +++ b/lib/desktop/__tests__/edit-attachments.test.ts @@ -0,0 +1,267 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const policy = vi.hoisted(() => ({ decided: true, download: true, export: true })); + +vi.mock('@/lib/device-policy', () => ({ + canDownload: () => policy.download, + canExport: () => policy.export, +})); +vi.mock('@/lib/offline/offline-mode', () => ({ + scopeDecided: () => policy.decided, +})); + +import { + canEditFile, + editAllowed, + editFileInfo, + editForbidden, + followEditSessions, + parkFilesForReply, + parseEditSource, + readEditedFile, + resetEditSessions, + startAttachmentEdit, + takeFilesForReply, + useEditSessions, + type StartEditInput, +} from '../edit-attachments'; +import { setAppLockCheck } from '../app-lock-state'; +import { runWipeCleaners } from '@/lib/offline/wipe-registry'; +import { runBeforeSignOut } from '@/lib/sign-out-cleanup'; + +function fakeBridge() { + return { + canEdit: vi.fn((name: string) => !name.endsWith('.exe')), + begin: vi.fn(async (_key: string) => ({ ok: true as const, ticket: 't1' } as { ok: true; ticket: string; open?: string } | { ok: false; reason: 'locked' })), + open: vi.fn(async () => ({ ok: true as const, id: 's1' })), + reopen: vi.fn(async () => ({ ok: true as const, id: 's1' })), + list: vi.fn(async () => []), + read: vi.fn(async () => ({ ok: true as const, name: 'a.docx', type: 'x/y', data: new Uint8Array([1, 2]), hash: 'h' })), + taken: vi.fn(async () => {}), + discard: vi.fn(async () => {}), + clear: vi.fn(async () => {}), + setSource: vi.fn(), + claim: vi.fn(), + onChange: vi.fn(() => () => {}), + }; +} + +let bridge: ReturnType; + +const input = (over: Partial = {}): StartEditInput => ({ + key: 'k', + name: 'a.docx', + type: 'x/y', + account: 'acct', + source: { kind: 'mail', emailId: 'e1' }, + load: vi.fn(async () => new Uint8Array([9]).buffer), + ...over, +}); + +beforeEach(() => { + policy.decided = true; + policy.download = true; + policy.export = true; + bridge = fakeBridge(); + (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop = { version: 1, edit: bridge }; + resetEditSessions(); + setAppLockCheck(null); +}); + +afterEach(() => { + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; +}); + +describe('the policy', () => { + it('takes both saving attachments and export', () => { + expect(editAllowed('acct')).toBe(true); + policy.download = false; + expect(editAllowed('acct')).toBe(false); + policy.download = true; + policy.export = false; + expect(editAllowed('acct')).toBe(false); + }); + + it('counts an unknown policy as no for starting, and as no reason to delete anything', () => { + policy.decided = false; + expect(editAllowed('acct')).toBe(false); + expect(editForbidden('acct')).toBe(false); + policy.decided = true; + policy.export = false; + expect(editForbidden('acct')).toBe(true); + }); +}); + +describe('starting', () => { + it('asks main from the click, then fetches, then opens with what it fetched', async () => { + const order: string[] = []; + bridge.begin.mockImplementation(async () => { + order.push('begin'); + return { ok: true, ticket: 't1' }; + }); + const start = input({ load: async () => { + order.push('load'); + return new Uint8Array([7, 8]).buffer; + } }); + bridge.open.mockImplementation(async () => { + order.push('open'); + return { ok: true, id: 's1' }; + }); + expect(await startAttachmentEdit(start)).toEqual({ ok: true, id: 's1' }); + expect(order).toEqual(['begin', 'load', 'open']); + const [ticket, file] = bridge.open.mock.calls[0] as unknown as [string, { data: Uint8Array; source: string; account: string; key: string }]; + expect(ticket).toBe('t1'); + expect([...file.data]).toEqual([7, 8]); + expect(file).toMatchObject({ account: 'acct', key: 'k' }); + expect(JSON.parse(file.source)).toEqual({ kind: 'mail', emailId: 'e1' }); + }); + + it('touches nothing when the organisation says no', async () => { + policy.download = false; + const start = input(); + expect(await startAttachmentEdit(start)).toEqual({ ok: false, reason: 'policy' }); + expect(bridge.begin).not.toHaveBeenCalled(); + expect(start.load).not.toHaveBeenCalled(); + }); + + it('stops when the answer changes while the bytes are on their way, as a guarded sink does', async () => { + const start = input({ load: async () => { + policy.export = false; + return new Uint8Array([1]).buffer; + } }); + expect(await startAttachmentEdit(start)).toEqual({ ok: false, reason: 'policy' }); + expect(bridge.open).not.toHaveBeenCalled(); + }); + + it('stops when the app locks while the bytes are on their way', async () => { + const start = input({ load: async () => { + setAppLockCheck(() => true); + return new Uint8Array([1]).buffer; + } }); + expect(await startAttachmentEdit(start)).toEqual({ ok: false, reason: 'locked' }); + expect(bridge.open).not.toHaveBeenCalled(); + }); + + it('opens the same file again and fetches nothing, so the edits stay', async () => { + bridge.begin.mockResolvedValue({ ok: true, ticket: 't2', open: 's9' }); + const start = input(); + await startAttachmentEdit(start); + expect(bridge.reopen).toHaveBeenCalledWith('t2', 's9'); + expect(start.load).not.toHaveBeenCalled(); + expect(bridge.open).not.toHaveBeenCalled(); + }); + + it('passes on what main refuses', async () => { + bridge.begin.mockResolvedValue({ ok: false, reason: 'locked' }); + const start = input(); + expect(await startAttachmentEdit(start)).toEqual({ ok: false, reason: 'locked' }); + expect(start.load).not.toHaveBeenCalled(); + }); + + it('asks the shell which files may go, and answers no without a shell', () => { + expect(canEditFile('a.docx')).toBe(true); + expect(canEditFile('a.exe')).toBe(false); + expect(canEditFile(null)).toBe(false); + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; + expect(canEditFile('a.docx')).toBe(false); + }); + + it('does nothing in a browser', async () => { + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; + const start = input(); + expect(await startAttachmentEdit(start)).toEqual({ ok: false, reason: 'unavailable' }); + expect(start.load).not.toHaveBeenCalled(); + }); +}); + +describe('reading a saved file back', () => { + it('refuses when the organisation has said no since', async () => { + policy.export = false; + expect(await readEditedFile({ id: 's1', account: 'acct' })).toEqual({ ok: false, reason: 'policy' }); + expect(bridge.read).not.toHaveBeenCalled(); + }); + + it('gives a file that remembers its session and version', async () => { + const outcome = await readEditedFile({ id: 's1', account: 'acct' }); + if (!outcome.ok) throw new Error('refused'); + expect(outcome.file.name).toBe('a.docx'); + expect(outcome.file.type).toBe('x/y'); + expect(new Uint8Array(await outcome.file.arrayBuffer())).toEqual(new Uint8Array([1, 2])); + expect(editFileInfo(outcome.file)).toEqual({ id: 's1', hash: 'h' }); + expect(editFileInfo(new File([], 'other'))).toBeUndefined(); + }); + + it('passes a held or lost file on as such', async () => { + bridge.read.mockResolvedValueOnce({ ok: false, reason: 'busy' } as never); + expect(await readEditedFile({ id: 's1', account: 'acct' })).toEqual({ ok: false, reason: 'busy' }); + }); +}); + +describe('a file on its way to a reply', () => { + it('waits for that message, once', () => { + const file = new File([], 'a.txt'); + parkFilesForReply('e1', [file]); + expect(takeFilesForReply('e2')).toEqual([]); + expect(takeFilesForReply('e1')).toEqual([file]); + expect(takeFilesForReply('e1')).toEqual([]); + }); + + it('does not wait for ever', () => { + vi.useFakeTimers(); + try { + parkFilesForReply('e1', [new File([], 'a.txt')]); + vi.advanceTimersByTime(3 * 60 * 1000); + expect(takeFilesForReply('e1')).toEqual([]); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('what main says', () => { + it('follows the list once per page', async () => { + const session = { id: 's1', name: 'a', type: '', account: 'x', source: '', changed: true, version: 1, claimed: false }; + bridge.list.mockResolvedValue([session] as never); + followEditSessions(); + followEditSessions(); + expect(bridge.onChange).toHaveBeenCalledTimes(1); + await vi.waitFor(() => expect(useEditSessions.getState().sessions).toEqual([session])); + (bridge.onChange.mock.calls[0] as unknown as [(s: unknown[]) => void])[0]([]); + expect(useEditSessions.getState().sessions).toEqual([]); + }); +}); + +describe('where a source came from', () => { + it('reads what it wrote, and treats anything else as just a file', () => { + expect(parseEditSource(JSON.stringify({ kind: 'mail', emailId: 'e', ownerAccountId: 'o' }))).toEqual({ kind: 'mail', emailId: 'e', ownerAccountId: 'o' }); + expect(parseEditSource(JSON.stringify({ kind: 'draft', draftId: 'd' }))).toEqual({ kind: 'draft', draftId: 'd' }); + expect(parseEditSource(JSON.stringify({ kind: 'draft', draftId: null }))).toEqual({ kind: 'draft', draftId: null }); + expect(parseEditSource(JSON.stringify({ kind: 'mail' }))).toEqual({ kind: 'file' }); + expect(parseEditSource('not json')).toEqual({ kind: 'file' }); + }); +}); + +describe('the copies go with the account', () => { + it('on a wipe of an account, and of everything', async () => { + await runWipeCleaners('acct'); + expect(bridge.clear).toHaveBeenCalledWith('acct'); + bridge.clear.mockClear(); + await runWipeCleaners(null); + expect(bridge.clear).toHaveBeenCalledWith(null); + }); + + it('at sign-out', async () => { + await runBeforeSignOut('acct'); + expect(bridge.clear).toHaveBeenCalledWith('acct'); + }); + + it("not when the app ended the session itself and keeps the account's data", async () => { + await runBeforeSignOut('acct', { keepLocalStore: true }); + expect(bridge.clear).not.toHaveBeenCalled(); + }); + + it('a cleaner with no shell is no failure', async () => { + delete (window as unknown as { bulwarkDesktop?: unknown }).bulwarkDesktop; + await expect(runWipeCleaners(null)).resolves.toBeUndefined(); + }); +}); diff --git a/lib/desktop/__tests__/os-commands.test.ts b/lib/desktop/__tests__/os-commands.test.ts index d3f717f64..35338c572 100644 --- a/lib/desktop/__tests__/os-commands.test.ts +++ b/lib/desktop/__tests__/os-commands.test.ts @@ -228,6 +228,17 @@ describe('a toast\'s buttons', () => { stop(); }); + it('a toast for a saved attachment only brings the window up, and leaves the page where it is', async () => { + const { setMailLinkOpener } = await import('../mail-links'); + const opener = vi.fn(); + const stop = setMailLinkOpener(opener); + await run({ type: 'notification', action: 'open', context: JSON.stringify({ editedFile: true }) }); + expect(focus).toHaveBeenCalled(); + expect(opener).not.toHaveBeenCalled(); + expect(leaveFor).not.toHaveBeenCalled(); + stop(); + }); + it('a click on a summary toast opens the Inbox of that login', async () => { const { setMailLinkOpener } = await import('../mail-links'); const opener = vi.fn(); diff --git a/lib/desktop/edit-attachments.ts b/lib/desktop/edit-attachments.ts new file mode 100644 index 000000000..117acbbbf --- /dev/null +++ b/lib/desktop/edit-attachments.ts @@ -0,0 +1,175 @@ +/** + * "Edit" on an attachment, the page's side. The desktop app copies the file to a private + * folder, opens it in its default program and says when it was saved (the shell's + * features/os-edit.ts). What happens to a saved file is decided here and in what uses + * this: a composer offers "Update attachment" (hooks/use-composer-edits.ts), and the + * rest goes through the offers in components/desktop/edited-files-host.tsx. + * + * The organisation's word on saving attachments and exporting mail is per account and only + * known here, so it's asked at every step, as the local export does around its sink: + * before anything starts, after the bytes arrive, and before a saved file is read back. + * A policy that turns to no ends the session (the host watches), and one that isn't known + * yet counts as no for starting something, but deletes nothing. + */ + +import { create } from 'zustand'; +import { isAppLocked } from '@/lib/desktop/app-lock-state'; +import { getDesktopBridge } from '@/lib/desktop/bridge'; +import type { DesktopEditBridge, DesktopEditOpenResult, DesktopEditSession } from '@/lib/desktop/types'; +import { canDownload, canExport } from '@/lib/device-policy'; +import { scopeDecided } from '@/lib/offline/offline-mode'; +import { onDeviceWipe } from '@/lib/offline/wipe-registry'; +import { onBeforeSignOut, onFullSignOut } from '@/lib/sign-out-cleanup'; + +/** Where a session's file came from, kept by main for as long as the session lives. */ +export type EditSource = + /** A message's attachment: offers a reply. */ + | { kind: 'mail'; emailId: string; ownerAccountId?: string } + /** A draft's attachment: offers the update, in the composer holding it. */ + | { kind: 'draft'; draftId: string | null; ownerAccountId?: string } + /** Its message went or it was taken off a draft: only the file is left. */ + | { kind: 'file' }; + +export function parseEditSource(raw: string): EditSource { + try { + const parsed = JSON.parse(raw) as Partial & { emailId?: unknown; draftId?: unknown; ownerAccountId?: unknown }; + const ownerAccountId = typeof parsed.ownerAccountId === 'string' ? parsed.ownerAccountId : undefined; + if (parsed.kind === 'mail' && typeof parsed.emailId === 'string') return { kind: 'mail', emailId: parsed.emailId, ownerAccountId }; + if (parsed.kind === 'draft') return { kind: 'draft', draftId: typeof parsed.draftId === 'string' ? parsed.draftId : null, ownerAccountId }; + } catch { + // Falls through: what's left is a file. + } + return { kind: 'file' }; +} + +export function getEditBridge(): DesktopEditBridge | null { + return getDesktopBridge()?.edit ?? null; +} + +/** Nothing in the browser. Otherwise the shell's own list of what may be opened. */ +export function canEditFile(name: string | null | undefined): boolean { + return !!name && getEditBridge()?.canEdit(name) === true; +} + +/** Whether this account may keep a copy outside the app: saving attachments and export both have to be allowed. */ +export function editAllowed(account: string): boolean { + return scopeDecided(account) && canDownload(account) && canExport(account); +} + +/** A definite no. An unknown policy isn't one: nothing is deleted for that. */ +export function editForbidden(account: string): boolean { + return scopeDecided(account) && !(canDownload(account) && canExport(account)); +} + +export type EditStartResult = DesktopEditOpenResult | { ok: false; reason: 'policy' | 'unavailable' | 'gesture' }; + +export interface StartEditInput { + /** One session per key: Edit on the same attachment opens the same file, with its edits. */ + key: string; + name: string; + type: string; + account: string; + source: EditSource; + load: () => Promise; +} + +/** Call it straight from the click: main only starts a session on a real one. */ +export async function startAttachmentEdit(input: StartEditInput): Promise { + const edit = getEditBridge(); + if (!edit) return { ok: false, reason: 'unavailable' }; + if (!editAllowed(input.account)) return { ok: false, reason: 'policy' }; + const begun = await edit.begin(input.key); + if (!begun.ok) return begun; + if (begun.open) return edit.reopen(begun.ticket, begun.open); + const loaded = await input.load(); + // It can take a while to arrive, and the answer can change meanwhile. + if (!editAllowed(input.account)) return { ok: false, reason: 'policy' }; + if (isAppLocked()) return { ok: false, reason: 'locked' }; + const data = new Uint8Array(loaded instanceof Blob ? await loaded.arrayBuffer() : loaded); + return edit.open(begun.ticket, { + key: input.key, + name: input.name, + type: input.type, + data, + account: input.account, + source: JSON.stringify(input.source), + }); +} + +/** A file read back remembers which session it came from, so whichever composer it lands in takes the session on. */ +const editFiles = new WeakMap(); + +export function editFileInfo(file: File | undefined): { id: string; hash: string } | undefined { + return file ? editFiles.get(file) : undefined; +} + +export type EditReadOutcome = + | { ok: true; file: File; hash: string } + | { ok: false; reason: 'policy' | 'locked' | 'missing' | 'busy' | 'too-large' | 'unavailable' }; + +export async function readEditedFile(session: Pick): Promise { + const edit = getEditBridge(); + if (!edit) return { ok: false, reason: 'unavailable' }; + if (!editAllowed(session.account)) return { ok: false, reason: 'policy' }; + const answer = await edit.read(session.id); + if (!answer.ok) return answer; + const bytes = answer.data; + const file = new File([new Uint8Array(bytes)], answer.name, { type: answer.type || 'application/octet-stream' }); + editFiles.set(file, { id: session.id, hash: answer.hash }); + return { ok: true, file, hash: answer.hash }; +} + +const REPLY_WAIT_MS = 2 * 60 * 1000; +const parkedReplies = new Map(); + +/** The next reply composer opened on this message takes these. Waits here so every way of opening one works. */ +export function parkFilesForReply(emailId: string, files: File[]): void { + parkedReplies.set(emailId, { files, at: Date.now() }); +} + +export function takeFilesForReply(emailId: string | undefined): File[] { + if (!emailId) return []; + const parked = parkedReplies.get(emailId); + parkedReplies.delete(emailId); + return parked && Date.now() - parked.at < REPLY_WAIT_MS ? parked.files : []; +} + +interface EditSessionsState { + sessions: DesktopEditSession[]; +} + +/** What main says, per window. Empty while the app is locked. */ +export const useEditSessions = create(() => ({ sessions: [] })); + +let listening = false; + +/** Once per page, and for its life. Does nothing in a browser. */ +export function followEditSessions(): void { + const edit = getEditBridge(); + if (!edit || listening) return; + listening = true; + edit.onChange((sessions) => useEditSessions.setState({ sessions })); + void edit.list().then((sessions) => useEditSessions.setState({ sessions }), () => {}); +} + +/** For tests. */ +export function resetEditSessions(): void { + listening = false; + parkedReplies.clear(); + useEditSessions.setState({ sessions: [] }); +} + +const clear = async (account: string | null) => { + await getEditBridge()?.clear(account); +}; + +// The copies are of mail, so they go with the account. A wipe doesn't ask and neither does this; +// the question before a sign-out the user started is in the host. A sign-out the app decided +// on because it couldn't confirm the login (keepLocalStore) keeps them, as it keeps the store: +// nobody chose it, and these can be someone's only copy of an afternoon's work. While it lasts +// the host doesn't show them, since that account isn't signed in. +onDeviceWipe((account) => clear(account)); +onBeforeSignOut((account, options) => (options.keepLocalStore ? Promise.resolve() : clear(account))); +onFullSignOut((options) => { + if (!options.keepLocalStore) void clear(null); +}); diff --git a/lib/desktop/mail-notifications.ts b/lib/desktop/mail-notifications.ts index 12cd12e5d..958ac5156 100644 --- a/lib/desktop/mail-notifications.ts +++ b/lib/desktop/mail-notifications.ts @@ -45,6 +45,8 @@ export interface MailNotificationContext { accountId?: string; slot?: number; login?: string; + /** Not mail: an attachment saved in another program (components/desktop/edited-files-host.tsx). */ + editedFile?: boolean; } /** True where this module plays the new-mail sound, so useNewMailAlerts doesn't as well. */ diff --git a/lib/desktop/os-commands.ts b/lib/desktop/os-commands.ts index ede5e140b..c52c1baad 100644 --- a/lib/desktop/os-commands.ts +++ b/lib/desktop/os-commands.ts @@ -101,6 +101,11 @@ async function handleNotification(action: string, rawContext: string, reply: str } if (await handleReminderCommand(action, rawContext, env)) return; const context = parseContext(rawContext); + // A saved file's toast: the offer is on the main window, wherever it was. + if (context.editedFile) { + showWindow(); + return; + } if (action === 'reply') { await openFromNotification(context, env, { text: reply ?? '' }); return; diff --git a/lib/desktop/types.ts b/lib/desktop/types.ts index a8331c347..347d73d3d 100644 --- a/lib/desktop/types.ts +++ b/lib/desktop/types.ts @@ -604,6 +604,71 @@ export interface DesktopPrivacyBridge { onChange: (listener: (state: DesktopPrivacyState) => void) => () => void; } +/** An attachment copied to a private folder and open in its default program. */ +export interface DesktopEditSession { + id: string; + name: string; + type: string; + /** The local account it belongs to. */ + account: string; + /** What the page said it came from. Main only keeps it. */ + source: string; + /** Saved differently from what the page last took. */ + changed: boolean; + /** Goes up with each save. */ + version: number; + /** A composer has it and offers the update itself. */ + claimed: boolean; +} + +export interface DesktopEditFile { + /** One session per key: Edit on the same attachment opens the same file. */ + key: string; + name: string; + type: string; + data: Uint8Array; + account: string; + source: string; +} + +export type DesktopEditBeginResult = + | { ok: true; ticket: string; /** A session for that key exists: reopen this one. */ open?: string } + | { ok: false; reason: 'locked' | 'gesture' }; + +export type DesktopEditOpenResult = + | { ok: true; id: string } + | { ok: false; reason: 'locked' | 'ticket' | 'type' | 'too-large' | 'full' | 'no-app' | 'failed' }; + +export type DesktopEditReadResult = + | { ok: true; name: string; type: string; data: Uint8Array; hash: string } + | { ok: false; reason: 'locked' | 'missing' | 'busy' | 'too-large' }; + +/** + * Edit on an attachment: a private copy opened in its default program, watched for saves. + * Main refuses file types that run something and anything while locked. It can't know the + * organisation's rules, so lib/desktop/edit-attachments.ts asks those at each step. + */ +export interface DesktopEditBridge { + /** Whether this file may go through Edit at all: the same rule main enforces. */ + canEdit: (name: string) => boolean; + /** Straight from the click: main checks it was one. The ticket lasts long enough to fetch the bytes. */ + begin: (key: string) => Promise; + open: (ticket: string, file: DesktopEditFile) => Promise; + reopen: (ticket: string, id: string) => Promise; + /** Empty while locked. */ + list: () => Promise; + read: (id: string) => Promise; + /** This version is where it should be, so it's no longer a change. */ + taken: (id: string, hash: string) => Promise; + discard: (id: string) => Promise; + /** An account's copies, or with null all of this origin's. */ + clear: (account: string | null) => Promise; + setSource: (id: string, source: string) => void; + /** A composer holds it, or stopped. Ends by itself with the page. */ + claim: (id: string, on: boolean) => void; + onChange: (listener: (sessions: DesktopEditSession[]) => void) => () => void; +} + export interface BulwarkDesktopBridge { version: number; platform: 'win32' | 'darwin' | 'linux'; @@ -626,6 +691,7 @@ export interface BulwarkDesktopBridge { appLock?: DesktopAppLockBridge; localImport?: DesktopLocalImportBridge; privacy?: DesktopPrivacyBridge; + edit?: DesktopEditBridge; } declare global { diff --git a/lib/popout/open.ts b/lib/popout/open.ts index 3cee94b3d..a4e40df6c 100644 --- a/lib/popout/open.ts +++ b/lib/popout/open.ts @@ -81,6 +81,12 @@ export function openNewComposerWindow(localAccountId?: string | null): boolean { return focused(openWindow(appPath('/popout/compose') + query({ account: localAccountId }), name, 'compose')); } +/** A saved draft in a composer window of its own. The same draft twice focuses the same window. */ +export function openDraftWindow(target: { draftId: string; localAccountId?: string | null; ownerAccountId?: string | null }): boolean { + const url = appPath('/popout/compose') + query({ draft: target.draftId, account: target.localAccountId, owner: target.ownerAccountId }); + return focused(openWindow(url, `bulwark-compose-draft-${target.draftId.replace(/\W/g, '_')}`, 'compose')); +} + export interface ComposerWindow { /** Hands the draft over. True once the composer is on screen there; until then the sender keeps its copy. */ handOver(payload: ComposePopoutPayload): Promise; diff --git a/locales/ar/common.json b/locales/ar/common.json index c759d9601..8f41af3a8 100644 --- a/locales/ar/common.json +++ b/locales/ar/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "تعذّر نسخ الملف.", "reply_lost": "تعذّر الاحتفاظ بالرد الذي كتبته. افتح الرسالة وأجب من هناك." }, + "desktopEdit": { + "edit": "تعديل", + "edit_named": "تعديل {name}", + "opened": "{name} مفتوح في برنامجه. احفظ تغييراتك هناك، وسيُطلب منك تحديد ما يجب فعله بها.", + "offers_label": "المرفقات المعدّلة", + "changed_title": "تم تغيير {name}", + "changed_body": "حفظت تغييرات في برنامج آخر. ماذا تريد أن تفعل بها؟", + "reply": "إرفاق برد", + "new_message": "إرفاق برسالة جديدة", + "open_draft": "فتح المسودة", + "save_copy": "حفظ نسخة…", + "discard": "تجاهل التعديلات…", + "discard_title": "هل تريد تجاهل تعديلاتك على {name}؟", + "discard_detail": "تُحذف النسخة المعدّلة. ولا يتغير المرفق الأصلي.", + "discard_confirm": "تجاهل", + "cancel": "إلغاء", + "update": "تحديث المرفق", + "no_app": "لا يوجد برنامج على هذا الكمبيوتر يمكنه فتح هذا الملف.", + "blocked_type": "لا يمكن فتح هذا النوع من الملفات للتعديل، لأنه قد يعمل كبرنامج.", + "blocked_policy": "لا تسمح مؤسستك بحفظ المرفقات على هذا الجهاز.", + "removed_policy": "لم تعد مؤسستك تسمح بذلك، لذا حُذفت النسخة المعدّلة من {name}.", + "too_large": "هذا الملف كبير جدًا بحيث لا يمكن فتحه للتعديل.", + "too_many": "هناك ملفات كثيرة جدًا مفتوحة للتعديل. انتهِ من بعضها أولًا.", + "failed": "تعذر فتح الملف للتعديل.", + "read_busy": "ما زال برنامج آخر يستخدم {name}. أغلقه هناك وحاول مرة أخرى.", + "read_failed": "تعذرت قراءة النسخة المعدّلة من {name}.", + "send_stale_title": "يحتوي {name} على تعديلات ليست في هذه الرسالة", + "send_stale_detail": "إذا أرسلت الآن، فستُرسل الرسالة بالإصدار الأقدم. تبقى تعديلاتك على هذا الكمبيوتر إلى أن تقرر ما تفعله بها.", + "send_stale_send": "إرسال على أي حال", + "send_stale_back": "رجوع", + "signout_title": "هل تريد تسجيل الخروج وحذف تعديلاتك؟", + "signout_detail": "تُحذف عند تسجيل الخروج المرفقات التي عدّلتها ولم ترفقها أو تحفظها.", + "signout_confirm": "تسجيل الخروج", + "lock_note": "تبقى الملفات التي فتحتها باستخدام «تعديل» مفتوحة في برنامجها أثناء قفل التطبيق، وتظل قابلة للقراءة على هذا الكمبيوتر. ولا يمكن فتح ملفات جديدة حتى تفتح القفل." + }, "desktopReminders": { "generic_title": "تذكير", "snooze": "تأجيل {count} د", diff --git a/locales/ca/common.json b/locales/ca/common.json index 9ca9c8032..5819b9a6c 100644 --- a/locales/ca/common.json +++ b/locales/ca/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "No s'ha pogut copiar el fitxer.", "reply_lost": "No s'ha pogut conservar la resposta que heu escrit. Obriu el missatge i responeu des d'allà." }, + "desktopEdit": { + "edit": "Edita", + "edit_named": "Edita {name}", + "opened": "{name} és obert al seu programa. Deseu-hi els canvis i se us preguntarà què fer-ne.", + "offers_label": "Adjunts editats", + "changed_title": "{name} ha canviat", + "changed_body": "Heu desat canvis en un altre programa. Què voleu fer-ne?", + "reply": "Adjunta a una resposta", + "new_message": "Adjunta a un missatge nou", + "open_draft": "Obre l’esborrany", + "save_copy": "Desa una còpia…", + "discard": "Descarta els canvis…", + "discard_title": "Voleu descartar els canvis a {name}?", + "discard_detail": "S’elimina la còpia editada. L’adjunt original no canvia.", + "discard_confirm": "Descarta", + "cancel": "Cancel·la", + "update": "Actualitza l’adjunt", + "no_app": "Cap programa d’aquest ordinador pot obrir aquest fitxer.", + "blocked_type": "Aquest tipus de fitxer no es pot obrir per editar-lo, perquè es podria executar com un programa.", + "blocked_policy": "La vostra organització no permet desar adjunts en aquest dispositiu.", + "removed_policy": "La vostra organització ja no ho permet, així que s’ha eliminat la còpia editada de {name}.", + "too_large": "Aquest fitxer és massa gran per obrir-lo i editar-lo.", + "too_many": "Hi ha massa fitxers oberts per editar. Primer acabeu-ne alguns.", + "failed": "No s’ha pogut obrir el fitxer per editar-lo.", + "read_busy": "Un altre programa encara fa servir {name}. Tanqueu-lo allà i torneu-ho a provar.", + "read_failed": "No s’ha pogut llegir la còpia editada de {name}.", + "send_stale_title": "{name} té canvis que no són en aquest missatge", + "send_stale_detail": "Si l’envieu ara, el missatge surt amb la versió anterior. Els canvis es queden en aquest ordinador fins que decidiu què fer-ne.", + "send_stale_send": "Envia igualment", + "send_stale_back": "Torna", + "signout_title": "Voleu tancar la sessió i eliminar els canvis?", + "signout_detail": "Els adjunts que heu editat però no heu adjuntat ni desat s’eliminen en tancar la sessió.", + "signout_confirm": "Tanca la sessió", + "lock_note": "Els fitxers oberts amb Edita continuen oberts al seu programa mentre l’aplicació està bloquejada, i continuen sent llegibles en aquest ordinador. No se’n poden obrir de nous fins que la desbloquegeu." + }, "desktopReminders": { "generic_title": "Recordatori", "snooze": "Posposa {count} min", diff --git a/locales/cs/common.json b/locales/cs/common.json index 5585c00c0..f85fb066c 100644 --- a/locales/cs/common.json +++ b/locales/cs/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Soubor se nepodařilo zkopírovat.", "reply_lost": "Napsanou odpověď se nepodařilo zachovat. Otevřete zprávu a odpovězte v ní." }, + "desktopEdit": { + "edit": "Upravit", + "edit_named": "Upravit {name}", + "opened": "{name} je otevřený ve svém programu. Uložte tam změny a pak se vás zeptáme, co s nimi udělat.", + "offers_label": "Upravené přílohy", + "changed_title": "{name} se změnil", + "changed_body": "Uložili jste změny v jiném programu. Co s nimi chcete udělat?", + "reply": "Připojit k odpovědi", + "new_message": "Připojit k nové zprávě", + "open_draft": "Otevřít koncept", + "save_copy": "Uložit kopii…", + "discard": "Zahodit změny…", + "discard_title": "Zahodit změny v {name}?", + "discard_detail": "Upravená kopie se smaže. Původní příloha se nezmění.", + "discard_confirm": "Zahodit", + "cancel": "Zrušit", + "update": "Aktualizovat přílohu", + "no_app": "Tento soubor nedokáže otevřít žádný program na tomto počítači.", + "blocked_type": "Tento typ souboru nelze otevřít k úpravám, protože by se mohl spustit jako program.", + "blocked_policy": "Vaše organizace nepovoluje ukládat přílohy na toto zařízení.", + "removed_policy": "Vaše organizace už to nepovoluje, proto byla upravená kopie {name} smazána.", + "too_large": "Tento soubor je příliš velký, aby se dal otevřít k úpravám.", + "too_many": "K úpravám je otevřeno příliš mnoho souborů. Některé nejdřív dokončete.", + "failed": "Soubor se nepodařilo otevřít k úpravám.", + "read_busy": "{name} stále používá jiný program. Zavřete ho tam a zkuste to znovu.", + "read_failed": "Upravenou kopii {name} se nepodařilo přečíst.", + "send_stale_title": "{name} má změny, které v této zprávě nejsou", + "send_stale_detail": "Když teď odešlete, zpráva odejde se starší verzí. Vaše změny zůstanou na tomto počítači, dokud se nerozhodnete, co s nimi.", + "send_stale_send": "Přesto odeslat", + "send_stale_back": "Zpět", + "signout_title": "Odhlásit se a smazat změny?", + "signout_detail": "Přílohy, které jste upravili, ale nepřipojili ani neuložili, se při odhlášení smažou.", + "signout_confirm": "Odhlásit se", + "lock_note": "Soubory otevřené přes Upravit zůstanou otevřené ve svém programu, i když je aplikace zamčená, a zůstanou na tomto počítači čitelné. Nové se otevřou až po odemčení." + }, "desktopReminders": { "generic_title": "Připomenutí", "snooze": "Odložit o {count} min", diff --git a/locales/da/common.json b/locales/da/common.json index 9fa9629c6..95f1da09b 100644 --- a/locales/da/common.json +++ b/locales/da/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Filen kunne ikke kopieres.", "reply_lost": "Dit skrevne svar kunne ikke gemmes. Åbn beskeden, og svar der." }, + "desktopEdit": { + "edit": "Rediger", + "edit_named": "Rediger {name}", + "opened": "{name} er åben i sit program. Gem dine ændringer der, så bliver du spurgt, hvad der skal ske med dem.", + "offers_label": "Redigerede vedhæftninger", + "changed_title": "{name} blev ændret", + "changed_body": "Du har gemt ændringer i et andet program. Hvad skal der ske med dem?", + "reply": "Vedhæft til et svar", + "new_message": "Vedhæft til en ny besked", + "open_draft": "Åbn kladde", + "save_copy": "Gem en kopi…", + "discard": "Kassér ændringer…", + "discard_title": "Kassér dine ændringer i {name}?", + "discard_detail": "Den redigerede kopi slettes. Den oprindelige vedhæftning ændres ikke.", + "discard_confirm": "Kassér", + "cancel": "Annuller", + "update": "Opdater vedhæftning", + "no_app": "Intet program på denne computer kan åbne filen.", + "blocked_type": "Denne filtype kan ikke åbnes til redigering, fordi den kan køre som et program.", + "blocked_policy": "Din organisation tillader ikke at gemme vedhæftninger på denne enhed.", + "removed_policy": "Din organisation tillader det ikke længere, så den redigerede kopi af {name} blev slettet.", + "too_large": "Filen er for stor til at åbne til redigering.", + "too_many": "Der er for mange filer åbne til redigering. Gør nogle af dem færdige først.", + "failed": "Filen kunne ikke åbnes til redigering.", + "read_busy": "Et andet program bruger stadig {name}. Luk den der, og prøv igen.", + "read_failed": "Den redigerede kopi af {name} kunne ikke læses.", + "send_stale_title": "{name} har ændringer, der ikke er i denne besked", + "send_stale_detail": "Hvis du sender nu, går beskeden af sted med den ældre version. Dine ændringer bliver på denne computer, indtil du beslutter, hvad der skal ske med dem.", + "send_stale_send": "Send alligevel", + "send_stale_back": "Tilbage", + "signout_title": "Log ud og slet dine ændringer?", + "signout_detail": "Vedhæftninger, du har redigeret, men hverken vedhæftet eller gemt, slettes, når du logger ud.", + "signout_confirm": "Log ud", + "lock_note": "Filer, du har åbnet med Rediger, forbliver åbne i deres program, mens appen er låst, og kan stadig læses på denne computer. Nye kan først åbnes, når du låser op." + }, "desktopReminders": { "generic_title": "Påmindelse", "snooze": "Udsæt {count} min.", diff --git a/locales/de/common.json b/locales/de/common.json index d1bc0fa61..da12be301 100644 --- a/locales/de/common.json +++ b/locales/de/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Die Datei konnte nicht kopiert werden.", "reply_lost": "Ihre eingegebene Antwort konnte nicht übernommen werden. Öffnen Sie die Nachricht und antworten Sie dort." }, + "desktopEdit": { + "edit": "Bearbeiten", + "edit_named": "{name} bearbeiten", + "opened": "{name} ist in seinem Programm geöffnet. Speichern Sie Ihre Änderungen dort, danach werden Sie gefragt, was damit geschehen soll.", + "offers_label": "Bearbeitete Anhänge", + "changed_title": "{name} wurde geändert", + "changed_body": "Sie haben Änderungen in einem anderen Programm gespeichert. Was soll damit geschehen?", + "reply": "An eine Antwort anhängen", + "new_message": "An eine neue Nachricht anhängen", + "open_draft": "Entwurf öffnen", + "save_copy": "Kopie speichern…", + "discard": "Änderungen verwerfen…", + "discard_title": "Ihre Änderungen an {name} verwerfen?", + "discard_detail": "Die bearbeitete Kopie wird gelöscht. Der ursprüngliche Anhang bleibt, wie er ist.", + "discard_confirm": "Verwerfen", + "cancel": "Abbrechen", + "update": "Anhang aktualisieren", + "no_app": "Kein Programm auf diesem Computer kann diese Datei öffnen.", + "blocked_type": "Dieser Dateityp lässt sich nicht zum Bearbeiten öffnen, weil er als Programm laufen könnte.", + "blocked_policy": "Ihre Organisation erlaubt nicht, Anhänge auf diesem Gerät zu speichern.", + "removed_policy": "Ihre Organisation erlaubt das nicht mehr, daher wurde die bearbeitete Kopie von {name} gelöscht.", + "too_large": "Diese Datei ist zu groß, um sie zum Bearbeiten zu öffnen.", + "too_many": "Es sind zu viele Dateien zum Bearbeiten geöffnet. Schließen Sie zuerst einige davon ab.", + "failed": "Die Datei konnte nicht zum Bearbeiten geöffnet werden.", + "read_busy": "Ein anderes Programm verwendet {name} noch. Schließen Sie die Datei dort und versuchen Sie es erneut.", + "read_failed": "Die bearbeitete Kopie von {name} konnte nicht gelesen werden.", + "send_stale_title": "{name} hat Änderungen, die nicht in dieser Nachricht sind", + "send_stale_detail": "Wenn Sie jetzt senden, geht die Nachricht mit der älteren Fassung hinaus. Ihre Änderungen bleiben auf diesem Computer, bis Sie entscheiden, was damit geschehen soll.", + "send_stale_send": "Trotzdem senden", + "send_stale_back": "Zurück", + "signout_title": "Abmelden und Ihre Änderungen löschen?", + "signout_detail": "Anhänge, die Sie bearbeitet, aber weder angehängt noch gespeichert haben, werden beim Abmelden gelöscht.", + "signout_confirm": "Abmelden", + "lock_note": "Dateien, die Sie mit „Bearbeiten“ geöffnet haben, bleiben in ihrem Programm geöffnet, während die App gesperrt ist, und bleiben auf diesem Computer lesbar. Neue lassen sich erst nach dem Entsperren öffnen." + }, "desktopReminders": { "generic_title": "Erinnerung", "snooze": "{count} Min. schlummern", diff --git a/locales/en/common.json b/locales/en/common.json index b7b372d47..5c5450d17 100644 --- a/locales/en/common.json +++ b/locales/en/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "The file could not be copied.", "reply_lost": "Your typed reply could not be kept. Open the message and reply there." }, + "desktopEdit": { + "edit": "Edit", + "edit_named": "Edit {name}", + "opened": "{name} is open in its program. Save your changes there, and you'll be asked what to do with them.", + "offers_label": "Edited attachments", + "changed_title": "{name} was changed", + "changed_body": "You saved changes in another program. What should happen to them?", + "reply": "Attach to a reply", + "new_message": "Attach to a new message", + "open_draft": "Open draft", + "save_copy": "Save a copy…", + "discard": "Discard edits…", + "discard_title": "Discard your edits to {name}?", + "discard_detail": "The edited copy is deleted. The original attachment doesn't change.", + "discard_confirm": "Discard", + "cancel": "Cancel", + "update": "Update attachment", + "no_app": "No program on this computer can open this file.", + "blocked_type": "This type of file can't be opened for editing, because it could run as a program.", + "blocked_policy": "Your organisation doesn't allow saving attachments on this device.", + "removed_policy": "Your organisation no longer allows this, so the edited copy of {name} was deleted.", + "too_large": "This file is too large to open for editing.", + "too_many": "Too many files are open for editing. Finish with some of them first.", + "failed": "The file could not be opened for editing.", + "read_busy": "Another program is still using {name}. Close it there and try again.", + "read_failed": "The edited copy of {name} could not be read.", + "send_stale_title": "{name} has edits that aren't in this message", + "send_stale_detail": "If you send now, the message goes with the older version. Your edits stay on this computer until you decide what to do with them.", + "send_stale_send": "Send anyway", + "send_stale_back": "Go back", + "signout_title": "Sign out and delete your edits?", + "signout_detail": "Attachments you edited but didn't attach or save are deleted when you sign out.", + "signout_confirm": "Sign out", + "lock_note": "Files you opened with Edit stay open in their program while the app is locked, and they stay readable on this computer. New ones can't open until you unlock." + }, "desktopReminders": { "generic_title": "Reminder", "snooze": "Snooze {count} min", diff --git a/locales/es/common.json b/locales/es/common.json index a6af887c6..90f6f4df8 100644 --- a/locales/es/common.json +++ b/locales/es/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "No se pudo copiar el archivo.", "reply_lost": "No se pudo conservar la respuesta que escribiste. Abre el mensaje y responde desde allí." }, + "desktopEdit": { + "edit": "Editar", + "edit_named": "Editar {name}", + "opened": "{name} está abierto en su programa. Guarde los cambios allí y se le preguntará qué hacer con ellos.", + "offers_label": "Adjuntos editados", + "changed_title": "{name} ha cambiado", + "changed_body": "Ha guardado cambios en otro programa. ¿Qué quiere hacer con ellos?", + "reply": "Adjuntar a una respuesta", + "new_message": "Adjuntar a un mensaje nuevo", + "open_draft": "Abrir borrador", + "save_copy": "Guardar una copia…", + "discard": "Descartar los cambios…", + "discard_title": "¿Descartar los cambios en {name}?", + "discard_detail": "Se elimina la copia editada. El adjunto original no cambia.", + "discard_confirm": "Descartar", + "cancel": "Cancelar", + "update": "Actualizar adjunto", + "no_app": "Ningún programa de este equipo puede abrir este archivo.", + "blocked_type": "Este tipo de archivo no se puede abrir para editarlo, porque podría ejecutarse como un programa.", + "blocked_policy": "Su organización no permite guardar adjuntos en este dispositivo.", + "removed_policy": "Su organización ya no lo permite, así que se eliminó la copia editada de {name}.", + "too_large": "Este archivo es demasiado grande para abrirlo y editarlo.", + "too_many": "Hay demasiados archivos abiertos para editar. Termine primero con algunos.", + "failed": "No se pudo abrir el archivo para editarlo.", + "read_busy": "Otro programa sigue usando {name}. Ciérrelo allí e inténtelo de nuevo.", + "read_failed": "No se pudo leer la copia editada de {name}.", + "send_stale_title": "{name} tiene cambios que no están en este mensaje", + "send_stale_detail": "Si envía ahora, el mensaje sale con la versión anterior. Sus cambios se quedan en este equipo hasta que decida qué hacer con ellos.", + "send_stale_send": "Enviar de todos modos", + "send_stale_back": "Volver", + "signout_title": "¿Cerrar sesión y eliminar sus cambios?", + "signout_detail": "Los adjuntos que editó pero no adjuntó ni guardó se eliminan al cerrar sesión.", + "signout_confirm": "Cerrar sesión", + "lock_note": "Los archivos abiertos con Editar siguen abiertos en su programa mientras la aplicación está bloqueada, y siguen siendo legibles en este equipo. No se pueden abrir otros hasta que la desbloquee." + }, "desktopReminders": { "generic_title": "Recordatorio", "snooze": "Posponer {count} min", diff --git a/locales/et/common.json b/locales/et/common.json index 303262a33..95d1d136c 100644 --- a/locales/et/common.json +++ b/locales/et/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Faili ei saanud kopeerida.", "reply_lost": "Kirjutatud vastust ei saanud säilitada. Ava kiri ja vasta seal." }, + "desktopEdit": { + "edit": "Muuda", + "edit_named": "Muuda faili {name}", + "opened": "{name} on oma programmis avatud. Salvesta muudatused seal ja sinult küsitakse, mida nendega teha.", + "offers_label": "Muudetud manused", + "changed_title": "{name} on muutunud", + "changed_body": "Salvestasid muudatused teises programmis. Mida nendega teha?", + "reply": "Lisa vastusele", + "new_message": "Lisa uuele kirjale", + "open_draft": "Ava mustand", + "save_copy": "Salvesta koopia…", + "discard": "Loobu muudatustest…", + "discard_title": "Kas loobuda faili {name} muudatustest?", + "discard_detail": "Muudetud koopia kustutatakse. Algne manus ei muutu.", + "discard_confirm": "Loobu", + "cancel": "Tühista", + "update": "Uuenda manust", + "no_app": "Ükski selle arvuti programm ei saa seda faili avada.", + "blocked_type": "Seda tüüpi faili ei saa muutmiseks avada, sest see võib käivituda programmina.", + "blocked_policy": "Sinu organisatsioon ei luba selles seadmes manuseid salvestada.", + "removed_policy": "Sinu organisatsioon ei luba seda enam, seega kustutati faili {name} muudetud koopia.", + "too_large": "See fail on muutmiseks avamiseks liiga suur.", + "too_many": "Muutmiseks on avatud liiga palju faile. Lõpeta kõigepealt mõned neist.", + "failed": "Faili ei saanud muutmiseks avada.", + "read_busy": "Teine programm kasutab faili {name} endiselt. Sulge see seal ja proovi uuesti.", + "read_failed": "Faili {name} muudetud koopiat ei saanud lugeda.", + "send_stale_title": "Failis {name} on muudatusi, mida selles kirjas pole", + "send_stale_detail": "Kui saadad praegu, läheb kiri vanema versiooniga. Sinu muudatused jäävad sellesse arvutisse, kuni otsustad, mida nendega teha.", + "send_stale_send": "Saada ikkagi", + "send_stale_back": "Tagasi", + "signout_title": "Kas logida välja ja kustutada muudatused?", + "signout_detail": "Manused, mida muutsid, kuid ei lisanud ega salvestanud, kustutatakse väljalogimisel.", + "signout_confirm": "Logi välja", + "lock_note": "Muutmiseks avatud failid jäävad oma programmis avatuks ka siis, kui rakendus on lukus, ja on selles arvutis endiselt loetavad. Uusi ei saa enne lukust avamist avada." + }, "desktopReminders": { "generic_title": "Meeldetuletus", "snooze": "Lükka {count} min edasi", diff --git a/locales/fa/common.json b/locales/fa/common.json index 9a1f39794..4e0a0eedc 100644 --- a/locales/fa/common.json +++ b/locales/fa/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "رونوشت پرونده ممکن نشد.", "reply_lost": "پاسخی که نوشتید نگه داشته نشد. پیام را باز کنید و از آنجا پاسخ دهید." }, + "desktopEdit": { + "edit": "ویرایش", + "edit_named": "ویرایش {name}", + "opened": "{name} در برنامه خودش باز است. تغییرات را همان‌جا ذخیره کنید تا از شما پرسیده شود با آنها چه شود.", + "offers_label": "پیوست‌های ویرایش‌شده", + "changed_title": "{name} تغییر کرد", + "changed_body": "تغییراتی را در برنامه دیگری ذخیره کردید. با آنها چه شود؟", + "reply": "پیوست به پاسخ", + "new_message": "پیوست به پیام جدید", + "open_draft": "باز کردن پیش‌نویس", + "save_copy": "ذخیره یک نسخه…", + "discard": "دور انداختن ویرایش‌ها…", + "discard_title": "ویرایش‌های {name} دور انداخته شود؟", + "discard_detail": "نسخه ویرایش‌شده حذف می‌شود. پیوست اصلی تغییر نمی‌کند.", + "discard_confirm": "دور انداختن", + "cancel": "انصراف", + "update": "به‌روزرسانی پیوست", + "no_app": "هیچ برنامه‌ای در این رایانه نمی‌تواند این فایل را باز کند.", + "blocked_type": "این نوع فایل را نمی‌توان برای ویرایش باز کرد، چون ممکن است مانند برنامه اجرا شود.", + "blocked_policy": "سازمان شما اجازه ذخیره پیوست‌ها در این دستگاه را نمی‌دهد.", + "removed_policy": "سازمان شما دیگر اجازه این کار را نمی‌دهد، بنابراین نسخه ویرایش‌شده {name} حذف شد.", + "too_large": "این فایل برای باز شدن جهت ویرایش خیلی بزرگ است.", + "too_many": "فایل‌های زیادی برای ویرایش باز است. ابتدا کار برخی از آنها را تمام کنید.", + "failed": "فایل برای ویرایش باز نشد.", + "read_busy": "برنامه دیگری هنوز از {name} استفاده می‌کند. آن را همان‌جا ببندید و دوباره امتحان کنید.", + "read_failed": "نسخه ویرایش‌شده {name} خوانده نشد.", + "send_stale_title": "{name} ویرایش‌هایی دارد که در این پیام نیست", + "send_stale_detail": "اگر اکنون بفرستید، پیام با نسخه قدیمی‌تر می‌رود. ویرایش‌های شما تا زمانی که تصمیم بگیرید در این رایانه می‌ماند.", + "send_stale_send": "با این حال بفرست", + "send_stale_back": "بازگشت", + "signout_title": "خروج از حساب و حذف ویرایش‌ها؟", + "signout_detail": "پیوست‌هایی که ویرایش کرده‌اید ولی پیوست یا ذخیره نکرده‌اید، هنگام خروج حذف می‌شوند.", + "signout_confirm": "خروج از حساب", + "lock_note": "فایل‌هایی که با «ویرایش» باز کرده‌اید تا وقتی برنامه قفل است در برنامه خود باز می‌مانند و در این رایانه قابل خواندن هستند. فایل‌های جدید تا باز کردن قفل باز نمی‌شوند." + }, "desktopReminders": { "generic_title": "یادآوری", "snooze": "تعویق {count} دقیقه", diff --git a/locales/fr/common.json b/locales/fr/common.json index fd43c5da3..021ef4b2a 100644 --- a/locales/fr/common.json +++ b/locales/fr/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Le fichier n'a pas pu être copié.", "reply_lost": "Votre réponse saisie n'a pas pu être conservée. Ouvrez le message et répondez depuis celui-ci." }, + "desktopEdit": { + "edit": "Modifier", + "edit_named": "Modifier {name}", + "opened": "{name} est ouvert dans son programme. Enregistrez vos modifications dans ce programme : on vous demandera ensuite quoi en faire.", + "offers_label": "Pièces jointes modifiées", + "changed_title": "{name} a été modifié", + "changed_body": "Vous avez enregistré des modifications dans un autre programme. Que voulez-vous en faire ?", + "reply": "Joindre à une réponse", + "new_message": "Joindre à un nouveau message", + "open_draft": "Ouvrir le brouillon", + "save_copy": "Enregistrer une copie…", + "discard": "Abandonner les modifications…", + "discard_title": "Abandonner vos modifications de {name} ?", + "discard_detail": "La copie modifiée est supprimée. La pièce jointe d’origine ne change pas.", + "discard_confirm": "Abandonner", + "cancel": "Annuler", + "update": "Mettre à jour la pièce jointe", + "no_app": "Aucun programme de cet ordinateur ne peut ouvrir ce fichier.", + "blocked_type": "Ce type de fichier ne peut pas être ouvert pour modification, car il pourrait s’exécuter comme un programme.", + "blocked_policy": "Votre organisation n’autorise pas l’enregistrement des pièces jointes sur cet appareil.", + "removed_policy": "Votre organisation ne l’autorise plus : la copie modifiée de {name} a été supprimée.", + "too_large": "Ce fichier est trop volumineux pour être ouvert et modifié.", + "too_many": "Trop de fichiers sont ouverts pour modification. Terminez-en quelques-uns d’abord.", + "failed": "Le fichier n’a pas pu être ouvert pour modification.", + "read_busy": "Un autre programme utilise encore {name}. Fermez-le dans ce programme et réessayez.", + "read_failed": "La copie modifiée de {name} n’a pas pu être lue.", + "send_stale_title": "{name} contient des modifications absentes de ce message", + "send_stale_detail": "Si vous envoyez maintenant, le message part avec l’ancienne version. Vos modifications restent sur cet ordinateur jusqu’à ce que vous décidiez quoi en faire.", + "send_stale_send": "Envoyer quand même", + "send_stale_back": "Revenir", + "signout_title": "Vous déconnecter et supprimer vos modifications ?", + "signout_detail": "Les pièces jointes modifiées, mais ni jointes ni enregistrées, sont supprimées à la déconnexion.", + "signout_confirm": "Se déconnecter", + "lock_note": "Les fichiers ouverts avec Modifier restent ouverts dans leur programme pendant que l’application est verrouillée, et restent lisibles sur cet ordinateur. Aucun nouveau fichier ne peut s’ouvrir avant le déverrouillage." + }, "desktopReminders": { "generic_title": "Rappel", "snooze": "Reporter de {count} min", diff --git a/locales/he/common.json b/locales/he/common.json index 10bb0aacf..1dfb42c78 100644 --- a/locales/he/common.json +++ b/locales/he/common.json @@ -6959,6 +6959,41 @@ "copy_failed": "לא ניתן להעתיק את הקובץ.", "reply_lost": "לא ניתן היה לשמור את התשובה שהקלדת. פתחו את ההודעה והשיבו משם." }, + "desktopEdit": { + "edit": "עריכה", + "edit_named": "עריכת {name}", + "opened": "{name} פתוח בתוכנה שלו. שמרו שם את השינויים, ואז תישאלו מה לעשות בהם.", + "offers_label": "קבצים מצורפים שנערכו", + "changed_title": "{name} השתנה", + "changed_body": "שמרתם שינויים בתוכנה אחרת. מה לעשות בהם?", + "reply": "צירוף לתשובה", + "new_message": "צירוף להודעה חדשה", + "open_draft": "פתיחת הטיוטה", + "save_copy": "שמירת עותק…", + "discard": "ביטול העריכות…", + "discard_title": "לבטל את העריכות ב{name}?", + "discard_detail": "העותק הערוך יימחק. הקובץ המצורף המקורי לא ישתנה.", + "discard_confirm": "ביטול העריכות", + "cancel": "ביטול", + "update": "עדכון הקובץ המצורף", + "no_app": "אין במחשב זה תוכנה שיכולה לפתוח את הקובץ.", + "blocked_type": "אי אפשר לפתוח סוג קובץ זה לעריכה, כי הוא עלול לרוץ כתוכנה.", + "blocked_policy": "הארגון שלכם לא מאפשר לשמור קבצים מצורפים במכשיר זה.", + "removed_policy": "הארגון שלכם כבר לא מאפשר זאת, ולכן העותק הערוך של {name} נמחק.", + "too_large": "הקובץ גדול מדי לפתיחה לעריכה.", + "too_many": "יותר מדי קבצים פתוחים לעריכה. סיימו קודם עם חלק מהם.", + "failed": "לא ניתן היה לפתוח את הקובץ לעריכה.", + "read_busy": "תוכנה אחרת עדיין משתמשת ב{name}. סגרו אותו שם ונסו שוב.", + "read_failed": "לא ניתן היה לקרוא את העותק הערוך של {name}.", + "send_stale_title": "ב{name} יש עריכות שאינן בהודעה זו", + "send_stale_detail": "אם תשלחו עכשיו, ההודעה תצא עם הגרסה הישנה. העריכות יישארו במחשב זה עד שתחליטו מה לעשות בהן.", + "send_stale_send": "לשלוח בכל זאת", + "send_stale_back": "חזרה", + "signout_title": "להתנתק ולמחוק את העריכות?", + "signout_detail": "קבצים שערכתם אך לא צירפתם או שמרתם יימחקו בעת ההתנתקות.", + "signout_confirm": "התנתקות", + "lock_note": "קבצים שפתחתם בעזרת עריכה נשארים פתוחים בתוכנה שלהם בזמן שהאפליקציה נעולה, ונשארים קריאים במחשב זה. אי אפשר לפתוח חדשים עד לביטול הנעילה." + }, "desktopReminders": { "generic_title": "תזכורת", "snooze": "דחייה ב-{count} דק'", diff --git a/locales/hu/common.json b/locales/hu/common.json index 50702f8fb..53ff502c1 100644 --- a/locales/hu/common.json +++ b/locales/hu/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "A fájlt nem sikerült másolni.", "reply_lost": "A beírt válasz nem maradt meg. Nyissa meg az üzenetet, és válaszoljon ott." }, + "desktopEdit": { + "edit": "Szerkesztés", + "edit_named": "{name} szerkesztése", + "opened": "A(z) {name} meg van nyitva a programjában. Ott mentse a módosításokat, és megkérdezzük, mi legyen velük.", + "offers_label": "Szerkesztett mellékletek", + "changed_title": "A(z) {name} megváltozott", + "changed_body": "Módosításokat mentett egy másik programban. Mi legyen velük?", + "reply": "Csatolás válaszhoz", + "new_message": "Csatolás új üzenethez", + "open_draft": "Piszkozat megnyitása", + "save_copy": "Másolat mentése…", + "discard": "Módosítások elvetése…", + "discard_title": "Elveti a(z) {name} módosításait?", + "discard_detail": "A szerkesztett másolat törlődik. Az eredeti melléklet nem változik.", + "discard_confirm": "Elvetés", + "cancel": "Mégse", + "update": "Melléklet frissítése", + "no_app": "A számítógépen egyik program sem tudja megnyitni ezt a fájlt.", + "blocked_type": "Ez a fájltípus nem nyitható meg szerkesztésre, mert programként futhat.", + "blocked_policy": "A szervezete nem engedélyezi mellékletek mentését erre az eszközre.", + "removed_policy": "A szervezete ezt már nem engedélyezi, ezért a(z) {name} szerkesztett másolata törölve lett.", + "too_large": "Ez a fájl túl nagy ahhoz, hogy szerkesztésre megnyíljon.", + "too_many": "Túl sok fájl van megnyitva szerkesztésre. Előbb fejezzen be néhányat.", + "failed": "A fájlt nem sikerült megnyitni szerkesztésre.", + "read_busy": "Egy másik program még használja ezt: {name}. Zárja be ott, és próbálja újra.", + "read_failed": "A(z) {name} szerkesztett másolatát nem sikerült beolvasni.", + "send_stale_title": "A(z) {name} olyan módosításokat tartalmaz, amelyek nincsenek ebben az üzenetben", + "send_stale_detail": "Ha most küldi el, az üzenet a régebbi változattal megy el. A módosítások ezen a számítógépen maradnak, amíg nem dönt róluk.", + "send_stale_send": "Küldés így is", + "send_stale_back": "Vissza", + "signout_title": "Kijelentkezik, és törli a módosításokat?", + "signout_detail": "A szerkesztett, de nem csatolt és nem mentett mellékletek kijelentkezéskor törlődnek.", + "signout_confirm": "Kijelentkezés", + "lock_note": "A Szerkesztéssel megnyitott fájlok nyitva maradnak a programjukban, amíg az alkalmazás zárolva van, és olvashatók maradnak ezen a számítógépen. Újak csak a feloldás után nyithatók meg." + }, "desktopReminders": { "generic_title": "Emlékeztető", "snooze": "Halasztás {count} perccel", diff --git a/locales/it/common.json b/locales/it/common.json index 7ff4479d1..7154ac556 100644 --- a/locales/it/common.json +++ b/locales/it/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Impossibile copiare il file.", "reply_lost": "Non è stato possibile conservare la risposta digitata. Apri il messaggio e rispondi da lì." }, + "desktopEdit": { + "edit": "Modifica", + "edit_named": "Modifica {name}", + "opened": "{name} è aperto nel suo programma. Salva lì le modifiche e ti verrà chiesto cosa farne.", + "offers_label": "Allegati modificati", + "changed_title": "{name} è stato modificato", + "changed_body": "Hai salvato delle modifiche in un altro programma. Cosa vuoi farne?", + "reply": "Allega a una risposta", + "new_message": "Allega a un nuovo messaggio", + "open_draft": "Apri bozza", + "save_copy": "Salva una copia…", + "discard": "Scarta le modifiche…", + "discard_title": "Scartare le modifiche a {name}?", + "discard_detail": "La copia modificata viene eliminata. L’allegato originale non cambia.", + "discard_confirm": "Scarta", + "cancel": "Annulla", + "update": "Aggiorna allegato", + "no_app": "Nessun programma di questo computer può aprire questo file.", + "blocked_type": "Questo tipo di file non può essere aperto per la modifica, perché potrebbe essere eseguito come programma.", + "blocked_policy": "La tua organizzazione non consente di salvare allegati su questo dispositivo.", + "removed_policy": "La tua organizzazione non lo consente più, quindi la copia modificata di {name} è stata eliminata.", + "too_large": "Questo file è troppo grande per essere aperto e modificato.", + "too_many": "Ci sono troppi file aperti per la modifica. Prima terminane alcuni.", + "failed": "Non è stato possibile aprire il file per la modifica.", + "read_busy": "Un altro programma sta ancora usando {name}. Chiudilo lì e riprova.", + "read_failed": "Non è stato possibile leggere la copia modificata di {name}.", + "send_stale_title": "{name} ha modifiche che non sono in questo messaggio", + "send_stale_detail": "Se invii ora, il messaggio parte con la versione precedente. Le modifiche restano su questo computer finché non decidi cosa farne.", + "send_stale_send": "Invia comunque", + "send_stale_back": "Torna indietro", + "signout_title": "Uscire ed eliminare le modifiche?", + "signout_detail": "Gli allegati modificati ma non allegati né salvati vengono eliminati quando esci.", + "signout_confirm": "Esci", + "lock_note": "I file aperti con Modifica restano aperti nel loro programma mentre l’app è bloccata, e restano leggibili su questo computer. Non se ne possono aprire altri finché non la sblocchi." + }, "desktopReminders": { "generic_title": "Promemoria", "snooze": "Rimanda di {count} min", diff --git a/locales/ja/common.json b/locales/ja/common.json index 3eda5c005..1d4063e78 100644 --- a/locales/ja/common.json +++ b/locales/ja/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "ファイルをコピーできませんでした。", "reply_lost": "入力した返信を保持できませんでした。メッセージを開いて返信してください。" }, + "desktopEdit": { + "edit": "編集", + "edit_named": "{name} を編集", + "opened": "{name} を対応するプログラムで開きました。そこで変更を保存すると、どうするかを確認します。", + "offers_label": "編集した添付ファイル", + "changed_title": "{name} が変更されました", + "changed_body": "別のプログラムで変更を保存しました。どうしますか?", + "reply": "返信に添付", + "new_message": "新しいメッセージに添付", + "open_draft": "下書きを開く", + "save_copy": "コピーを保存…", + "discard": "編集内容を破棄…", + "discard_title": "{name} の編集内容を破棄しますか?", + "discard_detail": "編集したコピーは削除されます。元の添付ファイルは変わりません。", + "discard_confirm": "破棄", + "cancel": "キャンセル", + "update": "添付ファイルを更新", + "no_app": "このコンピューターには、このファイルを開けるプログラムがありません。", + "blocked_type": "この種類のファイルはプログラムとして実行される可能性があるため、編集用に開けません。", + "blocked_policy": "組織により、このデバイスへの添付ファイルの保存は許可されていません。", + "removed_policy": "組織で許可されなくなったため、{name} の編集済みコピーを削除しました。", + "too_large": "このファイルは大きすぎるため、編集用に開けません。", + "too_many": "編集用に開いているファイルが多すぎます。先にいくつか終わらせてください。", + "failed": "ファイルを編集用に開けませんでした。", + "read_busy": "別のプログラムが {name} をまだ使用しています。そちらで閉じてから、もう一度お試しください。", + "read_failed": "{name} の編集済みコピーを読み取れませんでした。", + "send_stale_title": "{name} には、このメッセージに含まれていない編集内容があります", + "send_stale_detail": "今送信すると、古いバージョンが送られます。編集内容は、どうするか決めるまでこのコンピューターに残ります。", + "send_stale_send": "このまま送信", + "send_stale_back": "戻る", + "signout_title": "サインアウトして編集内容を削除しますか?", + "signout_detail": "編集したものの添付も保存もしていないファイルは、サインアウト時に削除されます。", + "signout_confirm": "サインアウト", + "lock_note": "「編集」で開いたファイルは、アプリのロック中もそのプログラムで開いたままになり、このコンピューター上で読み取れる状態のままです。新しいファイルはロック解除まで開けません。" + }, "desktopReminders": { "generic_title": "リマインダー", "snooze": "{count} 分後に再通知", diff --git a/locales/ko/common.json b/locales/ko/common.json index 355bdbb3f..d6433ab06 100644 --- a/locales/ko/common.json +++ b/locales/ko/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "파일을 복사할 수 없습니다.", "reply_lost": "입력한 답장을 유지할 수 없습니다. 메시지를 열어 답장하세요." }, + "desktopEdit": { + "edit": "편집", + "edit_named": "{name} 편집", + "opened": "{name}이(가) 해당 프로그램에서 열렸습니다. 그곳에서 변경 내용을 저장하면 어떻게 할지 묻습니다.", + "offers_label": "편집한 첨부 파일", + "changed_title": "{name}이(가) 변경되었습니다", + "changed_body": "다른 프로그램에서 변경 내용을 저장했습니다. 어떻게 할까요?", + "reply": "답장에 첨부", + "new_message": "새 메시지에 첨부", + "open_draft": "임시보관함 열기", + "save_copy": "사본 저장…", + "discard": "편집 내용 버리기…", + "discard_title": "{name}의 편집 내용을 버릴까요?", + "discard_detail": "편집한 사본이 삭제됩니다. 원본 첨부 파일은 바뀌지 않습니다.", + "discard_confirm": "버리기", + "cancel": "취소", + "update": "첨부 파일 업데이트", + "no_app": "이 컴퓨터에는 이 파일을 열 수 있는 프로그램이 없습니다.", + "blocked_type": "이 파일 형식은 프로그램으로 실행될 수 있어 편집용으로 열 수 없습니다.", + "blocked_policy": "조직에서 이 기기에 첨부 파일을 저장하는 것을 허용하지 않습니다.", + "removed_policy": "조직에서 더 이상 허용하지 않아 {name}의 편집한 사본을 삭제했습니다.", + "too_large": "이 파일은 너무 커서 편집용으로 열 수 없습니다.", + "too_many": "편집용으로 열린 파일이 너무 많습니다. 먼저 일부를 마무리하세요.", + "failed": "파일을 편집용으로 열 수 없습니다.", + "read_busy": "다른 프로그램이 아직 {name}을(를) 사용 중입니다. 그곳에서 닫고 다시 시도하세요.", + "read_failed": "{name}의 편집한 사본을 읽을 수 없습니다.", + "send_stale_title": "{name}에 이 메시지에 없는 편집 내용이 있습니다", + "send_stale_detail": "지금 보내면 이전 버전으로 전송됩니다. 편집 내용은 어떻게 할지 결정할 때까지 이 컴퓨터에 남아 있습니다.", + "send_stale_send": "그래도 보내기", + "send_stale_back": "돌아가기", + "signout_title": "로그아웃하고 편집 내용을 삭제할까요?", + "signout_detail": "편집했지만 첨부하거나 저장하지 않은 파일은 로그아웃할 때 삭제됩니다.", + "signout_confirm": "로그아웃", + "lock_note": "편집으로 연 파일은 앱이 잠겨 있는 동안에도 해당 프로그램에서 계속 열려 있으며 이 컴퓨터에서 계속 읽을 수 있습니다. 잠금을 해제할 때까지 새 파일은 열 수 없습니다." + }, "desktopReminders": { "generic_title": "알림", "snooze": "{count}분 후 다시 알림", diff --git a/locales/lv/common.json b/locales/lv/common.json index 2f5d9e297..b1a1deba0 100644 --- a/locales/lv/common.json +++ b/locales/lv/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Failu neizdevās nokopēt.", "reply_lost": "Ievadīto atbildi neizdevās saglabāt. Atveriet ziņojumu un atbildiet tur." }, + "desktopEdit": { + "edit": "Rediģēt", + "edit_named": "Rediģēt {name}", + "opened": "{name} ir atvērts savā programmā. Saglabājiet izmaiņas tur, un jums jautās, ko ar tām darīt.", + "offers_label": "Rediģētie pielikumi", + "changed_title": "{name} ir mainīts", + "changed_body": "Jūs saglabājāt izmaiņas citā programmā. Ko ar tām darīt?", + "reply": "Pievienot atbildei", + "new_message": "Pievienot jaunam ziņojumam", + "open_draft": "Atvērt melnrakstu", + "save_copy": "Saglabāt kopiju…", + "discard": "Atmest izmaiņas…", + "discard_title": "Vai atmest {name} izmaiņas?", + "discard_detail": "Rediģētā kopija tiek izdzēsta. Sākotnējais pielikums nemainās.", + "discard_confirm": "Atmest", + "cancel": "Atcelt", + "update": "Atjaunināt pielikumu", + "no_app": "Neviena šī datora programma nevar atvērt šo failu.", + "blocked_type": "Šo faila veidu nevar atvērt rediģēšanai, jo tas var darboties kā programma.", + "blocked_policy": "Jūsu organizācija neļauj saglabāt pielikumus šajā ierīcē.", + "removed_policy": "Jūsu organizācija to vairs neļauj, tāpēc {name} rediģētā kopija ir izdzēsta.", + "too_large": "Šis fails ir pārāk liels, lai to atvērtu rediģēšanai.", + "too_many": "Rediģēšanai atvērts pārāk daudz failu. Vispirms pabeidziet dažus no tiem.", + "failed": "Failu neizdevās atvērt rediģēšanai.", + "read_busy": "Cita programma joprojām izmanto {name}. Aizveriet to tur un mēģiniet vēlreiz.", + "read_failed": "Neizdevās nolasīt {name} rediģēto kopiju.", + "send_stale_title": "{name} ir izmaiņas, kuru nav šajā ziņojumā", + "send_stale_detail": "Ja sūtīsiet tagad, ziņojums aizies ar vecāko versiju. Jūsu izmaiņas paliek šajā datorā, līdz izlemsiet, ko ar tām darīt.", + "send_stale_send": "Tomēr sūtīt", + "send_stale_back": "Atpakaļ", + "signout_title": "Vai izrakstīties un dzēst izmaiņas?", + "signout_detail": "Pielikumi, ko rediģējāt, bet nepievienojāt un nesaglabājāt, izrakstoties tiek izdzēsti.", + "signout_confirm": "Izrakstīties", + "lock_note": "Faili, kas atvērti ar Rediģēt, paliek atvērti savā programmā, kamēr lietotne ir bloķēta, un paliek lasāmi šajā datorā. Jaunus nevar atvērt, kamēr neatbloķēsiet." + }, "desktopReminders": { "generic_title": "Atgādinājums", "snooze": "Atlikt par {count} min", diff --git a/locales/mn/common.json b/locales/mn/common.json index cf0de6ec1..8ae7f8dc5 100644 --- a/locales/mn/common.json +++ b/locales/mn/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Файлыг хуулж чадсангүй.", "reply_lost": "Бичсэн хариуг хадгалж чадсангүй. Захиаг нээгээд тэндээс хариулна уу." }, + "desktopEdit": { + "edit": "Засах", + "edit_named": "{name} засах", + "opened": "{name} өөрийн программд нээлттэй байна. Өөрчлөлтөө тэнд хадгалаарай, тэгвэл юу хийхийг асууна.", + "offers_label": "Зассан хавсралтууд", + "changed_title": "{name} өөрчлөгдлөө", + "changed_body": "Та өөр программд өөрчлөлт хадгалсан байна. Үүнийг яах вэ?", + "reply": "Хариунд хавсаргах", + "new_message": "Шинэ зурваст хавсаргах", + "open_draft": "Ноорог нээх", + "save_copy": "Хуулбар хадгалах…", + "discard": "Засваруудыг хаях…", + "discard_title": "{name}-ийн засваруудыг хаях уу?", + "discard_detail": "Зассан хуулбар устана. Анхны хавсралт өөрчлөгдөхгүй.", + "discard_confirm": "Хаях", + "cancel": "Цуцлах", + "update": "Хавсралтыг шинэчлэх", + "no_app": "Энэ компьютерийн ямар ч программ энэ файлыг нээж чадахгүй.", + "blocked_type": "Энэ төрлийн файл программ болж ажиллаж болзошгүй тул засахаар нээх боломжгүй.", + "blocked_policy": "Танай байгууллага энэ төхөөрөмжид хавсралт хадгалахыг зөвшөөрдөггүй.", + "removed_policy": "Танай байгууллага үүнийг зөвшөөрөхөө больсон тул {name}-ийн зассан хуулбарыг устгалаа.", + "too_large": "Энэ файл засахаар нээхэд хэт том байна.", + "too_many": "Засахаар хэт олон файл нээлттэй байна. Эхлээд заримыг нь дуусгаарай.", + "failed": "Файлыг засахаар нээж чадсангүй.", + "read_busy": "Өөр программ {name}-г ашигласаар байна. Тэнд хаагаад дахин оролдоно уу.", + "read_failed": "{name}-ийн зассан хуулбарыг уншиж чадсангүй.", + "send_stale_title": "{name}-д энэ зурваст ороогүй засвар байна", + "send_stale_detail": "Одоо илгээвэл зурвас хуучин хувилбартайгаа явна. Таны засварууд шийдвэр гаргах хүртэл энэ компьютерт үлдэнэ.", + "send_stale_send": "Ямар ч байсан илгээх", + "send_stale_back": "Буцах", + "signout_title": "Гарч, засваруудаа устгах уу?", + "signout_detail": "Зассан боловч хавсаргаагүй, хадгалаагүй хавсралтууд гарах үед устана.", + "signout_confirm": "Гарах", + "lock_note": "Засах-аар нээсэн файлууд апп түгжээтэй үед ч өөрийн программд нээлттэй хэвээр байх бөгөөд энэ компьютерт уншигдах боломжтой хэвээр байна. Түгжээг тайлах хүртэл шинээр нээх боломжгүй." + }, "desktopReminders": { "generic_title": "Сануулга", "snooze": "{count} минут хойшлуулах", diff --git a/locales/nb/common.json b/locales/nb/common.json index c434676eb..44fca5515 100644 --- a/locales/nb/common.json +++ b/locales/nb/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Filen kunne ikke kopieres.", "reply_lost": "Svaret du skrev, kunne ikke beholdes. Åpne meldingen og svar der." }, + "desktopEdit": { + "edit": "Rediger", + "edit_named": "Rediger {name}", + "opened": "{name} er åpen i programmet sitt. Lagre endringene der, så blir du spurt om hva som skal skje med dem.", + "offers_label": "Redigerte vedlegg", + "changed_title": "{name} ble endret", + "changed_body": "Du lagret endringer i et annet program. Hva skal skje med dem?", + "reply": "Legg ved et svar", + "new_message": "Legg ved en ny melding", + "open_draft": "Åpne utkast", + "save_copy": "Lagre en kopi…", + "discard": "Forkast endringer…", + "discard_title": "Vil du forkaste endringene i {name}?", + "discard_detail": "Den redigerte kopien slettes. Det opprinnelige vedlegget endres ikke.", + "discard_confirm": "Forkast", + "cancel": "Avbryt", + "update": "Oppdater vedlegg", + "no_app": "Ingen programmer på denne datamaskinen kan åpne filen.", + "blocked_type": "Denne filtypen kan ikke åpnes for redigering fordi den kan kjøre som et program.", + "blocked_policy": "Organisasjonen din tillater ikke lagring av vedlegg på denne enheten.", + "removed_policy": "Organisasjonen din tillater ikke dette lenger, så den redigerte kopien av {name} ble slettet.", + "too_large": "Filen er for stor til å åpnes for redigering.", + "too_many": "For mange filer er åpne for redigering. Gjør ferdig noen av dem først.", + "failed": "Filen kunne ikke åpnes for redigering.", + "read_busy": "Et annet program bruker fortsatt {name}. Lukk den der og prøv igjen.", + "read_failed": "Den redigerte kopien av {name} kunne ikke leses.", + "send_stale_title": "{name} har endringer som ikke er i denne meldingen", + "send_stale_detail": "Hvis du sender nå, går meldingen med den eldre versjonen. Endringene blir på denne datamaskinen til du bestemmer hva som skal skje med dem.", + "send_stale_send": "Send likevel", + "send_stale_back": "Tilbake", + "signout_title": "Vil du logge ut og slette endringene?", + "signout_detail": "Vedlegg du har redigert, men ikke lagt ved eller lagret, slettes når du logger ut.", + "signout_confirm": "Logg ut", + "lock_note": "Filer du åpnet med Rediger, forblir åpne i programmet sitt mens appen er låst, og kan fortsatt leses på denne datamaskinen. Nye kan ikke åpnes før du låser opp." + }, "desktopReminders": { "generic_title": "Påminnelse", "snooze": "Utsett {count} min", diff --git a/locales/nl/common.json b/locales/nl/common.json index 3afb0250b..0e91f5b33 100644 --- a/locales/nl/common.json +++ b/locales/nl/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Het bestand kon niet worden gekopieerd.", "reply_lost": "Je getypte antwoord kon niet worden bewaard. Open het bericht en antwoord daar." }, + "desktopEdit": { + "edit": "Bewerken", + "edit_named": "{name} bewerken", + "opened": "{name} is geopend in zijn programma. Sla uw wijzigingen daar op, dan wordt u gevraagd wat ermee moet gebeuren.", + "offers_label": "Bewerkte bijlagen", + "changed_title": "{name} is gewijzigd", + "changed_body": "U hebt wijzigingen opgeslagen in een ander programma. Wat moet daarmee gebeuren?", + "reply": "Bijvoegen bij een antwoord", + "new_message": "Bijvoegen bij een nieuw bericht", + "open_draft": "Concept openen", + "save_copy": "Kopie opslaan…", + "discard": "Wijzigingen weggooien…", + "discard_title": "Uw wijzigingen in {name} weggooien?", + "discard_detail": "De bewerkte kopie wordt verwijderd. De oorspronkelijke bijlage verandert niet.", + "discard_confirm": "Weggooien", + "cancel": "Annuleren", + "update": "Bijlage bijwerken", + "no_app": "Geen enkel programma op deze computer kan dit bestand openen.", + "blocked_type": "Dit type bestand kan niet worden geopend om te bewerken, omdat het als programma kan worden uitgevoerd.", + "blocked_policy": "Uw organisatie staat niet toe dat bijlagen op dit apparaat worden opgeslagen.", + "removed_policy": "Uw organisatie staat dit niet meer toe, dus de bewerkte kopie van {name} is verwijderd.", + "too_large": "Dit bestand is te groot om te openen en te bewerken.", + "too_many": "Er zijn te veel bestanden geopend om te bewerken. Rond er eerst een paar af.", + "failed": "Het bestand kon niet worden geopend om te bewerken.", + "read_busy": "Een ander programma gebruikt {name} nog. Sluit het daar en probeer het opnieuw.", + "read_failed": "De bewerkte kopie van {name} kon niet worden gelezen.", + "send_stale_title": "{name} heeft wijzigingen die niet in dit bericht staan", + "send_stale_detail": "Als u nu verzendt, gaat het bericht met de oudere versie mee. Uw wijzigingen blijven op deze computer tot u beslist wat ermee moet gebeuren.", + "send_stale_send": "Toch verzenden", + "send_stale_back": "Terug", + "signout_title": "Afmelden en uw wijzigingen verwijderen?", + "signout_detail": "Bijlagen die u hebt bewerkt maar niet hebt bijgevoegd of opgeslagen, worden bij het afmelden verwijderd.", + "signout_confirm": "Afmelden", + "lock_note": "Bestanden die u met Bewerken hebt geopend, blijven in hun programma geopend terwijl de app is vergrendeld, en blijven leesbaar op deze computer. Nieuwe kunnen pas na het ontgrendelen worden geopend." + }, "desktopReminders": { "generic_title": "Herinnering", "snooze": "{count} min uitstellen", diff --git a/locales/pl/common.json b/locales/pl/common.json index 003c9b529..c2c1d8920 100644 --- a/locales/pl/common.json +++ b/locales/pl/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Nie udało się skopiować pliku.", "reply_lost": "Nie udało się zachować wpisanej odpowiedzi. Otwórz wiadomość i odpowiedz w niej." }, + "desktopEdit": { + "edit": "Edytuj", + "edit_named": "Edytuj {name}", + "opened": "{name} jest otwarty w swoim programie. Zapisz tam zmiany, a zapytamy, co z nimi zrobić.", + "offers_label": "Edytowane załączniki", + "changed_title": "{name} został zmieniony", + "changed_body": "Zapisano zmiany w innym programie. Co z nimi zrobić?", + "reply": "Dołącz do odpowiedzi", + "new_message": "Dołącz do nowej wiadomości", + "open_draft": "Otwórz wersję roboczą", + "save_copy": "Zapisz kopię…", + "discard": "Odrzuć zmiany…", + "discard_title": "Odrzucić zmiany w {name}?", + "discard_detail": "Edytowana kopia zostanie usunięta. Oryginalny załącznik się nie zmieni.", + "discard_confirm": "Odrzuć", + "cancel": "Anuluj", + "update": "Zaktualizuj załącznik", + "no_app": "Żaden program na tym komputerze nie może otworzyć tego pliku.", + "blocked_type": "Tego typu pliku nie można otworzyć do edycji, ponieważ mógłby uruchomić się jako program.", + "blocked_policy": "Twoja organizacja nie zezwala na zapisywanie załączników na tym urządzeniu.", + "removed_policy": "Twoja organizacja już na to nie zezwala, więc edytowana kopia {name} została usunięta.", + "too_large": "Ten plik jest za duży, aby otworzyć go do edycji.", + "too_many": "Do edycji otwarto zbyt wiele plików. Najpierw zakończ pracę z niektórymi.", + "failed": "Nie udało się otworzyć pliku do edycji.", + "read_busy": "Inny program nadal używa {name}. Zamknij go tam i spróbuj ponownie.", + "read_failed": "Nie udało się odczytać edytowanej kopii {name}.", + "send_stale_title": "{name} ma zmiany, których nie ma w tej wiadomości", + "send_stale_detail": "Jeśli wyślesz teraz, wiadomość pójdzie ze starszą wersją. Zmiany zostaną na tym komputerze, dopóki nie zdecydujesz, co z nimi zrobić.", + "send_stale_send": "Wyślij mimo to", + "send_stale_back": "Wróć", + "signout_title": "Wylogować i usunąć zmiany?", + "signout_detail": "Załączniki, które edytowano, ale nie dołączono ani nie zapisano, zostaną usunięte przy wylogowaniu.", + "signout_confirm": "Wyloguj", + "lock_note": "Pliki otwarte przez Edytuj pozostają otwarte w swoim programie, gdy aplikacja jest zablokowana, i można je nadal odczytać na tym komputerze. Nowych nie można otworzyć przed odblokowaniem." + }, "desktopReminders": { "generic_title": "Przypomnienie", "snooze": "Odłóż o {count} min", diff --git a/locales/pt/common.json b/locales/pt/common.json index 4cfe8b1e4..120c9e1ad 100644 --- a/locales/pt/common.json +++ b/locales/pt/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Não foi possível copiar o ficheiro.", "reply_lost": "Não foi possível guardar a resposta escrita. Abra a mensagem e responda a partir dela." }, + "desktopEdit": { + "edit": "Editar", + "edit_named": "Editar {name}", + "opened": "{name} está aberto no respetivo programa. Guarde lá as alterações e ser-lhe-á perguntado o que fazer com elas.", + "offers_label": "Anexos editados", + "changed_title": "{name} foi alterado", + "changed_body": "Guardou alterações noutro programa. O que pretende fazer com elas?", + "reply": "Anexar a uma resposta", + "new_message": "Anexar a uma nova mensagem", + "open_draft": "Abrir rascunho", + "save_copy": "Guardar uma cópia…", + "discard": "Rejeitar alterações…", + "discard_title": "Rejeitar as alterações a {name}?", + "discard_detail": "A cópia editada é eliminada. O anexo original não muda.", + "discard_confirm": "Rejeitar", + "cancel": "Cancelar", + "update": "Atualizar anexo", + "no_app": "Nenhum programa deste computador consegue abrir este ficheiro.", + "blocked_type": "Este tipo de ficheiro não pode ser aberto para edição, porque pode ser executado como programa.", + "blocked_policy": "A sua organização não permite guardar anexos neste dispositivo.", + "removed_policy": "A sua organização já não o permite, por isso a cópia editada de {name} foi eliminada.", + "too_large": "Este ficheiro é demasiado grande para ser aberto para edição.", + "too_many": "Há demasiados ficheiros abertos para edição. Termine primeiro alguns deles.", + "failed": "Não foi possível abrir o ficheiro para edição.", + "read_busy": "Outro programa ainda está a usar {name}. Feche-o lá e tente novamente.", + "read_failed": "Não foi possível ler a cópia editada de {name}.", + "send_stale_title": "{name} tem alterações que não estão nesta mensagem", + "send_stale_detail": "Se enviar agora, a mensagem segue com a versão anterior. As suas alterações ficam neste computador até decidir o que fazer com elas.", + "send_stale_send": "Enviar na mesma", + "send_stale_back": "Voltar", + "signout_title": "Terminar sessão e eliminar as alterações?", + "signout_detail": "Os anexos que editou, mas não anexou nem guardou, são eliminados ao terminar sessão.", + "signout_confirm": "Terminar sessão", + "lock_note": "Os ficheiros abertos com Editar continuam abertos no respetivo programa enquanto a aplicação está bloqueada, e continuam legíveis neste computador. Não é possível abrir outros até desbloquear." + }, "desktopReminders": { "generic_title": "Lembrete", "snooze": "Adiar {count} min", diff --git a/locales/ro/common.json b/locales/ro/common.json index 572f9b856..544ef7c76 100644 --- a/locales/ro/common.json +++ b/locales/ro/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Fișierul nu a putut fi copiat.", "reply_lost": "Răspunsul scris nu a putut fi păstrat. Deschide mesajul și răspunde de acolo." }, + "desktopEdit": { + "edit": "Editează", + "edit_named": "Editează {name}", + "opened": "{name} este deschis în programul său. Salvați modificările acolo și veți fi întrebat ce să faceți cu ele.", + "offers_label": "Atașamente editate", + "changed_title": "{name} a fost modificat", + "changed_body": "Ați salvat modificări în alt program. Ce să se întâmple cu ele?", + "reply": "Atașează la un răspuns", + "new_message": "Atașează la un mesaj nou", + "open_draft": "Deschide ciorna", + "save_copy": "Salvează o copie…", + "discard": "Renunță la modificări…", + "discard_title": "Renunțați la modificările din {name}?", + "discard_detail": "Copia editată este ștearsă. Atașamentul original nu se schimbă.", + "discard_confirm": "Renunță", + "cancel": "Anulează", + "update": "Actualizează atașamentul", + "no_app": "Niciun program de pe acest computer nu poate deschide acest fișier.", + "blocked_type": "Acest tip de fișier nu poate fi deschis pentru editare, deoarece ar putea rula ca program.", + "blocked_policy": "Organizația dvs. nu permite salvarea atașamentelor pe acest dispozitiv.", + "removed_policy": "Organizația dvs. nu mai permite acest lucru, așa că a fost ștearsă copia editată a {name}.", + "too_large": "Acest fișier este prea mare pentru a fi deschis pentru editare.", + "too_many": "Sunt prea multe fișiere deschise pentru editare. Terminați mai întâi cu câteva.", + "failed": "Fișierul nu a putut fi deschis pentru editare.", + "read_busy": "Alt program încă folosește {name}. Închideți-l acolo și încercați din nou.", + "read_failed": "Copia editată a {name} nu a putut fi citită.", + "send_stale_title": "{name} are modificări care nu sunt în acest mesaj", + "send_stale_detail": "Dacă trimiteți acum, mesajul pleacă cu versiunea mai veche. Modificările rămân pe acest computer până când decideți ce faceți cu ele.", + "send_stale_send": "Trimite oricum", + "send_stale_back": "Înapoi", + "signout_title": "Vă deconectați și ștergeți modificările?", + "signout_detail": "Atașamentele editate, dar neatașate și nesalvate, sunt șterse la deconectare.", + "signout_confirm": "Deconectare", + "lock_note": "Fișierele deschise cu Editează rămân deschise în programul lor cât timp aplicația este blocată și rămân lizibile pe acest computer. Altele noi nu se pot deschide până la deblocare." + }, "desktopReminders": { "generic_title": "Memento", "snooze": "Amână {count} min", diff --git a/locales/ru/common.json b/locales/ru/common.json index 2fdb08106..1165390e8 100644 --- a/locales/ru/common.json +++ b/locales/ru/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Не удалось скопировать файл.", "reply_lost": "Не удалось сохранить введённый ответ. Откройте письмо и ответьте из него." }, + "desktopEdit": { + "edit": "Изменить", + "edit_named": "Изменить {name}", + "opened": "{name} открыт в своей программе. Сохраните там изменения, и вас спросят, что с ними сделать.", + "offers_label": "Изменённые вложения", + "changed_title": "{name} изменён", + "changed_body": "Вы сохранили изменения в другой программе. Что с ними сделать?", + "reply": "Вложить в ответ", + "new_message": "Вложить в новое письмо", + "open_draft": "Открыть черновик", + "save_copy": "Сохранить копию…", + "discard": "Отменить изменения…", + "discard_title": "Отменить изменения в {name}?", + "discard_detail": "Изменённая копия будет удалена. Исходное вложение не изменится.", + "discard_confirm": "Отменить изменения", + "cancel": "Отмена", + "update": "Обновить вложение", + "no_app": "Ни одна программа на этом компьютере не может открыть этот файл.", + "blocked_type": "Файл такого типа нельзя открыть для изменения: он может запуститься как программа.", + "blocked_policy": "Ваша организация не разрешает сохранять вложения на этом устройстве.", + "removed_policy": "Ваша организация больше этого не разрешает, поэтому изменённая копия {name} удалена.", + "too_large": "Этот файл слишком большой, чтобы открыть его для изменения.", + "too_many": "Для изменения открыто слишком много файлов. Сначала закончите с некоторыми из них.", + "failed": "Не удалось открыть файл для изменения.", + "read_busy": "Другая программа ещё использует {name}. Закройте его там и повторите попытку.", + "read_failed": "Не удалось прочитать изменённую копию {name}.", + "send_stale_title": "В {name} есть изменения, которых нет в этом письме", + "send_stale_detail": "Если отправить сейчас, письмо уйдёт со старой версией. Ваши изменения останутся на этом компьютере, пока вы не решите, что с ними делать.", + "send_stale_send": "Всё равно отправить", + "send_stale_back": "Назад", + "signout_title": "Выйти и удалить изменения?", + "signout_detail": "Вложения, которые вы изменили, но не вложили и не сохранили, при выходе удаляются.", + "signout_confirm": "Выйти", + "lock_note": "Файлы, открытые через «Изменить», остаются открытыми в своей программе, пока приложение заблокировано, и их по-прежнему можно прочитать на этом компьютере. Новые нельзя открыть, пока вы не разблокируете приложение." + }, "desktopReminders": { "generic_title": "Напоминание", "snooze": "Отложить на {count} мин", diff --git a/locales/sk/common.json b/locales/sk/common.json index d8a42ccfb..f5e8778cc 100644 --- a/locales/sk/common.json +++ b/locales/sk/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Súbor sa nepodarilo skopírovať.", "reply_lost": "Napísanú odpoveď sa nepodarilo zachovať. Otvorte správu a odpovedzte v nej." }, + "desktopEdit": { + "edit": "Upraviť", + "edit_named": "Upraviť {name}", + "opened": "{name} je otvorený vo svojom programe. Uložte tam zmeny a potom sa vás spýtame, čo s nimi urobiť.", + "offers_label": "Upravené prílohy", + "changed_title": "{name} sa zmenil", + "changed_body": "Uložili ste zmeny v inom programe. Čo s nimi chcete urobiť?", + "reply": "Pripojiť k odpovedi", + "new_message": "Pripojiť k novej správe", + "open_draft": "Otvoriť koncept", + "save_copy": "Uložiť kópiu…", + "discard": "Zahodiť zmeny…", + "discard_title": "Zahodiť zmeny v {name}?", + "discard_detail": "Upravená kópia sa odstráni. Pôvodná príloha sa nezmení.", + "discard_confirm": "Zahodiť", + "cancel": "Zrušiť", + "update": "Aktualizovať prílohu", + "no_app": "Tento súbor nedokáže otvoriť žiadny program v tomto počítači.", + "blocked_type": "Tento typ súboru nemožno otvoriť na úpravy, pretože by sa mohol spustiť ako program.", + "blocked_policy": "Vaša organizácia nepovoľuje ukladať prílohy do tohto zariadenia.", + "removed_policy": "Vaša organizácia to už nepovoľuje, preto bola upravená kópia {name} odstránená.", + "too_large": "Tento súbor je príliš veľký na otvorenie na úpravy.", + "too_many": "Na úpravy je otvorených príliš veľa súborov. Niektoré najprv dokončite.", + "failed": "Súbor sa nepodarilo otvoriť na úpravy.", + "read_busy": "{name} stále používa iný program. Zatvorte ho tam a skúste to znova.", + "read_failed": "Upravenú kópiu {name} sa nepodarilo prečítať.", + "send_stale_title": "{name} má zmeny, ktoré v tejto správe nie sú", + "send_stale_detail": "Ak odošlete teraz, správa odíde so staršou verziou. Vaše zmeny zostanú v tomto počítači, kým sa nerozhodnete, čo s nimi.", + "send_stale_send": "Napriek tomu odoslať", + "send_stale_back": "Späť", + "signout_title": "Odhlásiť sa a odstrániť zmeny?", + "signout_detail": "Prílohy, ktoré ste upravili, ale nepripojili ani neuložili, sa pri odhlásení odstránia.", + "signout_confirm": "Odhlásiť sa", + "lock_note": "Súbory otvorené cez Upraviť zostávajú otvorené vo svojom programe, kým je aplikácia zamknutá, a zostávajú v tomto počítači čitateľné. Nové sa otvoria až po odomknutí." + }, "desktopReminders": { "generic_title": "Pripomienka", "snooze": "Odložiť o {count} min", diff --git a/locales/th/common.json b/locales/th/common.json index af4128993..8afc2658f 100644 --- a/locales/th/common.json +++ b/locales/th/common.json @@ -6966,6 +6966,41 @@ "copy_failed": "คัดลอกไฟล์ไม่ได้", "reply_lost": "ไม่สามารถเก็บคำตอบที่พิมพ์ไว้ได้ เปิดข้อความแล้วตอบจากที่นั่น" }, + "desktopEdit": { + "edit": "แก้ไข", + "edit_named": "แก้ไข {name}", + "opened": "{name} เปิดอยู่ในโปรแกรมของไฟล์นั้น บันทึกการเปลี่ยนแปลงที่นั่น แล้วระบบจะถามว่าจะทำอย่างไรกับการเปลี่ยนแปลงนั้น", + "offers_label": "ไฟล์แนบที่แก้ไขแล้ว", + "changed_title": "{name} มีการเปลี่ยนแปลง", + "changed_body": "คุณบันทึกการเปลี่ยนแปลงในโปรแกรมอื่น จะให้ทำอย่างไรกับการเปลี่ยนแปลงนั้น", + "reply": "แนบไปกับการตอบกลับ", + "new_message": "แนบไปกับข้อความใหม่", + "open_draft": "เปิดฉบับร่าง", + "save_copy": "บันทึกสำเนา…", + "discard": "ละทิ้งการแก้ไข…", + "discard_title": "ละทิ้งการแก้ไขใน {name} หรือไม่", + "discard_detail": "สำเนาที่แก้ไขจะถูกลบ ไฟล์แนบต้นฉบับจะไม่เปลี่ยนแปลง", + "discard_confirm": "ละทิ้ง", + "cancel": "ยกเลิก", + "update": "อัปเดตไฟล์แนบ", + "no_app": "ไม่มีโปรแกรมในคอมพิวเตอร์นี้ที่เปิดไฟล์นี้ได้", + "blocked_type": "เปิดไฟล์ประเภทนี้เพื่อแก้ไขไม่ได้ เพราะอาจทำงานเป็นโปรแกรมได้", + "blocked_policy": "องค์กรของคุณไม่อนุญาตให้บันทึกไฟล์แนบในอุปกรณ์นี้", + "removed_policy": "องค์กรของคุณไม่อนุญาตอีกต่อไป จึงลบสำเนาที่แก้ไขของ {name} แล้ว", + "too_large": "ไฟล์นี้ใหญ่เกินกว่าจะเปิดเพื่อแก้ไข", + "too_many": "มีไฟล์ที่เปิดเพื่อแก้ไขมากเกินไป โปรดจัดการบางไฟล์ให้เสร็จก่อน", + "failed": "เปิดไฟล์เพื่อแก้ไขไม่ได้", + "read_busy": "โปรแกรมอื่นยังใช้ {name} อยู่ โปรดปิดที่นั่นแล้วลองอีกครั้ง", + "read_failed": "อ่านสำเนาที่แก้ไขของ {name} ไม่ได้", + "send_stale_title": "{name} มีการแก้ไขที่ไม่ได้อยู่ในข้อความนี้", + "send_stale_detail": "หากส่งตอนนี้ ข้อความจะส่งไปพร้อมเวอร์ชันเก่า การแก้ไขของคุณจะอยู่ในคอมพิวเตอร์นี้จนกว่าคุณจะตัดสินใจ", + "send_stale_send": "ส่งต่อไป", + "send_stale_back": "ย้อนกลับ", + "signout_title": "ออกจากระบบและลบการแก้ไขหรือไม่", + "signout_detail": "ไฟล์แนบที่คุณแก้ไขแต่ยังไม่ได้แนบหรือบันทึกจะถูกลบเมื่อออกจากระบบ", + "signout_confirm": "ออกจากระบบ", + "lock_note": "ไฟล์ที่เปิดด้วยแก้ไขจะยังเปิดอยู่ในโปรแกรมของไฟล์นั้นขณะที่แอปถูกล็อก และยังอ่านได้ในคอมพิวเตอร์นี้ ไฟล์ใหม่จะเปิดไม่ได้จนกว่าคุณจะปลดล็อก" + }, "desktopReminders": { "generic_title": "การแจ้งเตือน", "snooze": "เลื่อน {count} นาที", diff --git a/locales/tr/common.json b/locales/tr/common.json index c74a4ae59..43247eb84 100644 --- a/locales/tr/common.json +++ b/locales/tr/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Dosya kopyalanamadı.", "reply_lost": "Yazdığınız yanıt korunamadı. İletiyi açıp oradan yanıtlayın." }, + "desktopEdit": { + "edit": "Düzenle", + "edit_named": "{name} dosyasını düzenle", + "opened": "{name} kendi programında açık. Değişikliklerinizi orada kaydedin, ardından bunlarla ne yapılacağı size sorulur.", + "offers_label": "Düzenlenen ekler", + "changed_title": "{name} değişti", + "changed_body": "Başka bir programda değişiklik kaydettiniz. Bunlarla ne yapılsın?", + "reply": "Bir yanıta ekle", + "new_message": "Yeni bir iletiye ekle", + "open_draft": "Taslağı aç", + "save_copy": "Kopya kaydet…", + "discard": "Değişikliklerden vazgeç…", + "discard_title": "{name} üzerindeki değişikliklerden vazgeçilsin mi?", + "discard_detail": "Düzenlenen kopya silinir. Asıl ek değişmez.", + "discard_confirm": "Vazgeç", + "cancel": "İptal", + "update": "Eki güncelle", + "no_app": "Bu bilgisayardaki hiçbir program bu dosyayı açamıyor.", + "blocked_type": "Bu dosya türü düzenlemek için açılamaz, çünkü program olarak çalışabilir.", + "blocked_policy": "Kuruluşunuz bu cihaza ek kaydedilmesine izin vermiyor.", + "removed_policy": "Kuruluşunuz artık buna izin vermiyor, bu yüzden {name} dosyasının düzenlenen kopyası silindi.", + "too_large": "Bu dosya düzenlemek için açılamayacak kadar büyük.", + "too_many": "Düzenlemek için çok fazla dosya açık. Önce bazılarını bitirin.", + "failed": "Dosya düzenlemek için açılamadı.", + "read_busy": "{name} hâlâ başka bir program tarafından kullanılıyor. Orada kapatıp yeniden deneyin.", + "read_failed": "{name} dosyasının düzenlenen kopyası okunamadı.", + "send_stale_title": "{name} dosyasında bu iletide olmayan değişiklikler var", + "send_stale_detail": "Şimdi gönderirseniz ileti eski sürümle gider. Değişiklikleriniz, ne yapacağınıza karar verene kadar bu bilgisayarda kalır.", + "send_stale_send": "Yine de gönder", + "send_stale_back": "Geri dön", + "signout_title": "Oturum kapatılıp değişiklikler silinsin mi?", + "signout_detail": "Düzenleyip eklemediğiniz veya kaydetmediğiniz ekler oturumu kapattığınızda silinir.", + "signout_confirm": "Oturumu kapat", + "lock_note": "Düzenle ile açtığınız dosyalar uygulama kilitliyken kendi programlarında açık kalır ve bu bilgisayarda okunabilir olmayı sürdürür. Yenileri kilidi açana kadar açılamaz." + }, "desktopReminders": { "generic_title": "Anımsatıcı", "snooze": "{count} dk ertele", diff --git a/locales/uk/common.json b/locales/uk/common.json index 43227c05e..eaf91b8fc 100644 --- a/locales/uk/common.json +++ b/locales/uk/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "Не вдалося скопіювати файл.", "reply_lost": "Не вдалося зберегти введену відповідь. Відкрийте лист і дайте відповідь у ньому." }, + "desktopEdit": { + "edit": "Редагувати", + "edit_named": "Редагувати {name}", + "opened": "{name} відкрито у своїй програмі. Збережіть там зміни, і вас запитають, що з ними робити.", + "offers_label": "Відредаговані вкладення", + "changed_title": "{name} змінено", + "changed_body": "Ви зберегли зміни в іншій програмі. Що з ними зробити?", + "reply": "Вкласти у відповідь", + "new_message": "Вкласти в новий лист", + "open_draft": "Відкрити чернетку", + "save_copy": "Зберегти копію…", + "discard": "Відкинути зміни…", + "discard_title": "Відкинути зміни в {name}?", + "discard_detail": "Відредаговану копію буде видалено. Початкове вкладення не зміниться.", + "discard_confirm": "Відкинути", + "cancel": "Скасувати", + "update": "Оновити вкладення", + "no_app": "Жодна програма на цьому комп’ютері не може відкрити цей файл.", + "blocked_type": "Файл такого типу не можна відкрити для редагування, бо він може запуститися як програма.", + "blocked_policy": "Ваша організація не дозволяє зберігати вкладення на цьому пристрої.", + "removed_policy": "Ваша організація більше цього не дозволяє, тому відредаговану копію {name} видалено.", + "too_large": "Цей файл завеликий, щоб відкрити його для редагування.", + "too_many": "Для редагування відкрито забагато файлів. Спершу завершіть роботу з деякими з них.", + "failed": "Не вдалося відкрити файл для редагування.", + "read_busy": "Інша програма ще використовує {name}. Закрийте його там і спробуйте ще раз.", + "read_failed": "Не вдалося прочитати відредаговану копію {name}.", + "send_stale_title": "У {name} є зміни, яких немає в цьому листі", + "send_stale_detail": "Якщо надіслати зараз, лист піде зі старішою версією. Ваші зміни залишаться на цьому комп’ютері, доки ви не вирішите, що з ними робити.", + "send_stale_send": "Усе одно надіслати", + "send_stale_back": "Назад", + "signout_title": "Вийти й видалити зміни?", + "signout_detail": "Вкладення, які ви відредагували, але не вклали й не зберегли, під час виходу видаляються.", + "signout_confirm": "Вийти", + "lock_note": "Файли, відкриті через «Редагувати», залишаються відкритими у своїй програмі, поки застосунок заблоковано, і їх усе ще можна прочитати на цьому комп’ютері. Нові не можна відкрити, доки ви не розблокуєте застосунок." + }, "desktopReminders": { "generic_title": "Нагадування", "snooze": "Відкласти на {count} хв", diff --git a/locales/vi/common.json b/locales/vi/common.json index 8c6ef8e6f..90b075dfc 100644 --- a/locales/vi/common.json +++ b/locales/vi/common.json @@ -6970,6 +6970,41 @@ "copy_failed": "Không thể sao chép tệp.", "reply_lost": "Không thể giữ câu trả lời bạn đã nhập. Hãy mở thư và trả lời ở đó." }, + "desktopEdit": { + "edit": "Chỉnh sửa", + "edit_named": "Chỉnh sửa {name}", + "opened": "{name} đang mở trong chương trình của nó. Hãy lưu thay đổi ở đó, rồi bạn sẽ được hỏi muốn làm gì với chúng.", + "offers_label": "Tệp đính kèm đã chỉnh sửa", + "changed_title": "{name} đã thay đổi", + "changed_body": "Bạn đã lưu thay đổi trong một chương trình khác. Bạn muốn làm gì với chúng?", + "reply": "Đính kèm vào thư trả lời", + "new_message": "Đính kèm vào thư mới", + "open_draft": "Mở bản nháp", + "save_copy": "Lưu một bản sao…", + "discard": "Bỏ thay đổi…", + "discard_title": "Bỏ các thay đổi của bạn trong {name}?", + "discard_detail": "Bản sao đã chỉnh sửa sẽ bị xóa. Tệp đính kèm gốc không thay đổi.", + "discard_confirm": "Bỏ", + "cancel": "Hủy", + "update": "Cập nhật tệp đính kèm", + "no_app": "Không có chương trình nào trên máy tính này mở được tệp này.", + "blocked_type": "Không thể mở loại tệp này để chỉnh sửa vì nó có thể chạy như một chương trình.", + "blocked_policy": "Tổ chức của bạn không cho phép lưu tệp đính kèm trên thiết bị này.", + "removed_policy": "Tổ chức của bạn không còn cho phép việc này, nên bản sao đã chỉnh sửa của {name} đã bị xóa.", + "too_large": "Tệp này quá lớn để mở chỉnh sửa.", + "too_many": "Có quá nhiều tệp đang mở để chỉnh sửa. Hãy hoàn tất một vài tệp trước.", + "failed": "Không thể mở tệp để chỉnh sửa.", + "read_busy": "Một chương trình khác vẫn đang dùng {name}. Hãy đóng nó ở đó rồi thử lại.", + "read_failed": "Không đọc được bản sao đã chỉnh sửa của {name}.", + "send_stale_title": "{name} có thay đổi không nằm trong thư này", + "send_stale_detail": "Nếu gửi ngay, thư sẽ đi với phiên bản cũ hơn. Thay đổi của bạn vẫn ở trên máy tính này cho đến khi bạn quyết định.", + "send_stale_send": "Vẫn gửi", + "send_stale_back": "Quay lại", + "signout_title": "Đăng xuất và xóa thay đổi của bạn?", + "signout_detail": "Các tệp bạn đã chỉnh sửa nhưng chưa đính kèm hoặc lưu sẽ bị xóa khi đăng xuất.", + "signout_confirm": "Đăng xuất", + "lock_note": "Các tệp đã mở bằng Chỉnh sửa vẫn mở trong chương trình của chúng khi ứng dụng bị khóa và vẫn đọc được trên máy tính này. Không thể mở tệp mới cho đến khi bạn mở khóa." + }, "desktopReminders": { "generic_title": "Lời nhắc", "snooze": "Báo lại sau {count} phút", diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json index 1028578b1..8796e7340 100644 --- a/locales/zh-TW/common.json +++ b/locales/zh-TW/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "無法複製檔案。", "reply_lost": "無法保留您輸入的回覆。請開啟郵件並在其中回覆。" }, + "desktopEdit": { + "edit": "編輯", + "edit_named": "編輯 {name}", + "opened": "{name} 已在其程式中開啟。請在那裡儲存變更,之後會詢問你要如何處理這些變更。", + "offers_label": "已編輯的附件", + "changed_title": "{name} 已變更", + "changed_body": "你在其他程式中儲存了變更。要如何處理?", + "reply": "附加到回覆", + "new_message": "附加到新郵件", + "open_draft": "開啟草稿", + "save_copy": "儲存複本…", + "discard": "捨棄編輯…", + "discard_title": "要捨棄對 {name} 的編輯嗎?", + "discard_detail": "編輯後的複本會被刪除。原始附件不會改變。", + "discard_confirm": "捨棄", + "cancel": "取消", + "update": "更新附件", + "no_app": "這部電腦上沒有程式能開啟此檔案。", + "blocked_type": "此類檔案可能以程式方式執行,因此無法開啟進行編輯。", + "blocked_policy": "你的組織不允許在此裝置上儲存附件。", + "removed_policy": "你的組織已不再允許此操作,因此 {name} 的編輯複本已被刪除。", + "too_large": "此檔案太大,無法開啟進行編輯。", + "too_many": "開啟編輯的檔案太多。請先處理完其中一些。", + "failed": "無法開啟檔案進行編輯。", + "read_busy": "其他程式仍在使用 {name}。請在那裡關閉後再試一次。", + "read_failed": "無法讀取 {name} 的編輯複本。", + "send_stale_title": "{name} 有未包含在此郵件中的編輯", + "send_stale_detail": "如果現在傳送,郵件將使用舊版本。你的編輯會保留在這部電腦上,直到你決定如何處理。", + "send_stale_send": "仍要傳送", + "send_stale_back": "返回", + "signout_title": "要登出並刪除你的編輯嗎?", + "signout_detail": "已編輯但未附加或儲存的附件會在登出時刪除。", + "signout_confirm": "登出", + "lock_note": "應用程式鎖定期間,透過「編輯」開啟的檔案仍在其程式中保持開啟,並且在這部電腦上仍可讀取。解鎖前無法開啟新檔案。" + }, "desktopReminders": { "generic_title": "提醒", "snooze": "{count} 分鐘後再提醒", diff --git a/locales/zh/common.json b/locales/zh/common.json index 641f7a2cf..48e7a329e 100644 --- a/locales/zh/common.json +++ b/locales/zh/common.json @@ -6958,6 +6958,41 @@ "copy_failed": "无法复制文件。", "reply_lost": "无法保留你输入的回复。请打开邮件并在其中回复。" }, + "desktopEdit": { + "edit": "编辑", + "edit_named": "编辑 {name}", + "opened": "{name} 已在其程序中打开。请在那里保存更改,之后会询问你如何处理这些更改。", + "offers_label": "已编辑的附件", + "changed_title": "{name} 已更改", + "changed_body": "你在其他程序中保存了更改。要如何处理?", + "reply": "附加到回复", + "new_message": "附加到新邮件", + "open_draft": "打开草稿", + "save_copy": "保存副本…", + "discard": "放弃编辑…", + "discard_title": "要放弃对 {name} 的编辑吗?", + "discard_detail": "编辑后的副本将被删除。原始附件不会改变。", + "discard_confirm": "放弃", + "cancel": "取消", + "update": "更新附件", + "no_app": "这台电脑上没有程序能打开此文件。", + "blocked_type": "此类文件可能作为程序运行,因此无法打开进行编辑。", + "blocked_policy": "你的组织不允许在此设备上保存附件。", + "removed_policy": "你的组织已不再允许此操作,因此 {name} 的编辑副本已被删除。", + "too_large": "此文件太大,无法打开进行编辑。", + "too_many": "打开编辑的文件太多。请先处理完其中一些。", + "failed": "无法打开文件进行编辑。", + "read_busy": "其他程序仍在使用 {name}。请在那里关闭后重试。", + "read_failed": "无法读取 {name} 的编辑副本。", + "send_stale_title": "{name} 有未包含在此邮件中的编辑", + "send_stale_detail": "如果现在发送,邮件将使用旧版本。你的编辑会保留在这台电脑上,直到你决定如何处理。", + "send_stale_send": "仍然发送", + "send_stale_back": "返回", + "signout_title": "要退出登录并删除你的编辑吗?", + "signout_detail": "已编辑但未附加或保存的附件会在退出登录时删除。", + "signout_confirm": "退出登录", + "lock_note": "应用锁定期间,通过“编辑”打开的文件仍在其程序中保持打开,并且在这台电脑上仍可读取。解锁前无法打开新文件。" + }, "desktopReminders": { "generic_title": "提醒", "snooze": "{count} 分钟后再提醒", From 05e2e79ccfc5774afc5de077e67d78600998cd76 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:49:34 +0100 Subject: [PATCH 05/59] fix: keep the edited file offers clear of the toasts --- components/desktop/edited-files-host.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/desktop/edited-files-host.tsx b/components/desktop/edited-files-host.tsx index 68395f322..a2164c1f2 100644 --- a/components/desktop/edited-files-host.tsx +++ b/components/desktop/edited-files-host.tsx @@ -147,7 +147,8 @@ export function EditedFilesHost() {
{offers.map((session) => { const source = parseEditSource(session.source); From c0cf12c4319101cebbaf181d8f64e0faf73dbe3e Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:58:25 +0100 Subject: [PATCH 06/59] fix: show the edited file offers over the sidebar --- components/desktop/edited-files-host.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/desktop/edited-files-host.tsx b/components/desktop/edited-files-host.tsx index a2164c1f2..c4a41a6e4 100644 --- a/components/desktop/edited-files-host.tsx +++ b/components/desktop/edited-files-host.tsx @@ -147,8 +147,8 @@ export function EditedFilesHost() {
{offers.map((session) => { const source = parseEditSource(session.source); From 69313623e07cccbb65dca7e89a1c1e63c251763e Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:02:34 +0100 Subject: [PATCH 07/59] fix: keep the edited file offers clear of the account menu --- components/desktop/edited-files-host.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/desktop/edited-files-host.tsx b/components/desktop/edited-files-host.tsx index c4a41a6e4..4cc594eb0 100644 --- a/components/desktop/edited-files-host.tsx +++ b/components/desktop/edited-files-host.tsx @@ -147,8 +147,8 @@ export function EditedFilesHost() {
{offers.map((session) => { const source = parseEditSource(session.source); From e696fb16101f5a81066adb140127db6c093a6537 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:17:15 +0100 Subject: [PATCH 08/59] fix: ask before sending an older attachment also when the save was a moment ago --- .../__tests__/edited-files-host.test.tsx | 3 +- hooks/__tests__/use-composer-edits.test.tsx | 30 +++++++++++++++++-- hooks/use-composer-edits.ts | 14 ++++++--- .../__tests__/edit-attachments.test.ts | 3 +- lib/desktop/types.ts | 4 +++ 5 files changed, 46 insertions(+), 8 deletions(-) diff --git a/components/desktop/__tests__/edited-files-host.test.tsx b/components/desktop/__tests__/edited-files-host.test.tsx index 7e28bb6bf..19e0fd228 100644 --- a/components/desktop/__tests__/edited-files-host.test.tsx +++ b/components/desktop/__tests__/edited-files-host.test.tsx @@ -43,7 +43,7 @@ import { EditedFilesHost } from '../edited-files-host'; import { resetEditSessions, takeFilesForReply, useEditSessions } from '@/lib/desktop/edit-attachments'; const session = (over: Record = {}) => ({ - id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"mail","emailId":"e1","ownerAccountId":"owner"}', changed: true, version: 1, claimed: false, ...over, + id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"mail","emailId":"e1","ownerAccountId":"owner"}', changed: true, version: 1, hash: 'h', claimed: false, ...over, }); let bridge: { edit: Record>; dialogs: { confirm: ReturnType }; os: { notify: ReturnType } }; @@ -69,6 +69,7 @@ beforeEach(() => { open: vi.fn(), reopen: vi.fn(), list: vi.fn(async () => []), + settle: vi.fn(async () => []), read: vi.fn(async () => ({ ok: true, name: 'a.docx', type: 'x/y', data: new Uint8Array([1]), hash: 'h' })), taken: vi.fn(async () => {}), discard: vi.fn(async () => {}), diff --git a/hooks/__tests__/use-composer-edits.test.tsx b/hooks/__tests__/use-composer-edits.test.tsx index cce6879b2..0d2cd444e 100644 --- a/hooks/__tests__/use-composer-edits.test.tsx +++ b/hooks/__tests__/use-composer-edits.test.tsx @@ -28,6 +28,7 @@ function fakeBridge() { open: vi.fn(async () => ({ ok: true as const, id: 's1' })), reopen: vi.fn(async () => ({ ok: true as const, id: 's1' })), list: vi.fn(async () => []), + settle: vi.fn(async () => useEditSessions.getState().sessions), read: vi.fn(async () => ({ ok: true as const, name: 'a.docx', type: 'x/y', data: new Uint8Array([1, 2]), hash: 'h2' })), taken: vi.fn(async () => {}), discard: vi.fn(async () => {}), @@ -41,8 +42,8 @@ function fakeBridge() { let bridge: ReturnType; let confirm: ReturnType; -const session = (over: Partial<{ id: string; name: string; source: string; changed: boolean; claimed: boolean }> = {}) => ({ - id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"draft","draftId":"d1"}', changed: false, version: 0, claimed: true, ...over, +const session = (over: Partial<{ id: string; name: string; source: string; changed: boolean; claimed: boolean; hash: string }> = {}) => ({ + id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"draft","draftId":"d1"}', changed: false, version: 0, hash: 'current', claimed: true, ...over, }); interface Setup { @@ -217,6 +218,31 @@ describe('sending', () => { await expect(result.current.edits.confirmSend()).resolves.toBe(true); }); + it('sees a save from a moment ago, which the list has not heard of', async () => { + useEditSessions.setState({ sessions: [session()] }); + const { result } = setup({ start: [chip] }); + bridge.settle.mockResolvedValueOnce([session({ changed: true })] as never); + confirm.mockResolvedValueOnce(1); + await expect(result.current.edits.confirmSend()).resolves.toBe(false); + expect(confirm).toHaveBeenCalledTimes(1); + }); + + it('a chip holding the version on disk has nothing to ask about, even before main hears it went up', async () => { + const outcome = await readEditedFile({ id: 's1', account: 'acct' }); + if (!outcome.ok) throw new Error('refused'); + useEditSessions.setState({ sessions: [session({ changed: true, hash: outcome.hash })] }); + const { result } = setup({ start: [{ file: outcome.file, name: 'a.docx', type: 'x/y', editSessionId: 's1', uploading: true }] }); + expect(result.current.edits.hasUpdate(result.current.attachments[0])).toBe(false); + await expect(result.current.edits.confirmSend()).resolves.toBe(true); + expect(confirm).not.toHaveBeenCalled(); + }); + + it('a composer with no edited file asks main nothing', async () => { + const { result } = setup({ start: [{ name: 'a.docx', type: 'x/y', blobId: 'b' }] }); + await expect(result.current.edits.confirmSend()).resolves.toBe(true); + expect(bridge.settle).not.toHaveBeenCalled(); + }); + it('sent or discarded: an unchanged copy goes, edits nobody took stay and lose their draft', async () => { useEditSessions.setState({ sessions: [session({ id: 's1' }), session({ id: 's2', name: 'b.docx', changed: true })] }); const { result } = setup({ start: [chip, { name: 'b.docx', type: 'x/y', blobId: 'c', editSessionId: 's2' }] }); diff --git a/hooks/use-composer-edits.ts b/hooks/use-composer-edits.ts index 9350e96a1..5416dccf7 100644 --- a/hooks/use-composer-edits.ts +++ b/hooks/use-composer-edits.ts @@ -140,8 +140,11 @@ export function useComposerEdits({ attachments, se const sessionOf = useCallback((att: A) => (att.editSessionId ? sessions.find((s) => s.id === att.editSessionId) : undefined), [sessions]); - /** Whether this chip has saved edits to take. */ - const hasUpdate = useCallback((att: A) => sessionOf(att)?.changed === true, [sessionOf]); + /** Whether this chip has saved edits to take. Its own file on its way up isn't one. */ + const hasUpdate = useCallback((att: A) => { + const session = sessionOf(att); + return session?.changed === true && editFileInfo(att.file)?.hash !== session.hash; + }, [sessionOf]); const startEdit = useCallback(async (att: A) => { const key = att.editSessionId @@ -182,10 +185,13 @@ export function useComposerEdits({ attachments, se /** Edits on the way out in an older version: asks first. False: don't send. */ const confirmSend = useCallback(async (): Promise => { - const { attachments: list, sessions: all } = latest.current; + const { attachments: list } = latest.current; + if (!list.some((att) => att.editSessionId)) return true; + // Someone who saves and goes straight to Send is the case this is for: the watcher may not have seen it yet. + const all = await getEditBridge()?.settle() ?? latest.current.sessions; const stale = list.flatMap((att) => { const session = att.editSessionId ? all.find((s) => s.id === att.editSessionId) : undefined; - return session?.changed ? [session] : []; + return session?.changed && editFileInfo(att.file)?.hash !== session.hash ? [session] : []; }); const dialogs = getDesktopBridge()?.dialogs; if (stale.length === 0 || !dialogs) return true; diff --git a/lib/desktop/__tests__/edit-attachments.test.ts b/lib/desktop/__tests__/edit-attachments.test.ts index 5201f9bcc..101d381a6 100644 --- a/lib/desktop/__tests__/edit-attachments.test.ts +++ b/lib/desktop/__tests__/edit-attachments.test.ts @@ -36,6 +36,7 @@ function fakeBridge() { open: vi.fn(async () => ({ ok: true as const, id: 's1' })), reopen: vi.fn(async () => ({ ok: true as const, id: 's1' })), list: vi.fn(async () => []), + settle: vi.fn(async () => []), read: vi.fn(async () => ({ ok: true as const, name: 'a.docx', type: 'x/y', data: new Uint8Array([1, 2]), hash: 'h' })), taken: vi.fn(async () => {}), discard: vi.fn(async () => {}), @@ -220,7 +221,7 @@ describe('a file on its way to a reply', () => { describe('what main says', () => { it('follows the list once per page', async () => { - const session = { id: 's1', name: 'a', type: '', account: 'x', source: '', changed: true, version: 1, claimed: false }; + const session = { id: 's1', name: 'a', type: '', account: 'x', source: '', changed: true, version: 1, hash: 'h', claimed: false }; bridge.list.mockResolvedValue([session] as never); followEditSessions(); followEditSessions(); diff --git a/lib/desktop/types.ts b/lib/desktop/types.ts index 347d73d3d..78712cbf2 100644 --- a/lib/desktop/types.ts +++ b/lib/desktop/types.ts @@ -617,6 +617,8 @@ export interface DesktopEditSession { changed: boolean; /** Goes up with each save. */ version: number; + /** What the file holds now: a chip holding this version has nothing to update. */ + hash: string; /** A composer has it and offers the update itself. */ claimed: boolean; } @@ -657,6 +659,8 @@ export interface DesktopEditBridge { reopen: (ticket: string, id: string) => Promise; /** Empty while locked. */ list: () => Promise; + /** The list after looking at each file now, for a decision that can't wait for the watcher. */ + settle: () => Promise; read: (id: string) => Promise; /** This version is where it should be, so it's no longer a change. */ taken: (id: string, hash: string) => Promise; From c8c98e79d49364151b75d8473881278dfdd40ae9 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:09:12 +0100 Subject: [PATCH 09/59] feat: sign in to the desktop app in your browser, with your password manager MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The desktop login page gets "Sign in with your browser…" as its main button. On an instance it opens the instance's real login page in the system browser, with a PKCE challenge. The page checks the password or runs SSO, parks the sign-in under a one-time code, asks once, and sends the code to the app's loopback listener. This browser gets no session out of it, and the app's own page redeems the code, so SameSite=Strict is fine. Standalone runs the mail server's OAuth against the listener, with a page from main for a server with no OAuth at all. - `/api/auth/desktop-handoff/park` and `redeem`, and `sso/complete` parks tokens the same way for a loopback target - `auth.claim()`: the calls are taken once per document, in the first render, in `WindowControlsHost` - `BrowserSignIn` policy, default on, with its ADMX and samples - strings in all 30 languages, and the old button's are gone `runDesktopBrowserSignIn`'s tests changed because the code no longer goes through the callback page's address: it's redeemed where it arrives. --- app/(main)/[locale]/auth/callback/page.tsx | 20 +- .../login-page-desktop-policy.test.tsx | 143 +++++++- app/(main)/[locale]/login/page.tsx | 223 +++++++++--- app/api/auth/desktop-handoff/park/route.ts | 161 +++++++++ app/api/auth/desktop-handoff/redeem/route.ts | 104 ++++++ app/api/auth/desktop-oauth/route.ts | 62 ++-- app/api/auth/handoff/redeem/route.ts | 5 + app/api/auth/sso/complete/route.ts | 23 ++ app/api/auth/sso/start/route.ts | 9 +- components/auth/mobile-handoff-consent.tsx | 17 +- components/layout/window-controls-host.tsx | 4 + desktop-policies/Bulwark.admx | 12 + desktop-policies/de-DE/Bulwark.adml | 2 + desktop-policies/en-US/Bulwark.adml | 2 + .../org.bulwarkmail.desktop.mobileconfig | 2 + desktop-policies/policies.json | 1 + lib/__tests__/desktop-handoff-routes.test.ts | 322 ++++++++++++++++++ lib/__tests__/sso-complete-route.test.ts | 43 +++ lib/__tests__/sso-start-route.test.ts | 33 ++ lib/auth/handoff-store.ts | 32 +- lib/auth/mobile-handoff-client.ts | 37 ++ lib/auth/mobile-handoff.ts | 20 ++ lib/desktop/__tests__/browser-side.test.ts | 225 +++++++++--- .../__tests__/desktop-oauth-route.test.ts | 119 +++++++ lib/desktop/__tests__/policy-schema.test.ts | 2 +- lib/desktop/blocked-routes.ts | 2 +- lib/desktop/browser-sign-in.ts | 199 ++++++++--- lib/desktop/languages.ts | 12 + lib/desktop/policy-schema.ts | 14 + lib/desktop/types.ts | 44 ++- lib/oauth/discovery.ts | 1 + locales/ar/common.json | 31 +- locales/ca/common.json | 31 +- locales/cs/common.json | 31 +- locales/da/common.json | 31 +- locales/de/common.json | 31 +- locales/en/common.json | 31 +- locales/es/common.json | 31 +- locales/et/common.json | 31 +- locales/fa/common.json | 31 +- locales/fr/common.json | 31 +- locales/he/common.json | 31 +- locales/hu/common.json | 31 +- locales/it/common.json | 31 +- locales/ja/common.json | 31 +- locales/ko/common.json | 31 +- locales/lv/common.json | 31 +- locales/mn/common.json | 31 +- locales/nb/common.json | 31 +- locales/nl/common.json | 31 +- locales/pl/common.json | 31 +- locales/pt/common.json | 31 +- locales/ro/common.json | 31 +- locales/ru/common.json | 31 +- locales/sk/common.json | 31 +- locales/th/common.json | 31 +- locales/tr/common.json | 31 +- locales/uk/common.json | 31 +- locales/vi/common.json | 31 +- locales/zh-TW/common.json | 31 +- locales/zh/common.json | 31 +- scripts/lite/lib.mjs | 3 + stores/auth-store.ts | 219 +++++++----- 63 files changed, 2656 insertions(+), 391 deletions(-) create mode 100644 app/api/auth/desktop-handoff/park/route.ts create mode 100644 app/api/auth/desktop-handoff/redeem/route.ts create mode 100644 lib/__tests__/desktop-handoff-routes.test.ts create mode 100644 lib/desktop/__tests__/desktop-oauth-route.test.ts diff --git a/app/(main)/[locale]/auth/callback/page.tsx b/app/(main)/[locale]/auth/callback/page.tsx index e3862393a..f8a0d4b6c 100644 --- a/app/(main)/[locale]/auth/callback/page.tsx +++ b/app/(main)/[locale]/auth/callback/page.tsx @@ -1,8 +1,6 @@ "use client"; import { Suspense, useEffect, useRef, useState } from "react"; -import { IS_DESKTOP_BUILD } from "@/lib/desktop/flag"; -import { DESKTOP_CLIENT_ID_KEY, DESKTOP_REDIRECT_URI_KEY } from "@/lib/desktop/browser-sign-in"; import { useRouter, useSearchParams } from "next/navigation"; import { useTranslations } from "next-intl"; import { useAuthStore } from "@/stores/auth-store"; @@ -12,7 +10,7 @@ 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, mobileHandoffTarget } from "@/lib/auth/mobile-handoff"; +import { buildMobileHandoffUrl, desktopHandoffTarget, handoffTarget } from "@/lib/auth/mobile-handoff"; import { confirmMobileHandoffCodeUrl } from "@/lib/auth/mobile-handoff-client"; import { MobileHandoffConsent } from "@/components/auth/mobile-handoff-consent"; import { MailSkeleton } from "@/components/boot-skeleton/mail-skeleton"; @@ -32,6 +30,7 @@ function OAuthCallbackInner() { url: string | null; resolveUrl?: () => Promise; username: string; + desktop?: boolean; } | null>(null); // 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 @@ -118,12 +117,9 @@ function OAuthCallbackInner() { const prefix = getPathPrefix(params.locale as string); // Lite on Stalwart registers one locale-free URI (lib/auth/lite-oauth.ts); // the entry document brought us here from it. - // The desktop app's browser sign-in redirected to its loopback listener - // (lib/desktop/browser-sign-in.ts), which this page's origin can't tell. - const desktopRedirectUri = IS_DESKTOP_BUILD ? sessionStorage.getItem(DESKTOP_REDIRECT_URI_KEY) : null; - const redirectUri = desktopRedirectUri ?? (LITE_OAUTH_AVAILABLE + const redirectUri = LITE_OAUTH_AVAILABLE ? getLiteOAuthRedirectUri() - : `${window.location.origin}${prefix}/${params.locale}/auth/callback`); + : `${window.location.origin}${prefix}/${params.locale}/auth/callback`; loginWithOAuth(serverUrl, code, codeVerifier, redirectUri, serverId) .then((success) => { @@ -133,10 +129,6 @@ function OAuthCallbackInner() { sessionStorage.removeItem("oauth_server_url"); sessionStorage.removeItem("oauth_server_id"); sessionStorage.removeItem("oauth_add_account_mode"); - if (IS_DESKTOP_BUILD) { - sessionStorage.removeItem(DESKTOP_REDIRECT_URI_KEY); - sessionStorage.removeItem(DESKTOP_CLIENT_ID_KEY); - } let redirectTo = `${prefix}/${params.locale}`; try { const saved = sessionStorage.getItem('redirect_after_login'); @@ -160,7 +152,7 @@ function OAuthCallbackInner() { let mobileRedirectUri = ""; let mobileState: string | null = null; try { - mobileRedirectUri = mobileHandoffTarget(sessionStorage.getItem("mobile_redirect_uri")); + mobileRedirectUri = handoffTarget(sessionStorage.getItem("mobile_redirect_uri")); mobileState = sessionStorage.getItem("mobile_state"); } catch { /* sessionStorage may be unavailable */ } @@ -200,6 +192,7 @@ function OAuthCallbackInner() { code: handoffCode, state: handoffState, }), + desktop: Boolean(desktopHandoffTarget(mobileRedirectUri)), username: typeof data.server_url === "string" ? data.server_url : "", }); return; @@ -275,6 +268,7 @@ function OAuthCallbackInner() { url={pendingHandoff.url} resolveUrl={pendingHandoff.resolveUrl ?? null} username={pendingHandoff.username} + desktop={pendingHandoff.desktop} onError={() => { setPendingHandoff(null); setError("token_exchange_failed"); diff --git a/app/(main)/[locale]/login/__tests__/login-page-desktop-policy.test.tsx b/app/(main)/[locale]/login/__tests__/login-page-desktop-policy.test.tsx index de689d054..8af10cef2 100644 --- a/app/(main)/[locale]/login/__tests__/login-page-desktop-policy.test.tsx +++ b/app/(main)/[locale]/login/__tests__/login-page-desktop-policy.test.tsx @@ -6,9 +6,11 @@ import { EMPTY_POLICY_LAYERS, resolvePolicies } from '@/lib/desktop/policy-schem // The device's OS policy on the two ways into SSO: nothing starts towards a refused server. +const params = vi.hoisted(() => ({ value: null as URLSearchParams | null })); + vi.mock('next/navigation', () => ({ useParams: () => ({ locale: 'en' }), - useSearchParams: () => new URLSearchParams(), + useSearchParams: () => params.value ?? new URLSearchParams(), useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }), usePathname: () => '/login', })); @@ -56,6 +58,7 @@ let fetched: string[]; beforeEach(() => { configOverrides.value = {}; + params.value = null; fetched = []; sessionStorage.clear(); vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => { @@ -110,3 +113,141 @@ describe('automatic SSO', () => { await waitFor(() => expect(startedSso()).toBe(true), { timeout: 10000 }); }, 30_000); }); + +describe('sign-in with the browser, in the app', () => { + const REDIRECT = 'http://127.0.0.1:51234/bulwark-desktop/callback'; + + function appBridge(options: { servers?: string[]; browserSignIn?: boolean; complete?: () => unknown } = {}) { + const forced: Record = {}; + if (options.servers) forced.AllowedJmapServers = options.servers; + if (options.browserSignIn !== undefined) forced.BrowserSignIn = options.browserSignIn; + const snapshot = resolvePolicies({ ...EMPTY_POLICY_LAYERS, forcedMachine: forced }); + const controls = { + begin: vi.fn(async () => ({ ok: true, flowId: 'f1', redirectUri: REDIRECT, state: 'main-state' })), + complete: vi.fn(async () => (options.complete ? options.complete() : { ok: false, error: 'cancelled' })), + cancel: vi.fn(), + }; + window.bulwarkDesktop = { + version: 1, + platform: 'win32', + mode: 'instance', + auth: { claim: () => controls }, + policy: { get: () => snapshot, onChange: () => () => {} }, + } as unknown as BulwarkDesktopBridge; + return controls; + } + + const browserButton = () => screen.findByTestId('desktop-browser-sign-in', {}, { timeout: 10000 }); + + it('stays the other choice next to the form', async () => { + configOverrides.value = { oauthEnabled: false, oauthOnly: false }; + appBridge(); + render(); + expect((await browserButton()).textContent).toContain('button'); + expect(document.getElementById('username')).not.toBeNull(); + expect(document.getElementById('password')).not.toBeNull(); + }, 30_000); + + it('is the main way in on an OAuth-only instance, with no form', async () => { + appBridge(); + render(); + await browserButton(); + expect(document.getElementById('password')).toBeNull(); + expect(await ssoButton()).toBeInTheDocument(); + }, 30_000); + + it('is gone when a policy says so, and the form stays', async () => { + configOverrides.value = { oauthEnabled: false, oauthOnly: false }; + appBridge({ browserSignIn: false }); + render(); + 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(); + await waitFor(() => expect(document.getElementById('password')).not.toBeNull(), { timeout: 10000 }); + expect(screen.queryByTestId('desktop-browser-sign-in')).toBeNull(); + }, 30_000); + + it('starts nothing towards a server off the list, and says why', async () => { + const controls = appBridge({ servers: ['https://other.example.org'] }); + render(); + fireEvent.click(await browserButton()); + expect(await screen.findByText('server_refused')).toBeInTheDocument(); + expect(controls.begin).not.toHaveBeenCalled(); + }, 30_000); + + it('a flow that ran out says so, and the button comes back', async () => { + const controls = appBridge({ complete: () => ({ ok: false, error: 'timeout' }) }); + render(); + fireEvent.click(await browserButton()); + expect(await screen.findByText('timed_out')).toBeInTheDocument(); + expect(controls.complete).toHaveBeenCalledOnce(); + expect(await browserButton()).not.toBeDisabled(); + }, 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) => { + const url = String(input); + 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'] }); + return new Response(JSON.stringify({ error: 'blocked_by_policy' }), { status: 403 }); + } + return new Response('{}', { status: 200 }); + })); + render(); + fireEvent.click(await browserButton()); + expect(await screen.findByText('server_refused')).toBeInTheDocument(); + expect(fetched.some((url) => url.includes('/api/auth/desktop-handoff/redeem'))).toBe(true); + }, 30_000); +}); + +describe('the page the app opens in the browser', () => { + const CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'; + const search = (entries: Record) => new URLSearchParams(entries); + + it('parks the password and leaves this browser signed out, after asking', 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', mobile_code_challenge: CHALLENGE }); + const bodies: Record[] = []; + 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/park')) { + bodies.push(JSON.parse(String(init?.body))); + return new Response(JSON.stringify({ code: 'a'.repeat(64) }), { status: 200 }); + } + return new Response('{}', { status: 200 }); + })); + render(); + 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' } }); + fireEvent.submit(document.getElementById('password')!.closest('form')!); + expect(await screen.findByText('consent_title')).toBeInTheDocument(); + expect(bodies[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('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' }); + render(); + await waitFor(() => expect(document.getElementById('password')).not.toBeNull(), { timeout: 10000 }); + expect(screen.queryByTestId('desktop-handoff-banner')).toBeNull(); + }, 30_000); + + it('ignores a target that is not this computer', async () => { + configOverrides.value = { oauthEnabled: false, oauthOnly: false }; + params.value = search({ mobile_redirect_uri: 'http://evil.example:51234/bulwark-desktop/callback', mobile_state: 's', mobile_code_challenge: CHALLENGE }); + render(); + await waitFor(() => expect(document.getElementById('password')).not.toBeNull(), { timeout: 10000 }); + expect(screen.queryByTestId('desktop-handoff-banner')).toBeNull(); + }, 30_000); +}); diff --git a/app/(main)/[locale]/login/page.tsx b/app/(main)/[locale]/login/page.tsx index d04544e1e..97c136bb3 100644 --- a/app/(main)/[locale]/login/page.tsx +++ b/app/(main)/[locale]/login/page.tsx @@ -6,7 +6,7 @@ import { IS_DESKTOP_BUILD } from "@/lib/desktop/flag"; import { forgetDesktopServer, getDesktopBridge } from "@/lib/desktop/bridge"; import { customServerAllowedByDesktopPolicy, jmapServerAllowedByDesktopPolicy, useDesktopPolicy } from "@/lib/desktop/policy"; import { accountRefusedByDesktopPolicy } from "@/lib/desktop/refused-accounts"; -import { browserSignInAvailable, runDesktopBrowserSignIn } from "@/lib/desktop/browser-sign-in"; +import { browserSignInAvailable, cancelBrowserSignIn, runDesktopBrowserSignIn, runInstanceBrowserSignIn, type DesktopBrowserSignInOutcome } from "@/lib/desktop/browser-sign-in"; import { useRouter } from "@/i18n/navigation"; import { useParams, useSearchParams } from "next/navigation"; import { useTranslations } from "next-intl"; @@ -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, mobileCodeChallenge, mobileHandoffTarget, signedInLoginAction } from "@/lib/auth/mobile-handoff"; -import { requestMobileHandoffCodeUrl } from "@/lib/auth/mobile-handoff-client"; +import { buildMobileHandoffUrl, desktopHandoffTarget, mobileCodeChallenge, mobileHandoffTarget, signedInLoginAction } from "@/lib/auth/mobile-handoff"; +import { confirmMobileHandoffCodeUrl, 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"; @@ -194,11 +194,14 @@ function LoginPageContent() { const router = useRouter(); const t = useTranslations("login"); const tDesktop = useTranslations("desktop_sign_in"); + const tBrowser = useTranslations("desktop_browser_sign_in"); const tDesktopPolicy = useTranslations("desktop_policy"); const desktopPolicy = useDesktopPolicy(); // Only the desktop build sets these; a browser never shows them. const [desktopNotice, setDesktopNotice] = useState(null); const [desktopWaiting, setDesktopWaiting] = useState(false); + // Leaving the page ends a sign-in it's waiting for: the verifier goes with it. + useEffect(() => () => cancelBrowserSignIn(), []); const tSessionLimits = useTranslations("session_limits"); const tOffline = useTranslations("offline"); const tOfflineWipe = useTranslations("offlineWipe"); @@ -230,9 +233,15 @@ function LoginPageContent() { // server to park the sign-in on and keeps handing over in the fragment. const rawMobileCodeChallenge = IS_LITE ? "" : searchParams.get("mobile_code_challenge") ?? ""; const mobileChallenge = mobileCodeChallenge(rawMobileCodeChallenge); - const mobileRedirectUri = rawMobileCodeChallenge && !mobileChallenge + // 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 + ? desktopHandoffTarget(searchParams.get("mobile_redirect_uri")) + : ""; + const isDesktopHandoff = Boolean(desktopTarget); + const mobileRedirectUri = desktopTarget || (rawMobileCodeChallenge && !mobileChallenge ? "" - : mobileHandoffTarget(searchParams.get("mobile_redirect_uri")); + : mobileHandoffTarget(searchParams.get("mobile_redirect_uri"))); const mobileState = mobileRedirectUri ? rawMobileState : ""; const isMobileHandoff = Boolean(mobileRedirectUri); const [pendingHandoff, setPendingHandoff] = useState<{ @@ -392,7 +401,8 @@ function LoginPageContent() { const canRememberSession = rememberMeEnabled && (!IS_LITE || liteTokenLoginSupported !== false); // Sign-ins are remembered without asking unless the admin offers the box // (LOGIN_SHOW_REMEMBER_ME). - const showRememberMe = canRememberSession && loginShowRememberMe; + // Not in the browser the desktop app opened: nothing stays in this browser to remember. + const showRememberMe = canRememberSession && loginShowRememberMe && !isDesktopHandoff; const persistSession = canRememberSession && (!loginShowRememberMe || rememberMe); // A provider sign-in follows the box whenever it is shown, the automatic // one included (it starts unticked), and is remembered otherwise. Lite @@ -679,7 +689,8 @@ function LoginPageContent() { locale: params.locale, server_id: selectedServer?.id, remember: persistProviderSession, - ...(freshLoginRequired() ? { fresh_login: true } : {}), + // In the browser the desktop app opened, its word counts: the flag is in the app. + ...(freshLoginRequired() || (isDesktopHandoff && searchParams.get("fresh_login") === "1") ? { fresh_login: true } : {}), ...(isMobileHandoff ? { mobile_redirect_uri: mobileRedirectUri, @@ -692,6 +703,8 @@ function LoginPageContent() { if (!res.ok) { setOauthLoading(false); + // The app is waiting on this tab, so it can't just stay quiet here. + if (isDesktopHandoff) setHandoffError("server_error"); return; } @@ -713,7 +726,7 @@ function LoginPageContent() { } catch { setOauthLoading(false); } - }, [params.locale, selectedServer?.id, serverUrl, desktopPolicy, tDesktopPolicy, persistProviderSession, isMobileHandoff, mobileRedirectUri, mobileState, mobileChallenge]); + }, [params.locale, selectedServer?.id, serverUrl, desktopPolicy, tDesktopPolicy, persistProviderSession, isMobileHandoff, isDesktopHandoff, searchParams, mobileRedirectUri, mobileState, mobileChallenge]); useEffect(() => { // After signing out, show the login page rather than signing straight @@ -1041,38 +1054,88 @@ function LoginPageContent() { window.location.href = authUrl.toString(); }; - /** The desktop build: the server's own sign-in page in the system browser. */ - // Spelled out, not IS_DESKTOP_BUILD: only this form keeps the route out of other - // builds' bundles, which Lite's check on API strings relies on. - const handleDesktopBrowserSignIn = async () => { + /** What the user sees when a browser sign-in ends without one. Cancelling says nothing. */ + const showBrowserSignInOutcome = (outcome: DesktopBrowserSignInOutcome) => { + setDesktopWaiting(false); + if (outcome.kind === "policy") setDesktopPolicyNotice(tDesktopPolicy("server_refused")); + 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")); + else if (outcome.kind === "no_browser") setDesktopNotice(tBrowser("no_browser")); + else if (outcome.kind === "failed") setDesktopNotice(tBrowser("failed")); + }; + + /** The server's or the instance's own sign-in page in the system browser. */ + const handleBrowserSignIn = async () => { + setDesktopNotice(null); + setDesktopPolicyNotice(null); + // Spelled out, not IS_DESKTOP_BUILD: only this form keeps the route out of other + // builds' bundles, which Lite's check on API strings relies on. if (process.env.NEXT_PUBLIC_BULWARK_DESKTOP === '1') { const target = jmapEndpoint.trim(); if (!target) { setDesktopNotice(tDesktop("server_needed")); return; } - setDesktopNotice(null); + if (!jmapServerAllowedByDesktopPolicy(target, desktopPolicy)) { + setDesktopPolicyNotice(tDesktopPolicy("server_refused")); + return; + } setDesktopWaiting(true); - const prefix = getPathPrefix(params.locale as string); const outcome = await runDesktopBrowserSignIn({ serverUrl: target, - callbackPath: `${prefix}/${params.locale}/auth/callback`, slot: useAccountStore.getState().getNextCookieSlot(), remember: persistProviderSession, addAccount: isAddAccountMode, + fresh: freshLoginRequired(), + redeem: (server, code, verifier, redirectUri) => useAuthStore.getState().loginWithOAuth(server, code, verifier, redirectUri), + tryPassword: async ({ username, password, totp }) => { + if (await useAuthStore.getState().login(target, username, password, totp, persistSession)) { + if (!rememberMeEnabled || persistSession) saveUsername(username); + return { ok: true }; + } + const failed = useAuthStore.getState().error; + return { ok: false, error: failed === "invalid_credentials" || failed === "totp_required" ? failed : "other" }; + }, }); - if (outcome.kind === "callback") { - window.location.href = outcome.callbackUrl; + if (outcome.kind === "signed-in") { + setDesktopWaiting(false); + router.push('/'); return; } - setDesktopWaiting(false); forgetDesktopServer(target, "failed"); - if (outcome.kind === "unavailable") setDesktopNotice(tDesktop("browser_unavailable")); - else if (outcome.kind === "declined") setDesktopNotice(tDesktop("server_declined")); - else if (outcome.kind === "failed") setDesktopNotice(tDesktop("browser_failed")); + showBrowserSignInOutcome(outcome); + return; } + // A server the device's OS policy refuses, where it's known up front. With a list of + // servers the browser picks, and the redeem below is what checks. + if (!hasServerList && serverUrl && !jmapServerAllowedByDesktopPolicy(serverUrl, desktopPolicy)) { + setDesktopPolicyNotice(tDesktopPolicy("server_refused")); + return; + } + setDesktopWaiting(true); + const outcome = await runInstanceBrowserSignIn({ + base: `${window.location.origin}${getPathPrefix(params.locale as string)}`, + locale: params.locale as string, + fresh: freshLoginRequired(), + }); + if (outcome.kind !== "code") { + showBrowserSignInOutcome(outcome); + return; + } + const redeemed = await useAuthStore.getState().loginWithDesktopHandoff(outcome.code, outcome.verifier, { + remember: persistProviderSession, + rememberPassword: persistSession, + allowedServers: desktopPolicy.AllowedJmapServers.value, + }); + setDesktopWaiting(false); + if (redeemed === "ok") router.push('/'); + else if (redeemed === "blocked") setDesktopPolicyNotice(tDesktopPolicy("server_refused")); + else setDesktopNotice(tBrowser("failed")); }; + const browserSignInShown = browserSignInAvailable(); + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); @@ -1080,6 +1143,38 @@ 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. + 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) { + useAuthStore.setState({ + isLoading: false, + error: parked.error === "invalid_credentials" || parked.error === "totp_required" ? parked.error : "server_error", + }); + return; + } + useAuthStore.setState({ isLoading: false }); + const { code } = parked; + setPendingHandoff({ + url: null, + resolveUrl: () => confirmMobileHandoffCodeUrl({ target: mobileRedirectUri, code, state: mobileState }), + username: formData.username, + }); + return; + } // The device's OS policy, also on an instance: nothing is sent to a server it refuses. setDesktopPolicyNotice(null); if (!jmapServerAllowedByDesktopPolicy(effectiveServerUrl, desktopPolicy)) { @@ -1193,6 +1288,53 @@ function LoginPageContent() { // has to pick which one SSO targets before the button starts the flow, since // the selection drives OAuth discovery and the server_id sent to the callback // (issue #799). + // In the app: the main way in, above the form, which stays as the other choice. + const browserSignInOption = browserSignInShown && ( +
+ + {desktopWaiting && ( +

+ {tBrowser("waiting_hint")}{" "} + +

+ )} +
+
+ +
+
+ {tBrowser("or_here")} +
+
+
+ ); + + // The desktop app's sign-in, in the browser: says what this page is for. + const desktopHandoffBanner = isDesktopHandoff && ( +

+ {tBrowser("handoff_banner")} +

+ ); + const desktopPolicyAlert = desktopPolicyNotice && (

{desktopPolicyNotice} @@ -1426,9 +1568,11 @@ function LoginPageContent() { url={pendingHandoff?.url ?? null} resolveUrl={pendingHandoff?.resolveUrl ?? null} username={pendingHandoff?.username ?? ""} + desktop={isDesktopHandoff} onCancel={() => { setPendingHandoff(null); - router.push('/'); + // The app's sign-in stays open here, to try again or to leave. + if (!isDesktopHandoff) router.push('/'); }} onError={() => { setPendingHandoff(null); @@ -1598,6 +1742,8 @@ function LoginPageContent() { )} + {desktopHandoffBanner} + {/* Dev Mode: One-click login */} {devMode ? (

@@ -1629,10 +1775,14 @@ function LoginPageContent() { {serverPicker} {desktopPolicyAlert} {oauthMetadata && showRememberMe && rememberMeBox} + {browserSignInOption} {oauthMetadata ? (
) : ( /* Login Form */ @@ -1690,6 +1845,8 @@ function LoginPageContent() { )} + {browserSignInOption} + {/* Username field. The access token names the account, so token sign-in has none. */}
@@ -1897,7 +2054,10 @@ function LoginPageContent() { - )} {desktopPolicyAlert} - {IS_DESKTOP_BUILD && desktopNotice && ( + {desktopNotice && (

{desktopNotice}

diff --git a/app/api/auth/desktop-handoff/park/route.ts b/app/api/auth/desktop-handoff/park/route.ts new file mode 100644 index 000000000..30245042b --- /dev/null +++ b/app/api/auth/desktop-handoff/park/route.ts @@ -0,0 +1,161 @@ +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 { stalwartPasswordLogin } from '@/lib/auth/stalwart-password-login'; +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 { 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. +// +// 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. + +const NO_STORE = { 'Cache-Control': 'no-store' }; + +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 }); +} + +export async function POST(request: NextRequest) { + if (IS_DESKTOP_BUILD) return answer('Not found', 404); + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; + try { + const body = await request.json().catch(() => null); + 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 + || state.length > 512 + || !bounded(body?.server_url, 2048) + || !bounded(body?.username, 512) + || !bounded(body?.password, 4096) + || (totp !== undefined && totp.length > 16) + ) { + return answer('invalid_request', 400); + } + + await configManager.ensureLoaded(); + if (configManager.get('oauthEnabled', false) && configManager.get('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('jmapServerUrl', '') || process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL || ''; + const list = parseJmapServers(configManager.get('jmapServers', [])); + const allowCustom = configManager.get('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 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) } }, + ); + } + + let parked: Parameters[0]; + if (totp) { + const configuredClientId = + entry?.oauth?.clientId || configManager.get('oauthClientId', '') || process.env.OAUTH_CLIENT_ID; + const clientSecret = + entry?.oauth?.clientSecret + || configManager.get('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); + } + 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, + signed_in_at: Date.now(), + }; + } else { + try { + await verifyJmapAuth(upstream, `Basic ${Buffer.from(`${body.username}:${body.password}`).toString('base64')}`, { trusted, clientIp }); + await refund(); + } 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); + } + parked = { flow: 'desktop-password', server_url: resolved, server_id: entry?.id ?? null, 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 }); + logger.info('Desktop hand-off parked', { flow: parked.flow }); + return NextResponse.json({ code }, { headers: NO_STORE }); + } catch (error) { + if (isStoreUnavailable(error)) return storeUnavailableResponse(NO_STORE); + logger.error('Desktop hand-off park error', { error: error instanceof Error ? error.message : 'Unknown error' }); + return answer('Internal server error', 500); + } +} diff --git a/app/api/auth/desktop-handoff/redeem/route.ts b/app/api/auth/desktop-handoff/redeem/route.ts new file mode 100644 index 000000000..7875f65bb --- /dev/null +++ b/app/api/auth/desktop-handoff/redeem/route.ts @@ -0,0 +1,104 @@ +import { NextRequest, NextResponse } from 'next/server'; +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 { isHandoffCode, isHandoffCodeVerifier, redeemHandoff, reserveHandoffRedeem } from '@/lib/auth/handoff-store'; +import { writeSignInStamp } from '@/lib/auth/session-age'; +import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable'; +import type { BudgetRefund } from '@/lib/auth/verify-budget'; +import { IS_DESKTOP_BUILD } from '@/lib/desktop/flag'; +import { jmapServerAllowed } from '@/lib/desktop/policy-schema'; +import { getCookieOptions, getSignInCookieOptions } from '@/lib/oauth/cookie-config'; +import { storeIdToken } from '@/lib/oauth/end-session'; +import { refreshTokenCookieName, refreshTokenServerCookieName } from '@/lib/oauth/tokens'; +import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; + +// The desktop app's side of "Sign in with your browser", on an instance. The app's own +// page posts the code its loopback listener received, with the PKCE verifier behind the +// 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. + +const NO_STORE = { 'Cache-Control': 'no-store' }; + +function answer(error: string, status: number, extra: Record = {}) { + return NextResponse.json({ error, ...extra }, { status, headers: NO_STORE }); +} + +export async function POST(request: NextRequest) { + if (IS_DESKTOP_BUILD) return answer('Not found', 404); + const crossOrigin = rejectCrossOriginRequest(request); + if (crossOrigin) return crossOrigin; + let refund: BudgetRefund | null = null; + try { + refund = await reserveHandoffRedeem(loginClientAddress(request)); + if (!refund) return answer('too_many_requests', 429); + + const body = await request.json().catch(() => null); + const code = body?.code; + const verifier = body?.code_verifier; + if (!isHandoffCode(code)) return answer('invalid_request', 400); + if (!isHandoffCodeVerifier(verifier)) { + await redeemHandoff(code, ''); + return answer('invalid_verifier', 400); + } + const slot = typeof body?.slot === 'number' && Number.isInteger(body.slot) && body.slot >= 0 && body.slot < MAX_ACCOUNT_SLOTS ? body.slot : 0; + const remember = body?.remember !== false; + const allowedServers = Array.isArray(body?.allowed_servers) ? (body.allowed_servers as string[]) : null; + + const result = await redeemHandoff(code, verifier); + if (!result.ok) { + logger.warn('Desktop hand-off redeem refused', { reason: result.reason }); + return answer(result.reason === 'verifier_mismatch' ? 'invalid_verifier' : `${result.reason}_code`, 400); + } + 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' }); + + await refund(); + logger.info('Desktop hand-off redeemed', { flow: parked.flow }); + + if (parked.flow === 'desktop-password') { + // Down the app's normal login path, from the page, like a typed password. + return NextResponse.json( + { flow: 'password', server_url: parked.server_url, username: parked.username, password: parked.password }, + { headers: NO_STORE }, + ); + } + + const cookieStore = await cookies(); + if (parked.refresh_token) { + const options = getSignInCookieOptions(remember); + cookieStore.set(refreshTokenCookieName(slot), parked.refresh_token, options); + writeSignInStamp(cookieStore, slot, { signedInAt: parked.signed_in_at, refreshToken: parked.refresh_token }, options); + } + const serverCookie = refreshTokenServerCookieName(slot); + if (parked.server_id) cookieStore.set(serverCookie, parked.server_id, getCookieOptions()); + else cookieStore.delete(serverCookie); + storeIdToken(cookieStore, slot, parked.id_token, request.nextUrl.basePath, [parked.refresh_token, parked.server_id], remember); + + return NextResponse.json( + { + flow: 'tokens', + server_url: parked.server_url, + access_token: parked.access_token, + expires_in: parked.expires_in, + signed_in_at: parked.signed_in_at, + remember, + }, + { headers: NO_STORE }, + ); + } catch (error) { + if (isStoreUnavailable(error)) { + if (refund) await refund(); + return storeUnavailableResponse(NO_STORE); + } + logger.error('Desktop hand-off redeem error', { error: error instanceof Error ? error.message : 'Unknown error' }); + return answer('Internal server error', 500); + } +} diff --git a/app/api/auth/desktop-oauth/route.ts b/app/api/auth/desktop-oauth/route.ts index c6fa99102..dd7ee0383 100644 --- a/app/api/auth/desktop-oauth/route.ts +++ b/app/api/auth/desktop-oauth/route.ts @@ -10,6 +10,8 @@ import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; /** The client id on a server that won't register one: 0.16 accepts any id. */ const FALLBACK_CLIENT_ID = 'bulwark-desktop'; const REGISTERED_REDIRECT = 'http://127.0.0.1/bulwark-desktop/callback'; +/** Only tried when the server says no to loopback. Neither Stalwart line takes this one. */ +const SCHEME_REDIRECT = 'bulwark://sign-in/callback'; const REGISTER_TIMEOUT_MS = 5000; function isLoopbackRedirect(value: unknown): boolean { @@ -27,29 +29,42 @@ function isLoopbackRedirect(value: unknown): boolean { * ids are stateless, so the same metadata gives the same id and nothing is * stored. It accepts a loopback redirect and ignores the port when matching. */ -async function registerClient(base: string, scope: string): Promise { +async function postRegistration(endpoint: string, redirectUri: string, scope: string): Promise { + return fetch(endpoint, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + client_name: 'Bulwark', + redirect_uris: [redirectUri], + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + scope, + }), + redirect: 'error', + signal: AbortSignal.timeout(REGISTER_TIMEOUT_MS), + }); +} + +async function clientIdOf(response: Response): Promise { + const body = (await response.json().catch(() => null)) as { client_id?: unknown } | null; + return typeof body?.client_id === 'string' && body.client_id ? body.client_id : null; +} + +async function registerClient(endpoint: string, scope: string): Promise<{ clientId: string; useScheme: boolean }> { try { - const response = await fetch(`${base}/auth/register`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - client_name: 'Bulwark', - redirect_uris: [REGISTERED_REDIRECT], - token_endpoint_auth_method: 'none', - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - scope, - }), - redirect: 'error', - signal: AbortSignal.timeout(REGISTER_TIMEOUT_MS), - }); - if (!response.ok) return FALLBACK_CLIENT_ID; - const body = (await response.json()) as { client_id?: unknown }; - return typeof body.client_id === 'string' && body.client_id ? body.client_id : FALLBACK_CLIENT_ID; + const response = await postRegistration(endpoint, REGISTERED_REDIRECT, scope); + if (response.ok) return { clientId: (await clientIdOf(response)) ?? FALLBACK_CLIENT_ID, useScheme: false }; + const refusal = (await response.json().catch(() => null)) as { error?: unknown } | null; + if (refusal?.error === 'invalid_redirect_uri') { + const second = await postRegistration(endpoint, SCHEME_REDIRECT, scope); + const clientId = second.ok ? await clientIdOf(second) : null; + if (clientId) return { clientId, useScheme: true }; + } } catch (error) { logger.warn('Desktop OAuth: client registration failed', { error: error instanceof Error ? error.message : String(error) }); - return FALLBACK_CLIENT_ID; } + return { clientId: FALLBACK_CLIENT_ID, useScheme: false }; } /** @@ -74,10 +89,17 @@ export async function POST(request: NextRequest) { if (!metadata) return NextResponse.json({ error: 'no_oauth' }, { status: 404 }); const scope = withProviderDataScopes(DEFAULT_OAUTH_SCOPES, metadata.scopes_supported); + // RFC 8414 says where. Without it, Stalwart's path: 0.16's documents don't always name it. + const validate = getDiscoveryValidator(upstream.serverUrl); + const named = metadata.registration_endpoint; + const endpoint = named && (!validate || (await validate(named))) ? named : `${upstream.serverUrl}/auth/register`; + const { clientId, useScheme } = await registerClient(endpoint, scope); return NextResponse.json({ authorization_endpoint: metadata.authorization_endpoint, - client_id: await registerClient(upstream.serverUrl, scope), + client_id: clientId, scope, + issuer: metadata.issuer, + ...(useScheme ? { use_scheme: true } : {}), }); } catch (error) { logger.error('Desktop OAuth discovery failed', { error: error instanceof Error ? error.message : 'Unknown error' }); diff --git a/app/api/auth/handoff/redeem/route.ts b/app/api/auth/handoff/redeem/route.ts index eb18c4967..d77935166 100644 --- a/app/api/auth/handoff/redeem/route.ts +++ b/app/api/auth/handoff/redeem/route.ts @@ -53,6 +53,11 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error }, { status: 400, headers: NO_STORE }); } + // The desktop app's sign-in has its own redeem, which writes cookies from these fields. + if (result.bundle.flow === 'desktop-password' || result.bundle.flow === 'desktop-tokens') { + return NextResponse.json({ error: 'invalid_code' }, { status: 400, headers: NO_STORE }); + } + await refund(); logger.info('Mobile hand-off redeemed', { flow: result.bundle.flow }); return NextResponse.json({ ...result.bundle, state: result.state }, { headers: NO_STORE }); diff --git a/app/api/auth/sso/complete/route.ts b/app/api/auth/sso/complete/route.ts index dc2eb65a2..3f183cf19 100644 --- a/app/api/auth/sso/complete/route.ts +++ b/app/api/auth/sso/complete/route.ts @@ -10,6 +10,7 @@ import { } from '@/lib/oauth/token-exchange'; import { buildRedeemBundle } from '@/lib/auth/pair-bundle'; import { isHandoffCodeChallenge, stashHandoff } from '@/lib/auth/handoff-store'; +import { desktopHandoffTarget } from '@/lib/auth/mobile-handoff'; import { isStoreUnavailable, storeUnavailableResponse } from '@/lib/auth/store-unavailable'; import { refreshTokenCookieName, refreshTokenServerCookieName } from '@/lib/oauth/tokens'; import { getCookieOptions, getSignInCookieOptions } from '@/lib/oauth/cookie-config'; @@ -149,6 +150,28 @@ export async function POST(request: NextRequest) { // builds refuse a provider on another host, so those renew through // this webmail - the same bundle a paired phone gets. const { clientId, serverUrl } = getRequiredConfig(pendingServerId); + if (mobileRedirectUri && desktopHandoffTarget(mobileRedirectUri)) { + // The desktop app on this instance: its redeem writes its own cookies, the way + // the code below would have for this browser. sso/start made sure of a challenge. + if (!mobileCodeChallenge) throw new Error('desktop hand-off without a challenge'); + const handoffCode = await stashHandoff({ + flow: 'desktop-tokens', + server_url: serverUrl, + server_id: pendingServerId, + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + id_token: tokens.id_token, + expires_in: tokens.expires_in ?? 3600, + signed_in_at: signedInAt, + }, { challenge: mobileCodeChallenge, state: mobileState ?? '', awaitConfirm: true }); + logger.info('Desktop hand-off parked', { flow: 'desktop-tokens' }); + return NextResponse.json({ + mobile_handoff_code: handoffCode, + server_url: serverUrl, + mobile_redirect_uri: mobileRedirectUri, + mobile_state: mobileState, + }); + } const bundle = buildRedeemBundle({ flow: 'oauth', serverUrl, diff --git a/app/api/auth/sso/start/route.ts b/app/api/auth/sso/start/route.ts index 6a8963af8..fd2268522 100644 --- a/app/api/auth/sso/start/route.ts +++ b/app/api/auth/sso/start/route.ts @@ -12,7 +12,7 @@ import { getCookieOptions } from '@/lib/oauth/cookie-config'; import { hasSessionSecret } from '@/lib/auth/session-secret'; import { configManager } from '@/lib/admin/config-manager'; import { rejectCrossOriginRequest } from '@/lib/security/same-origin'; -import { isMobileCodeChallenge, mobileHandoffTarget } from '@/lib/auth/mobile-handoff'; +import { desktopHandoffTarget, isMobileCodeChallenge, mobileHandoffTarget } from '@/lib/auth/mobile-handoff'; const SSO_PENDING_COOKIE = 'sso_pending'; const SSO_PENDING_MAX_AGE = 300; // 5 minutes @@ -73,9 +73,14 @@ export async function POST(request: NextRequest) { : null; const mobileState = typeof rawMobileState === 'string' && rawMobileState ? rawMobileState : null; - if (mobileRedirectUri && !mobileHandoffTarget(mobileRedirectUri)) { + if (mobileRedirectUri && !mobileHandoffTarget(mobileRedirectUri) && !desktopHandoffTarget(mobileRedirectUri)) { return NextResponse.json({ error: 'Invalid mobile_redirect_uri' }, { status: 400 }); } + // The desktop app's listener only ever gets a code. Without a challenge there'd be + // tokens in the answer, on the way to a link. + if (mobileRedirectUri && desktopHandoffTarget(mobileRedirectUri) && !isMobileCodeChallenge(rawMobileCodeChallenge)) { + return NextResponse.json({ error: 'Invalid mobile_code_challenge' }, { status: 400 }); + } // 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. diff --git a/components/auth/mobile-handoff-consent.tsx b/components/auth/mobile-handoff-consent.tsx index 695161a7e..5816efc0c 100644 --- a/components/auth/mobile-handoff-consent.tsx +++ b/components/auth/mobile-handoff-consent.tsx @@ -19,6 +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; } /** @@ -29,8 +31,9 @@ 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 }: MobileHandoffConsentProps) { +export function MobileHandoffConsent({ url, resolveUrl, username, onCancel, onError, desktop }: MobileHandoffConsentProps) { const t = useTranslations("login"); + const tDesktop = useTranslations("desktop_browser_sign_in"); // The dialog closes itself right after confirming; while the code is being // made live, that close must not count as declining. const resolving = useRef(false); @@ -51,16 +54,18 @@ export function MobileHandoffConsent({ url, resolveUrl, username, onCancel, onEr return; } window.location.replace(resolved); - onCancel(); + // A custom scheme leaves this page where it is. The desktop app's listener is + // a page of its own, and going anywhere now could overtake it. + if (!desktop) onCancel(); }); return; } if (url) window.location.replace(url); }} - title={t("mobile_handoff.title")} - message={t("mobile_handoff.description", { username })} - confirmText={t("mobile_handoff.confirm")} - cancelText={t("mobile_handoff.cancel")} + title={desktop ? tDesktop("consent_title") : t("mobile_handoff.title")} + message={desktop ? tDesktop("consent_description", { username }) : t("mobile_handoff.description", { username })} + confirmText={desktop ? tDesktop("consent_confirm") : t("mobile_handoff.confirm")} + cancelText={desktop ? tDesktop("consent_cancel") : t("mobile_handoff.cancel")} /> ); } diff --git a/components/layout/window-controls-host.tsx b/components/layout/window-controls-host.tsx index c829e15c1..1681da6f0 100644 --- a/components/layout/window-controls-host.tsx +++ b/components/layout/window-controls-host.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from "react"; import { applyControlsArea, watchTitlebarArea, watchWindowRows, type TitlebarArea } from "@/lib/window-controls-overlay"; +import { claimBrowserSignIn } from "@/lib/desktop/browser-sign-in"; /** * The window's controls over the app, with no title bar row: see @@ -10,6 +11,9 @@ import { applyControlsArea, watchTitlebarArea, watchWindowRows, type TitlebarAre * (admin, setup) get it too; there are no messages up there. */ export function WindowControlsHost() { + // In the first render of every page, before any frame exists: a frame can reach the + // bridge, and whoever comes after this gets nothing. + if (typeof window !== "undefined") claimBrowserSignIn(); const [area, setArea] = useState(null); useEffect(() => watchTitlebarArea((next) => { diff --git a/desktop-policies/Bulwark.admx b/desktop-policies/Bulwark.admx index d4b1b0817..7eb70a262 100644 --- a/desktop-policies/Bulwark.admx +++ b/desktop-policies/Bulwark.admx @@ -209,6 +209,18 @@ + + + + + + + + + + + + diff --git a/desktop-policies/de-DE/Bulwark.adml b/desktop-policies/de-DE/Bulwark.adml index fbacf62b3..2b2d66655 100644 --- a/desktop-policies/de-DE/Bulwark.adml +++ b/desktop-policies/de-DE/Bulwark.adml @@ -56,6 +56,8 @@ Eine JSON-Regel pro Zeile, im Format von Chrome: {"pattern":"https://[*.]example.com","filter":{"ISSUER":{"CN":"Example CA"}}}. Die App wählt dann für diese Website das passende Zertifikat ohne Rückfrage. Websites, die den Zertifikatspeicher des Systems verwenden dürfen Die Bulwark-Server, nach https-Adresse, deren Plugins mit den Zertifikaten im Speicher des Betriebssystems signieren und entschlüsseln dürfen, ohne dass der Benutzer für jede Website gefragt wird. Eine pro Zeile. + Anmeldung über den Browser anbieten + Wenn aktiviert oder nicht konfiguriert, bietet die Anmeldeseite „Mit Ihrem Browser anmelden“ an, damit Benutzer dort ihren Passwort-Manager, Passkeys und Ihr Single Sign-on verwenden können. Wenn deaktiviert, fehlt die Schaltfläche und die App lehnt den Vorgang ab. Das Formular in der App bleibt, sofern der Server nicht nur OAuth erlaubt. Auf dem Gerät behaltene E-Mails löschen Setzen Sie dies auf einen neuen Wert, etwa das heutige Datum, um alles zu löschen, was die App für alle Server und Konten auf dem Gerät behält: E-Mails, Schlüssel und Anmeldungen, Benutzer melden sich also neu an. Jeder Wert löscht einmal: Die App merkt sich, welche sie schon ausgeführt hat, ein Wert kann also stehen bleiben. Verwenden Sie einen neuen Wert, um erneut zu löschen. diff --git a/desktop-policies/en-US/Bulwark.adml b/desktop-policies/en-US/Bulwark.adml index 5c73606f8..f848e7d44 100644 --- a/desktop-policies/en-US/Bulwark.adml +++ b/desktop-policies/en-US/Bulwark.adml @@ -56,6 +56,8 @@ One JSON rule per line, in the format Chrome uses: {"pattern":"https://[*.]example.com","filter":{"ISSUER":{"CN":"Example CA"}}}. The app then picks the matching certificate for that site without asking. Sites that may use the system certificate store The Bulwark servers, by https address, whose plugins may sign and decrypt with the certificates in the operating system's store, without the user being asked for each site. One per line. + Offer sign-in through the browser + When enabled or not configured, the login page offers "Sign in with your browser", so people can use their password manager, passkeys and your single sign-on there. When disabled, the button is gone and the app refuses the flow. The form in the app stays, unless the server only allows OAuth. Delete mail kept on the device Set this to a new value, such as today's date, to delete everything the app keeps on the device for every server and account: mail, keys, and sign-ins, so people sign in again. Each value deletes once: the app remembers the ones it has acted on, so it stays safe to leave a value in place. Use a new value to delete again. diff --git a/desktop-policies/org.bulwarkmail.desktop.mobileconfig b/desktop-policies/org.bulwarkmail.desktop.mobileconfig index 474b9f20a..bb3b0d05c 100644 --- a/desktop-policies/org.bulwarkmail.desktop.mobileconfig +++ b/desktop-policies/org.bulwarkmail.desktop.mobileconfig @@ -61,6 +61,8 @@ https://mail.example.com + BrowserSignIn + Recommended UpdateChannel diff --git a/desktop-policies/policies.json b/desktop-policies/policies.json index 965e905fb..751f93131 100644 --- a/desktop-policies/policies.json +++ b/desktop-policies/policies.json @@ -25,6 +25,7 @@ "KeystoreAllowedOrigins": [ "https://mail.example.com" ], + "BrowserSignIn": true, "Recommended": { "UpdateChannel": "stable" } diff --git a/lib/__tests__/desktop-handoff-routes.test.ts b/lib/__tests__/desktop-handoff-routes.test.ts new file mode 100644 index 000000000..4df5daf84 --- /dev/null +++ b/lib/__tests__/desktop-handoff-routes.test.ts @@ -0,0 +1,322 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +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. + */ + +const cookieJar = vi.hoisted(() => new Map }>()); +vi.mock('next/headers', () => ({ + cookies: async () => ({ + get: (name: string) => (cookieJar.has(name) ? { name, value: cookieJar.get(name)!.value } : undefined), + set: (name: string, value: string, options?: Record) => { + cookieJar.set(name, { value, options }); + }, + delete: (name: string) => { + cookieJar.delete(name); + }, + getAll: () => [...cookieJar.entries()].map(([name, { value }]) => ({ name, value })), + }), +})); + +const config = vi.hoisted(() => ({ values: {} as Record })); +vi.mock('@/lib/admin/config-manager', () => ({ + configManager: { + ensureLoaded: async () => {}, + get: (key: string, fallback: unknown) => (key in config.values ? config.values[key] : fallback), + }, +})); + +const verifyJmapAuth = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/auth/verify-jmap-auth', async (original) => ({ + ...(await original()), + verifyJmapAuth, +})); + +const stalwartPasswordLogin = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/auth/stalwart-password-login', async (original) => ({ + ...(await original()), + stalwartPasswordLogin, +})); + +const reserveLoginAttempt = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/auth/verify-budget', async (original) => ({ + ...(await original()), + reserveLoginAttempt, +})); + +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()), + reserveHandoffCreate: async () => true, + reserveHandoffRedeem: async () => async () => {}, +})); + +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: 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 { 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'; + +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' }, + body: JSON.stringify(body), + }); +} + +const parkBody = (extra: Record = {}) => ({ + code_challenge: CHALLENGE, + state: 'state-1', + server_url: SERVER, + username: 'a@example.org', + password: 'secret', + ...extra, +}); + +async function parkedCode(extra: Record = {}): Promise { + const answer = await park(post('/api/auth/desktop-handoff/park', parkBody(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; +} + +const redeemBody = (code: string, extra: Record = {}) => ({ code, code_verifier: VERIFIER, slot: 1, remember: true, allowed_servers: null, ...extra }); + +beforeEach(() => { + cookieJar.clear(); + resetHandoffStoreForTests(); + config.values = { jmapServerUrl: SERVER }; + verifyJmapAuth.mockReset(); + verifyJmapAuth.mockResolvedValue(undefined); + stalwartPasswordLogin.mockReset(); + reserveLoginAttempt.mockReset(); + reserveLoginAttempt.mockResolvedValue(async () => {}); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('the target', () => { + it('is only ever this computer on the one path', () => { + expect(desktopHandoffTarget('http://127.0.0.1:51234/bulwark-desktop/callback')).toBe('http://127.0.0.1:51234/bulwark-desktop/callback'); + for (const bad of [ + 'http://127.0.0.1/bulwark-desktop/callback', + 'http://127.0.0.1:99999/bulwark-desktop/callback', + 'http://localhost:51234/bulwark-desktop/callback', + 'https://127.0.0.1:51234/bulwark-desktop/callback', + 'http://127.0.0.1:51234/other', + 'http://127.0.0.1:51234/bulwark-desktop/callback?x=1', + 'http://127.0.0.1@evil.example:51234/bulwark-desktop/callback', + 'http://evil.example/bulwark-desktop/callback', + 'bulwarkmobile://auth/callback', + null, + ]) { + expect(desktopHandoffTarget(bad), String(bad)).toBe(''); + } + }); + + it('leaves the phone\'s rule as it was', () => { + expect(mobileHandoffTarget('http://127.0.0.1:51234/bulwark-desktop/callback')).toBe(''); + }); + + 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); + 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(); + expect([...cookieJar.keys()]).toEqual([]); + }); + + 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(verifyJmapAuth).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(); + }); + + 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' }); + }); + + 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('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); + }); +}); + +describe('redeeming, in the app', () => { + it('a password goes to the page, once, and no cookie is written for it', 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(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) }))); + 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); + }); + + 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))); + 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' }); + }); + + 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'] }))); + 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); + }); + + 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); + }); + + 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); + }); +}); + +describe('the two kinds of code stay apart', () => { + it('the phone\'s redeem gives away nothing of a desktop sign-in', async () => { + 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'); + }); + + 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))); + expect(answer.status).toBe(400); + expect(JSON.stringify(await answer.json())).not.toContain('secret'); + }); +}); diff --git a/lib/__tests__/sso-complete-route.test.ts b/lib/__tests__/sso-complete-route.test.ts index 22b508fd3..0bb8425d0 100644 --- a/lib/__tests__/sso-complete-route.test.ts +++ b/lib/__tests__/sso-complete-route.test.ts @@ -224,3 +224,46 @@ describe('sso/complete mobile hand-off while the shared store is down (#1066)', expect(JSON.stringify(res.body)).not.toMatch(/"at"|"rt"|mobile_handoff_code/); }); }); + +describe('/api/auth/sso/complete for the desktop app', () => { + const VERIFIER = 'x'.repeat(50); + const CHALLENGE = createHash('sha256').update(VERIFIER).digest('base64url'); + const LISTENER = 'http://127.0.0.1:51234/bulwark-desktop/callback'; + + it('parks the tokens under a code, writes nothing in this browser, and only a confirmed code redeems', 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 }); + const res = await complete(); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + mobile_handoff_code: expect.stringMatching(/^[0-9a-f]{64}$/), + server_url: 'https://mail.example.org', + mobile_redirect_uri: LISTENER, + mobile_state: 'd-1', + }); + expect(JSON.stringify(res.body)).not.toMatch(/"at"|"rt"|idt/); + expect(jar.has('jmap_rt')).toBe(false); + expect(jar.has('sso_pending')).toBe(false); + + expect((await redeemHandoff(res.body.mobile_handoff_code, VERIFIER)).ok).toBe(false); + }); + + 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' }); + const res = await complete(); + expect(await confirmHandoff(res.body.mobile_handoff_code)).toBe(true); + expect(await redeemHandoff(res.body.mobile_handoff_code, VERIFIER)).toMatchObject({ + ok: true, + state: 'd-1', + bundle: { flow: 'desktop-tokens', server_id: 'second', access_token: 'at', refresh_token: 'rt', id_token: 'idt' }, + }); + }); + + it('fails rather than hands over tokens if a pending cookie has no challenge', async () => { + pending({ mobile_redirect_uri: LISTENER, mobile_state: 'd-1' }); + const res = await complete(); + expect(res.status).toBe(401); + expect(JSON.stringify(res.body)).not.toMatch(/"at"|"rt"/); + }); +}); diff --git a/lib/__tests__/sso-start-route.test.ts b/lib/__tests__/sso-start-route.test.ts index 6caf98a87..8cb34545f 100644 --- a/lib/__tests__/sso-start-route.test.ts +++ b/lib/__tests__/sso-start-route.test.ts @@ -196,3 +196,36 @@ describe('sso start for the mobile app', () => { expect(encrypted.last).not.toHaveProperty('mobile_code_challenge'); }); }); + +describe('sso start for the desktop app', () => { + const CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'; + const LISTENER = 'http://127.0.0.1:51234/bulwark-desktop/callback'; + const desktop = (extra: Record = {}) => callRoute({ + redirect_uri: 'https://mail.example.com/auth/callback', + mobile_redirect_uri: LISTENER, + mobile_state: 'd-1', + ...extra, + }); + + beforeEach(() => { + encrypted.last = null; + }); + + it('keeps the loopback target and its challenge for the complete route', async () => { + const { status } = await desktop({ mobile_code_challenge: CHALLENGE }); + expect(status).toBe(200); + expect(encrypted.last).toMatchObject({ mobile_redirect_uri: LISTENER, mobile_state: 'd-1', mobile_code_challenge: CHALLENGE }); + }); + + it('refuses it without a challenge: tokens would come back for a link', async () => { + const { status } = await desktop(); + expect(status).toBe(400); + expect(encrypted.last).toBeNull(); + }); + + it.each(['http://127.0.0.1:51234/other', 'http://localhost:51234/bulwark-desktop/callback', 'http://evil.example/bulwark-desktop/callback'])('refuses %s as a target', async (target) => { + const { status } = await desktop({ mobile_code_challenge: CHALLENGE, mobile_redirect_uri: target }); + expect(status).toBe(400); + expect(encrypted.last).toBeNull(); + }); +}); diff --git a/lib/auth/handoff-store.ts b/lib/auth/handoff-store.ts index ba0a8fc0e..4e066125c 100644 --- a/lib/auth/handoff-store.ts +++ b/lib/auth/handoff-store.ts @@ -59,9 +59,29 @@ export function isHandoffCode(value: unknown): value is string { return typeof value === 'string' && CODE_RE.test(value); } +/** + * What the desktop app's sign-in parks (app/api/auth/desktop-handoff). The app's redeem + * writes its own cookies from this, so these fields never go to anyone else: the mobile + * redeem route refuses them. + */ +export type DesktopHandoffBundle = + | { flow: 'desktop-password'; server_url: string; server_id: string | null; username: string; password: string } + | { + flow: 'desktop-tokens'; + server_url: string; + server_id: string | null; + access_token: string; + refresh_token?: string; + id_token?: string; + expires_in: number; + signed_in_at: number; + }; + +export type ParkedHandoff = RedeemBundle | DesktopHandoffBundle; + interface HandoffRecord { /** Null once redeemed (or tried) or expired. */ - bundle: RedeemBundle | null; + bundle: ParkedHandoff | null; state: string; challenge: string; /** Whether the user confirmed the hand-off; only confirmed codes redeem. */ @@ -72,7 +92,7 @@ interface HandoffRecord { } export type HandoffRedeemResult = - | { ok: true; bundle: RedeemBundle; state: string } + | { ok: true; bundle: ParkedHandoff; state: string } | { ok: false; reason: 'invalid' | 'expired' | 'verifier_mismatch' }; const STORE_KEY = '__bulwarkMobileHandoffStore'; @@ -98,7 +118,7 @@ function s256(verifier: string): string { } function newRecord( - bundle: RedeemBundle, + bundle: ParkedHandoff, options: { challenge: string; state: string; awaitConfirm?: boolean }, now: number, ): HandoffRecord { @@ -121,7 +141,7 @@ function confirmed(record: HandoffRecord, now: number): HandoffRecord { } /** What a redeem attempt of `record` (spent by the attempt) gets. */ -function redeemOutcome(record: HandoffRecord, bundle: RedeemBundle | null, verifier: string, now: number): HandoffRedeemResult { +function redeemOutcome(record: HandoffRecord, bundle: ParkedHandoff | null, verifier: string, now: number): HandoffRedeemResult { if (!bundle) return { ok: false, reason: record.expiresAt <= now ? 'expired' : 'invalid' }; if (!record.confirmed) return { ok: false, reason: 'invalid' }; const expected = Buffer.from(record.challenge, 'ascii'); @@ -129,7 +149,7 @@ function redeemOutcome(record: HandoffRecord, bundle: RedeemBundle | null, verif if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) { return { ok: false, reason: 'verifier_mismatch' }; } - if (bundle.flow === 'oauth' && typeof bundle.expires_in === 'number') { + if ((bundle.flow === 'oauth' || bundle.flow === 'desktop-tokens') && typeof bundle.expires_in === 'number') { const elapsed = Math.floor((now - record.issuedAt) / 1000); return { ok: true, bundle: { ...bundle, expires_in: Math.max(0, bundle.expires_in - elapsed) }, state: record.state }; } @@ -161,7 +181,7 @@ const ttl = (record: HandoffRecord, now: number) => Math.max(record.forgetAt - n * `awaitConfirm` the code only becomes redeemable through confirmHandoff. */ export async function stashHandoff( - bundle: RedeemBundle, + bundle: ParkedHandoff, options: { challenge: string; state: string; awaitConfirm?: boolean }, now = Date.now(), ): Promise { diff --git a/lib/auth/mobile-handoff-client.ts b/lib/auth/mobile-handoff-client.ts index 9730bcce4..e8fe869c9 100644 --- a/lib/auth/mobile-handoff-client.ts +++ b/lib/auth/mobile-handoff-client.ts @@ -28,6 +28,43 @@ export async function requestMobileHandoffCodeUrl(opts: { } } +/** + * 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. + */ +export async function parkDesktopSignIn(opts: { + challenge: string; + state: string; + serverUrl: string; + serverId?: string; + username: string; + password: string; + totp?: string; + redirectUri: string; +}): Promise<{ code: string } | { error: string }> { + try { + const res = await apiFetch('/api/auth/desktop-handoff/park', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + code_challenge: opts.challenge, + state: opts.state, + server_url: opts.serverUrl, + server_id: opts.serverId, + username: opts.username, + password: opts.password, + totp: opts.totp, + redirect_uri: opts.redirectUri, + }), + }); + const data = (await res.json().catch(() => null)) as { code?: unknown; error?: unknown } | null; + if (res.ok && typeof data?.code === 'string' && data.code) return { code: data.code }; + return { error: typeof data?.error === 'string' ? data.error : 'login_failed' }; + } catch { + return { error: 'network_error' }; + } +} + /** * Confirm an SSO hand-off the server parked (/api/auth/handoff/confirm) and * return the app link with its code. Null when the code is gone (it waited diff --git a/lib/auth/mobile-handoff.ts b/lib/auth/mobile-handoff.ts index 3de25976f..0faeeb56d 100644 --- a/lib/auth/mobile-handoff.ts +++ b/lib/auth/mobile-handoff.ts @@ -27,6 +27,26 @@ export function mobileHandoffTarget(raw: string | null | undefined): string { : ''; } +/** + * The desktop app's loopback listener (RFC 8252), the other kind of target. Only ever + * with a code: unlike the phone's link, it has no older builds that take the sign-in in a + * fragment, so without a valid challenge this isn't a hand-off at all. The code goes + * nowhere but this computer, whichever port a link names, and it's worthless without the + * verifier behind the challenge. + */ +const DESKTOP_TARGET = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{3,4})\/bulwark-desktop\/callback$/; + +export function desktopHandoffTarget(raw: string | null | undefined): string { + if (typeof raw !== 'string') return ''; + const match = DESKTOP_TARGET.exec(raw.trim()); + return match && Number(match[1]) <= 65535 ? match[0] : ''; +} + +/** Either kind of target, as the callback page reads it back. */ +export function handoffTarget(raw: string | null | undefined): string { + return mobileHandoffTarget(raw) || desktopHandoffTarget(raw); +} + /** The URL the browser hands to the app: the target plus the fragment. */ export function buildMobileHandoffUrl(target: string, fragment: Record): string { return `${target}#${new URLSearchParams(fragment).toString()}`; diff --git a/lib/desktop/__tests__/browser-side.test.ts b/lib/desktop/__tests__/browser-side.test.ts index 6d7d8d23a..9a7136815 100644 --- a/lib/desktop/__tests__/browser-side.test.ts +++ b/lib/desktop/__tests__/browser-side.test.ts @@ -144,79 +144,212 @@ describe('JMAPClient on an approved http server', () => { }); describe('runDesktopBrowserSignIn', () => { - const ENDPOINTS = { authorization_endpoint: 'https://mail.example/authorize', client_id: 'registered-client', scope: 'openid email' }; + const ENDPOINTS = { authorization_endpoint: 'https://mail.example/authorize', client_id: 'registered-client', scope: 'openid email', issuer: 'https://mail.example' }; + const REDIRECT = 'http://127.0.0.1:51234/bulwark-desktop/callback'; function authBridge(result: unknown) { - const completeBrowserSignIn = vi.fn(async (_flowId: string, url: string) => ( - typeof result === 'function' ? (result as (u: string) => unknown)(url) : result - )); - const bridge = { - version: 1, - platform: 'win32', - servers: { prepare: vi.fn(async () => ({ ok: true, approved: false })), noteSession: vi.fn() }, - auth: { - beginBrowserSignIn: vi.fn(async () => ({ flowId: 'f1', redirectUri: 'http://127.0.0.1:51234/bulwark-desktop/callback' })), - completeBrowserSignIn, - cancelBrowserSignIn: vi.fn(), - }, - } as unknown as BulwarkDesktopBridge; - setBridge(bridge); - return bridge; + const controls = { + begin: vi.fn(async (): Promise => ({ ok: true, flowId: 'f1', redirectUri: REDIRECT, state: 'main-state' })), + complete: vi.fn(async (_flowId: string, url: string) => ( + typeof result === 'function' ? (result as (u: string) => unknown)(url) : result + )), + useScheme: vi.fn(async () => 'bulwark://sign-in/callback'), + cancel: vi.fn(), + beginPassword: vi.fn(async (): Promise => ({ ok: true, host: 'mail.example' })), + nextPassword: vi.fn(async (): Promise => ({ ok: false, error: 'timeout' })), + answerPassword: vi.fn(), + outcome: vi.fn(async (): Promise => ({ ok: true, code: '', state: 'main-state' })), + }; + setBridge({ version: 1, platform: 'win32', auth: { claim: () => controls } } as unknown as BulwarkDesktopBridge); + return controls; } - const options = { serverUrl: 'https://mail.example', callbackPath: '/en/auth/callback', slot: 1, remember: true, addAccount: false }; + const redeem = vi.fn(async () => true); + const tryPassword = vi.fn(async (): Promise<{ ok: true } | { ok: false; error: 'invalid_credentials' | 'totp_required' | 'other' }> => ({ ok: true })); + const options = { serverUrl: 'https://mail.example', slot: 1, remember: true, addAccount: false, fresh: false, redeem, tryPassword }; beforeEach(() => { + redeem.mockClear(); + tryPassword.mockClear(); vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(ENDPOINTS), { status: 200 }))); }); - it('runs PKCE with the loopback redirect and parks what the callback page needs', async () => { + it('runs PKCE with state from main and the loopback redirect, and redeems here, with nothing in an address', async () => { const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); let authorize = new URL('https://x'); authBridge((url: string) => { authorize = new URL(url); - return { ok: true, code: 'the-code', state: authorize.searchParams.get('state') }; + return { ok: true, code: 'the-code', state: 'main-state' }; + }); + let readBack = {}; + redeem.mockImplementationOnce(async () => { + readBack = { client: sessionStorage.getItem('oauth_client_id'), slot: sessionStorage.getItem('oauth_cookie_slot'), remember: sessionStorage.getItem('oauth_remember') }; + return true; }); const outcome = await runDesktopBrowserSignIn(options); - expect(outcome.kind).toBe('callback'); + expect(outcome).toEqual({ kind: 'signed-in' }); expect(authorize.origin + authorize.pathname).toBe('https://mail.example/authorize'); expect(authorize.searchParams.get('client_id')).toBe('registered-client'); - expect(authorize.searchParams.get('redirect_uri')).toBe('http://127.0.0.1:51234/bulwark-desktop/callback'); + expect(authorize.searchParams.get('redirect_uri')).toBe(REDIRECT); + expect(authorize.searchParams.get('state')).toBe('main-state'); expect(authorize.searchParams.get('code_challenge_method')).toBe('S256'); expect(authorize.searchParams.get('code_challenge')).toBeTruthy(); - expect(sessionStorage.getItem('oauth_redirect_uri')).toBe('http://127.0.0.1:51234/bulwark-desktop/callback'); - expect(sessionStorage.getItem('oauth_client_id')).toBe('registered-client'); - expect(sessionStorage.getItem('oauth_server_url')).toBe('https://mail.example'); - expect(sessionStorage.getItem('oauth_cookie_slot')).toBe('1'); - expect(sessionStorage.getItem('oauth_code_verifier')).toBeTruthy(); - }); - - it('rejects an answer with another state', async () => { - const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); - authBridge({ ok: true, code: 'c', state: 'forged' }); - const outcome = await runDesktopBrowserSignIn(options); - expect(outcome).toEqual({ kind: 'failed', error: 'state_mismatch' }); + expect(readBack).toEqual({ client: 'registered-client', slot: '1', remember: 'true' }); + const [server, code, verifier, redirect] = redeem.mock.calls[0] as unknown as string[]; + expect([server, code, redirect]).toEqual(['https://mail.example', 'the-code', REDIRECT]); + // The verifier behind the challenge, kept in this function and nowhere else. + expect(verifier.length).toBeGreaterThanOrEqual(43); + expect(authorize.toString()).not.toContain(verifier); expect(sessionStorage.getItem('oauth_code_verifier')).toBeNull(); + expect(sessionStorage.getItem('oauth_client_id')).toBeNull(); }); - it('sends nothing to a server the user declined', async () => { + it('refuses an answer another issuer signed', async () => { const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); - const bridge = authBridge({ ok: false, error: 'cancelled' }); - bridge.servers!.prepare = vi.fn(async () => ({ ok: false as const, reason: 'declined' as const })); - const outcome = await runDesktopBrowserSignIn(options); - expect(outcome.kind).toBe('declined'); - expect(bridge.auth!.beginBrowserSignIn).not.toHaveBeenCalled(); + authBridge({ ok: true, code: 'c', state: 'main-state', iss: 'https://evil.example' }); + expect(await runDesktopBrowserSignIn(options)).toEqual({ kind: 'failed', error: 'issuer_mismatch' }); + expect(redeem).not.toHaveBeenCalled(); + }); + + it('asks the provider for a new login when the app says one is due', async () => { + const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); + let authorize = new URL('https://x'); + authBridge((url: string) => { + authorize = new URL(url); + return { ok: false, error: 'cancelled' }; + }); + await runDesktopBrowserSignIn({ ...options, fresh: true }); + expect(authorize.searchParams.get('prompt')).toBe('login'); + }); + + it.each(['declined', 'policy', 'invalid'])('takes the no from main: %s, and nothing is asked of the server', async (error) => { + const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); + const controls = authBridge({ ok: false, error: 'cancelled' }); + controls.begin.mockResolvedValueOnce({ ok: false, error }); + expect((await runDesktopBrowserSignIn(options)).kind).toBe(error); + expect(controls.complete).not.toHaveBeenCalled(); expect(fetch).not.toHaveBeenCalled(); }); - it('says so when the server has no OAuth, and closes the listener', async () => { + it('a timeout is its own answer, so the page can say try again', async () => { const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); - vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 404 }))); - const bridge = authBridge({ ok: true }); - const outcome = await runDesktopBrowserSignIn(options); - expect(outcome.kind).toBe('unavailable'); - expect(bridge.auth!.cancelBrowserSignIn).toHaveBeenCalledWith('f1'); - expect(bridge.auth!.completeBrowserSignIn).not.toHaveBeenCalled(); + authBridge({ ok: false, error: 'timeout' }); + expect((await runDesktopBrowserSignIn(options)).kind).toBe('timeout'); + }); + + it('a discovery outage is a failure, not the password page', async () => { + const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); + vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 503 }))); + const controls = authBridge({ ok: true }); + expect((await runDesktopBrowserSignIn(options)).kind).toBe('failed'); + expect(controls.cancel).toHaveBeenCalledWith('f1'); + expect(controls.beginPassword).not.toHaveBeenCalled(); + }); + + it('a server with no OAuth gets the page main serves, and each post goes through the login of the app', async () => { + const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'no_oauth' }), { status: 404 }))); + const controls = authBridge({ ok: true }); + controls.nextPassword + .mockResolvedValueOnce({ ok: true, username: 'a', password: 'wrong' }) + .mockResolvedValueOnce({ ok: true, username: 'a', password: 'right', totp: '123456' }); + tryPassword.mockResolvedValueOnce({ ok: false, error: 'invalid_credentials' }).mockResolvedValueOnce({ ok: true }); + expect(await runDesktopBrowserSignIn(options)).toEqual({ kind: 'signed-in' }); + expect(controls.complete).not.toHaveBeenCalled(); + expect(tryPassword.mock.calls.map((call) => (call as unknown[])[0])).toEqual([ + { ok: true, username: 'a', password: 'wrong' }, + { ok: true, username: 'a', password: 'right', totp: '123456' }, + ]); + expect(controls.answerPassword.mock.calls).toEqual([ + ['f1', { ok: false, error: 'invalid_credentials' }], + ['f1', { ok: true }], + ]); + }); + + it('a server that refuses loopback goes by the scheme', async () => { + const { runDesktopBrowserSignIn } = await import('../browser-sign-in'); + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ...ENDPOINTS, use_scheme: true }), { status: 200 }))); + let authorize = new URL('https://x'); + const controls = authBridge((url: string) => { + authorize = new URL(url); + return { ok: true, code: 'c', state: 'main-state' }; + }); + await runDesktopBrowserSignIn(options); + expect(controls.useScheme).toHaveBeenCalledWith('f1'); + expect(authorize.searchParams.get('redirect_uri')).toBe('bulwark://sign-in/callback'); + expect((redeem.mock.calls[0] as unknown as string[])[3]).toBe('bulwark://sign-in/callback'); + }); +}); + +describe('runInstanceBrowserSignIn', () => { + const REDIRECT = 'http://127.0.0.1:51234/bulwark-desktop/callback'; + + function bridgeWith(complete: (flowId: string, url: string) => unknown) { + const controls = { + begin: vi.fn(async () => ({ ok: true, flowId: 'f1', redirectUri: REDIRECT, state: 'main-state' })), + complete: vi.fn(async (flowId: string, url: string) => complete(flowId, url)), + cancel: vi.fn(), + }; + setBridge({ version: 1, platform: 'win32', auth: { claim: () => controls } } as unknown as BulwarkDesktopBridge); + return controls; + } + + it('opens the login page of the instance with no secret in the address, and hands back the verifier', async () => { + const { runInstanceBrowserSignIn } = await import('../browser-sign-in'); + let opened = new URL('https://x'); + bridgeWith((_flow, url) => { + opened = new URL(url); + return { ok: true, code: 'the-code', state: 'main-state' }; + }); + const outcome = await runInstanceBrowserSignIn({ base: 'https://bulwark.example/mail', locale: 'de', fresh: false }); + expect(opened.origin + opened.pathname).toBe('https://bulwark.example/mail/de/login'); + expect(opened.searchParams.get('mobile_redirect_uri')).toBe(REDIRECT); + expect(opened.searchParams.get('mobile_state')).toBe('main-state'); + expect(opened.searchParams.get('mobile_code_challenge')).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(opened.searchParams.has('fresh_login')).toBe(false); + if (outcome.kind !== 'code') throw new Error(outcome.kind); + expect(outcome.code).toBe('the-code'); + expect(opened.toString()).not.toContain(outcome.verifier); + const challenge = Buffer.from(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(outcome.verifier))).toString('base64url'); + expect(opened.searchParams.get('mobile_code_challenge')).toBe(challenge); + }); + + it('passes on that a new login is due, and takes a timeout as a timeout', async () => { + const { runInstanceBrowserSignIn } = await import('../browser-sign-in'); + let opened = new URL('https://x'); + bridgeWith((_flow, url) => { + opened = new URL(url); + return { ok: false, error: 'timeout' }; + }); + expect((await runInstanceBrowserSignIn({ base: 'https://b.example', locale: 'en', fresh: true })).kind).toBe('timeout'); + expect(opened.searchParams.get('fresh_login')).toBe('1'); + }); +}); + +describe('who gets the sign-in calls', () => { + it('claims them once per bridge, whatever asks after that', async () => { + const { claimBrowserSignIn } = await import('../browser-sign-in'); + const controls = {}; + const claim = vi.fn(() => controls); + setBridge({ version: 1, platform: 'win32', auth: { claim } } as unknown as BulwarkDesktopBridge); + expect(claimBrowserSignIn()).toBe(controls); + expect(claimBrowserSignIn()).toBe(controls); + expect(claim).toHaveBeenCalledTimes(1); + }); + + it('offers nothing in a browser, under an older shell, or with the policy off', async () => { + const { browserSignInAvailable } = await import('../browser-sign-in'); + setBridge(undefined); + expect(browserSignInAvailable()).toBe(false); + setBridge({ version: 1, platform: 'win32' } as unknown as BulwarkDesktopBridge); + expect(browserSignInAvailable()).toBe(false); + const claim = () => ({}); + setBridge({ version: 1, platform: 'win32', auth: { claim } } as unknown as BulwarkDesktopBridge); + expect(browserSignInAvailable()).toBe(true); + const { EMPTY_POLICY_LAYERS, resolvePolicies } = await import('../policy-schema'); + const snapshot = resolvePolicies({ ...EMPTY_POLICY_LAYERS, forcedMachine: { BrowserSignIn: false } }); + setBridge({ version: 1, platform: 'win32', auth: { claim }, policy: { get: () => snapshot, onChange: () => () => {} } } as unknown as BulwarkDesktopBridge); + expect(browserSignInAvailable()).toBe(false); }); }); diff --git a/lib/desktop/__tests__/desktop-oauth-route.test.ts b/lib/desktop/__tests__/desktop-oauth-route.test.ts new file mode 100644 index 000000000..739529970 --- /dev/null +++ b/lib/desktop/__tests__/desktop-oauth-route.test.ts @@ -0,0 +1,119 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { NextRequest } from 'next/server'; + +/** + * What the desktop app asks before it sends someone to a server's own sign-in page: the + * authorize endpoint and a client id, and which redirect that server will take. + */ + +vi.mock('@/lib/logger', () => ({ logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() } })); +vi.mock('@/lib/admin/config-manager', () => ({ + configManager: { ensureLoaded: async () => {}, get: (key: string, fallback: unknown) => (key === 'allowCustomJmapEndpoint' ? true : fallback) }, +})); +vi.mock('@/lib/oauth/custom-upstream', () => ({ + resolveCustomUpstream: async (serverUrl: string, clientId: string) => (serverUrl.startsWith('https://') ? { serverUrl, clientId, trusted: false } : null), +})); +const discoverOAuth = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/oauth/discovery', () => ({ discoverOAuth })); +vi.mock('@/lib/oauth/token-exchange', () => ({ getDiscoveryValidator: () => undefined })); + +const SERVER = 'https://mail.example'; +const REDIRECT = 'http://127.0.0.1:51234/bulwark-desktop/callback'; +const METADATA = { issuer: SERVER, authorization_endpoint: `${SERVER}/login`, token_endpoint: `${SERVER}/auth/token` }; + +let registrations: { url: string; redirect: string }[]; +let answer: (redirect: string) => Response; + +function post(body: unknown) { + return new NextRequest(`https://app.bulwark.localhost/api/auth/desktop-oauth`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'sec-fetch-site': 'same-origin' }, + body: JSON.stringify(body), + }); +} + +async function route() { + vi.stubEnv('NEXT_PUBLIC_BULWARK_DESKTOP', '1'); + vi.resetModules(); + return (await import('@/app/api/auth/desktop-oauth/route')).POST; +} + +beforeEach(() => { + registrations = []; + discoverOAuth.mockReset().mockResolvedValue(METADATA); + answer = () => new Response(JSON.stringify({ client_id: 'swc1.abc' }), { status: 201 }); + vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const redirect = (JSON.parse(String(init?.body)) as { redirect_uris: string[] }).redirect_uris[0]; + registrations.push({ url: String(input), redirect }); + return answer(redirect); + })); +}); + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +describe('/api/auth/desktop-oauth', () => { + it('registers the loopback redirect, with no port: servers ignore the port', async () => { + const POST = await route(); + const res = await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT })); + expect(await res.json()).toMatchObject({ authorization_endpoint: `${SERVER}/login`, client_id: 'swc1.abc', issuer: SERVER }); + expect(registrations).toEqual([{ url: `${SERVER}/auth/register`, redirect: 'http://127.0.0.1/bulwark-desktop/callback' }]); + }); + + it('uses the registration endpoint the server names', async () => { + discoverOAuth.mockResolvedValue({ ...METADATA, registration_endpoint: `${SERVER}/oauth/clients` }); + const POST = await route(); + await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT })); + expect(registrations[0].url).toBe(`${SERVER}/oauth/clients`); + }); + + it('says so when a server has no OAuth', async () => { + discoverOAuth.mockResolvedValue(null); + const POST = await route(); + const res = await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT })); + expect(res.status).toBe(404); + expect(await res.json()).toEqual({ error: 'no_oauth' }); + }); + + it('a discovery outage is not the same answer', async () => { + discoverOAuth.mockRejectedValue(new Error('down')); + const POST = await route(); + expect((await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT }))).status).toBe(503); + }); + + it('with registration off, sends the fixed id and the loopback redirect', async () => { + answer = () => new Response('{}', { status: 401 }); + const POST = await route(); + const body = await (await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT }))).json(); + expect(body.client_id).toBe('bulwark-desktop'); + expect(body.use_scheme).toBeUndefined(); + expect(registrations).toHaveLength(1); + }); + + it('takes the scheme only from a server that refuses loopback by name and accepts the scheme', async () => { + answer = (redirect) => (redirect.startsWith('bulwark:') + ? new Response(JSON.stringify({ client_id: 'schemed' }), { status: 201 }) + : new Response(JSON.stringify({ error: 'invalid_redirect_uri' }), { status: 400 })); + const POST = await route(); + const body = await (await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT }))).json(); + expect(body).toMatchObject({ client_id: 'schemed', use_scheme: true }); + expect(registrations.map((r) => r.redirect)).toEqual(['http://127.0.0.1/bulwark-desktop/callback', 'bulwark://sign-in/callback']); + }); + + it('stays on loopback when the server refuses both', async () => { + answer = () => new Response(JSON.stringify({ error: 'invalid_redirect_uri' }), { status: 400 }); + const POST = await route(); + const body = await (await POST(post({ serverUrl: SERVER, redirectUri: REDIRECT }))).json(); + expect(body.client_id).toBe('bulwark-desktop'); + expect(body.use_scheme).toBeUndefined(); + }); + + it.each(['http://localhost:51234/bulwark-desktop/callback', 'https://evil.example/bulwark-desktop/callback', 'bulwark://sign-in/callback'])('refuses %s as the redirect', async (redirectUri) => { + const POST = await route(); + expect((await POST(post({ serverUrl: SERVER, redirectUri }))).status).toBe(400); + expect(registrations).toEqual([]); + }); +}); diff --git a/lib/desktop/__tests__/policy-schema.test.ts b/lib/desktop/__tests__/policy-schema.test.ts index 3411ad9ea..96ca32511 100644 --- a/lib/desktop/__tests__/policy-schema.test.ts +++ b/lib/desktop/__tests__/policy-schema.test.ts @@ -30,7 +30,7 @@ describe('the schema', () => { 'InstanceUrl', 'AllowStandalone', 'AllowedJmapServers', 'AllowInsecureInstance', 'UpdateChannel', 'AutoUpdate', 'PluginsMode', 'PluginAllowlist', 'OfflineEnabled', 'AppLockRequired', 'AppLockTimeoutMinutes', 'TelemetryAllowed', 'CrashReportsAllowed', 'QuickComposeShortcut', 'AuthServerAllowlist', 'AuthNegotiateDelegateAllowlist', - 'AutoSelectCertificateForUrls', 'KeystoreAllowedOrigins', 'WipeOfflineData', + 'AutoSelectCertificateForUrls', 'KeystoreAllowedOrigins', 'BrowserSignIn', 'WipeOfflineData', ]); for (const key of POLICY_KEYS) { const { title, description } = POLICY_SCHEMA[key]; diff --git a/lib/desktop/blocked-routes.ts b/lib/desktop/blocked-routes.ts index 093b38cf0..ec849e317 100644 --- a/lib/desktop/blocked-routes.ts +++ b/lib/desktop/blocked-routes.ts @@ -3,7 +3,7 @@ * hand-off both hand out `https://app.bulwark.localhost`, which nothing else * can reach, and the app has no use for impersonation. proxy.ts answers 404. */ -const BLOCKED = /^\/api\/auth\/(pair|handoff|impersonate)(\/|$)/; +const BLOCKED = /^\/api\/auth\/(pair|handoff|desktop-handoff|impersonate)(\/|$)/; export function isDesktopBlockedRoute(pathname: string): boolean { return BLOCKED.test(pathname); diff --git a/lib/desktop/browser-sign-in.ts b/lib/desktop/browser-sign-in.ts index a48437771..f671e0708 100644 --- a/lib/desktop/browser-sign-in.ts +++ b/lib/desktop/browser-sign-in.ts @@ -1,104 +1,207 @@ /** - * Sign-in through the system browser in the desktop build, for any Stalwart. + * "Sign in with your browser" in the desktop app, so a password manager, passkeys and an + * organisation's sign-in all work where they live. * - * A window on app.bulwark.localhost can't be a redirect target: Stalwart 1.0 - * refuses it for a public client, and identity providers won't embed. So the - * Electron main process listens on http://127.0.0.1: for one redirect and - * hands the code back. The rest is the regular PKCE flow: the same - * sessionStorage keys, then the callback page, which reads the stored redirect - * URI because it can't be rebuilt from this page's origin. + * Standalone: RFC 8252. The mail server's own authorize page in the system browser, with + * the redirect going to a listener in the Electron main process, and this page redeeming + * the code with the PKCE verifier it kept. A server with no OAuth at all gets a small page + * main serves on a stable loopback port, and what's posted there comes down the app's + * normal login path here. * - * Google and Entra can't work here. Their clients are registered by whoever - * owns them, and in standalone mode nobody does. Those need an instance. + * Instance: the instance's real login page at its real origin, so saved passwords match. + * It parks the sign-in on the instance and sends a one-time code to the same kind of + * listener (lib/auth/mobile-handoff.ts). The page redeems it with the verifier. + * + * The calls are taken once per document, in the first render (claimBrowserSignIn, from + * WindowControlsHost): a same-origin frame can reach the bridge, and main can't tell. + * + * Google and Entra can't work in standalone. Their clients are registered by whoever owns + * them, and there nobody does. Those need an instance. */ import { apiFetch } from '@/lib/browser-navigation'; -import { generateCodeChallenge, generateCodeVerifier, generateState } from '@/lib/oauth/pkce'; +import { IS_LITE } from '@/lib/lite'; +import { generateCodeChallenge, generateCodeVerifier } from '@/lib/oauth/pkce'; import { getDesktopBridge } from './bridge'; +import { desktopPolicyValue } from './policy'; +import type { DesktopBrowserSignInControls, DesktopPasswordSignInAnswer, DesktopPasswordSignInAttempt } from './types'; -export const DESKTOP_REDIRECT_URI_KEY = 'oauth_redirect_uri'; export const DESKTOP_CLIENT_ID_KEY = 'oauth_client_id'; export type DesktopBrowserSignInOutcome = - | { kind: 'callback'; callbackUrl: string } - | { kind: 'unavailable' } + | { kind: 'signed-in' } + /** Instance mode: what to redeem. */ + | { kind: 'code'; code: string; verifier: string } | { kind: 'declined' } + | { kind: 'invalid' } + | { kind: 'policy' } | { kind: 'cancelled' } + | { kind: 'timeout' } + | { kind: 'no_browser' } | { kind: 'failed'; error: string }; interface DesktopOAuthAnswer { authorization_endpoint: string; client_id: string; scope: string; + issuer?: string; + use_scheme?: boolean; } +let controls: DesktopBrowserSignInControls | null = null; +let claimedFrom: unknown; +let currentFlow: string | null = null; + +/** Before any frame exists. Whoever comes after this gets nothing from the preload. */ +export function claimBrowserSignIn(): DesktopBrowserSignInControls | null { + const bridge = getDesktopBridge(); + if (claimedFrom !== bridge) { + claimedFrom = bridge; + controls = bridge?.auth?.claim?.() ?? null; + } + return controls; +} + +/** Whether this page offers it. In a browser there's no bridge, and Lite has no server to park on. */ export function browserSignInAvailable(): boolean { - return !!getDesktopBridge()?.auth; + return !IS_LITE && !!claimBrowserSignIn() && desktopPolicyValue('BrowserSignIn') === true; } +/** The Cancel button, and leaving the page. */ +export function cancelBrowserSignIn(): void { + if (currentFlow) controls?.cancel(currentFlow); + currentFlow = null; +} + +function failure(error: string): DesktopBrowserSignInOutcome { + if (error === 'cancelled') return { kind: 'cancelled' }; + if (error === 'timeout') return { kind: 'timeout' }; + if (error === 'no_browser') return { kind: 'no_browser' }; + if (error === 'policy') return { kind: 'policy' }; + if (error === 'declined') return { kind: 'declined' }; + if (error === 'invalid') return { kind: 'invalid' }; + return { kind: 'failed', error }; +} + +/** Instance mode. The caller redeems the code (loginWithDesktopHandoff in the auth store). */ +export async function runInstanceBrowserSignIn(options: { base: string; locale: string; fresh: boolean }): Promise { + const auth = claimBrowserSignIn(); + if (!auth) return { kind: 'failed', error: 'unavailable' }; + const begun = await auth.begin({ kind: 'instance' }); + if (!begun.ok) return failure(begun.error); + currentFlow = begun.flowId; + try { + const verifier = generateCodeVerifier(); + const url = new URL(`${options.base}/${options.locale}/login`); + url.searchParams.set('mobile_redirect_uri', begun.redirectUri); + url.searchParams.set('mobile_state', begun.state); + url.searchParams.set('mobile_code_challenge', await generateCodeChallenge(verifier)); + if (options.fresh) url.searchParams.set('fresh_login', '1'); + const result = await auth.complete(begun.flowId, url.toString()); + if (!result.ok) return failure(result.error); + return { kind: 'code', code: result.code, verifier }; + } catch (error) { + auth.cancel(begun.flowId); + return { kind: 'failed', error: error instanceof Error ? error.name : 'error' }; + } finally { + currentFlow = null; + } +} + +/** The page main serves: each post goes through the app's own login, until one works. */ +async function runPasswordPage( + auth: DesktopBrowserSignInControls, + flowId: string, + tryPassword: (attempt: Extract) => Promise, +): Promise { + const started = await auth.beginPassword(flowId); + if (!started.ok) return failure(started.error); + for (;;) { + const attempt = await auth.nextPassword(flowId); + if (!attempt.ok) return attempt.error === 'done' ? { kind: 'signed-in' } : failure(attempt.error); + const answer = await tryPassword(attempt); + auth.answerPassword(flowId, answer); + if (answer.ok) { + const ended = await auth.outcome(flowId); + return ended.ok ? { kind: 'signed-in' } : failure(ended.error); + } + } +} + +/** Standalone. Only referenced from behind the desktop build's flag, so no other bundle holds the route. */ export async function runDesktopBrowserSignIn(options: { serverUrl: string; - callbackPath: string; slot: number; remember: boolean; addAccount: boolean; + fresh: boolean; + /** Redeems the code: loginWithOAuth in the auth store. */ + redeem: (serverUrl: string, code: string, verifier: string, redirectUri: string) => Promise; + tryPassword: (attempt: Extract) => Promise; }): Promise { - const bridge = getDesktopBridge(); - if (!bridge?.auth) return { kind: 'unavailable' }; - const { serverUrl, callbackPath, slot, remember, addAccount } = options; + const auth = claimBrowserSignIn(); + if (!auth) return { kind: 'failed', error: 'unavailable' }; + const { serverUrl, slot, remember, addAccount, fresh, redeem, tryPassword } = options; - const prepared = await bridge.servers?.prepare(serverUrl); - if (prepared && !prepared.ok) return { kind: 'declined' }; - - const { flowId, redirectUri } = await bridge.auth.beginBrowserSignIn(); + const begun = await auth.begin({ kind: 'oauth', serverUrl }); + if (!begun.ok) return failure(begun.error); + const { flowId } = begun; + currentFlow = flowId; try { const res = await apiFetch('/api/auth/desktop-oauth', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ serverUrl, redirectUri }), + body: JSON.stringify({ serverUrl, redirectUri: begun.redirectUri }), }); + if (res.status === 404) { + const body = (await res.json().catch(() => null)) as { error?: string } | null; + if (body?.error === 'no_oauth') return await runPasswordPage(auth, flowId, tryPassword); + } if (!res.ok) { - bridge.auth.cancelBrowserSignIn(flowId); - return { kind: 'unavailable' }; + auth.cancel(flowId); + return { kind: 'failed', error: 'discovery' }; } const answer = (await res.json()) as DesktopOAuthAnswer; + let redirectUri = begun.redirectUri; + if (answer.use_scheme) { + const scheme = await auth.useScheme(flowId); + if (!scheme) { + auth.cancel(flowId); + return { kind: 'failed', error: 'scheme' }; + } + redirectUri = scheme; + } const verifier = generateCodeVerifier(); - const challenge = await generateCodeChallenge(verifier); - const state = generateState(); - const authorizeUrl = new URL(answer.authorization_endpoint); authorizeUrl.searchParams.set('response_type', 'code'); authorizeUrl.searchParams.set('client_id', answer.client_id); authorizeUrl.searchParams.set('redirect_uri', redirectUri); authorizeUrl.searchParams.set('scope', answer.scope); - authorizeUrl.searchParams.set('state', state); - authorizeUrl.searchParams.set('code_challenge', challenge); + authorizeUrl.searchParams.set('state', begun.state); + authorizeUrl.searchParams.set('code_challenge', await generateCodeChallenge(verifier)); authorizeUrl.searchParams.set('code_challenge_method', 'S256'); if (addAccount) authorizeUrl.searchParams.set('prompt', 'select_account'); + if (fresh) authorizeUrl.searchParams.set('prompt', 'login'); - const result = await bridge.auth.completeBrowserSignIn(flowId, authorizeUrl.toString()); - if (!result.ok) { - return result.error === 'cancelled' ? { kind: 'cancelled' } : { kind: 'failed', error: result.error }; - } - if (result.state !== state) return { kind: 'failed', error: 'state_mismatch' }; + const result = await auth.complete(flowId, authorizeUrl.toString()); + if (!result.ok) return failure(result.error); + // RFC 9207: the answer names who issued it. Main has already checked the state. + if (result.iss && answer.issuer && result.iss !== answer.issuer) return { kind: 'failed', error: 'issuer_mismatch' }; - // What the callback page expects from a same-window flow, plus the two - // values only this flow has. - sessionStorage.setItem('oauth_code_verifier', verifier); - sessionStorage.setItem('oauth_state', state); - sessionStorage.setItem('oauth_server_url', serverUrl); - sessionStorage.removeItem('oauth_server_id'); + // What the auth store's exchange reads. The code never goes near an address bar. sessionStorage.setItem('oauth_remember', String(remember)); sessionStorage.setItem('oauth_cookie_slot', String(slot)); - sessionStorage.setItem(DESKTOP_REDIRECT_URI_KEY, redirectUri); sessionStorage.setItem(DESKTOP_CLIENT_ID_KEY, answer.client_id); - if (addAccount) sessionStorage.setItem('oauth_add_account_mode', 'true'); - - const query = new URLSearchParams({ code: result.code, state: result.state }); - return { kind: 'callback', callbackUrl: `${callbackPath}?${query}` }; + try { + return (await redeem(serverUrl, result.code, verifier, redirectUri)) ? { kind: 'signed-in' } : { kind: 'failed', error: 'exchange' }; + } finally { + sessionStorage.removeItem(DESKTOP_CLIENT_ID_KEY); + } } catch (error) { - bridge.auth.cancelBrowserSignIn(flowId); - return { kind: 'failed', error: error instanceof Error ? error.message : String(error) }; + auth.cancel(flowId); + return { kind: 'failed', error: error instanceof Error ? error.name : 'error' }; + } finally { + currentFlow = null; } } diff --git a/lib/desktop/languages.ts b/lib/desktop/languages.ts index aabfdeb01..5ac64fd54 100644 --- a/lib/desktop/languages.ts +++ b/lib/desktop/languages.ts @@ -42,6 +42,18 @@ export function noteComposerLanguage(key: string, language: string | null): void export function shellLabels(t: (key: string, values?: Record) => string): Record { return { ...updateLabels(t), + 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'), + 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'), + signInPassword: t('desktop_browser_sign_in.page_password'), + signInCode: t('desktop_browser_sign_in.page_code'), + signInSubmit: t('desktop_browser_sign_in.page_submit'), + signInWrongPassword: t('desktop_browser_sign_in.page_wrong_password'), + signInCodeNeeded: t('desktop_browser_sign_in.page_code_needed'), + signInNoAnswer: t('desktop_browser_sign_in.page_no_answer'), menuFile: t('desktopUi.menu.file'), menuEdit: t('desktopUi.menu.edit'), menuView: t('desktopUi.menu.view'), diff --git a/lib/desktop/policy-schema.ts b/lib/desktop/policy-schema.ts index ee00aec1f..56cd696c6 100644 --- a/lib/desktop/policy-schema.ts +++ b/lib/desktop/policy-schema.ts @@ -76,6 +76,7 @@ export interface PolicyValues { AuthNegotiateDelegateAllowlist: string | null; AutoSelectCertificateForUrls: CertificateRule[]; KeystoreAllowedOrigins: string[]; + BrowserSignIn: boolean; WipeOfflineData: string | null; } @@ -384,6 +385,18 @@ export const POLICY_SCHEMA: Record = { de: 'Die Bulwark-Server, nach https-Adresse, deren Plugins mit den Zertifikaten im Speicher des Betriebssystems signieren und entschlüsseln dürfen, ohne dass der Benutzer für jede Website gefragt wird. Eine pro Zeile.', }, }, + BrowserSignIn: { + category: 'signIn', + type: 'boolean', + default: true, + onInvalid: false, + sample: true, + title: { en: 'Offer sign-in through the browser', de: 'Anmeldung über den Browser anbieten' }, + description: { + en: 'When enabled or not configured, the login page offers "Sign in with your browser", so people can use their password manager, passkeys and your single sign-on there. When disabled, the button is gone and the app refuses the flow. The form in the app stays, unless the server only allows OAuth.', + de: 'Wenn aktiviert oder nicht konfiguriert, bietet die Anmeldeseite „Mit Ihrem Browser anmelden“ an, damit Benutzer dort ihren Passwort-Manager, Passkeys und Ihr Single Sign-on verwenden können. Wenn deaktiviert, fehlt die Schaltfläche und die App lehnt den Vorgang ab. Das Formular in der App bleibt, sofern der Server nicht nur OAuth erlaubt.', + }, + }, WipeOfflineData: { category: 'security', type: 'string', @@ -828,6 +841,7 @@ export const POLICY_CONSUMERS: Record = { QuickComposeShortcut: { pendingConsumer: 'step 7, quick compose' }, AutoSelectCertificateForUrls: { pendingConsumer: 'step 7, client certificates' }, KeystoreAllowedOrigins: { repo: 'shell', file: 'src/main/features/policies.ts' }, + BrowserSignIn: { repo: 'shell', file: 'src/main/features/browser-sign-in.ts' }, }; /** The part the embedded server enforces. Sent to it by message. */ diff --git a/lib/desktop/types.ts b/lib/desktop/types.ts index a8331c347..6210884eb 100644 --- a/lib/desktop/types.ts +++ b/lib/desktop/types.ts @@ -188,16 +188,46 @@ export interface DesktopLifecycleBridge { onFlushRequest: (handler: () => Promise) => () => void; } -export type DesktopBrowserSignInResult = - | { ok: true; code: string; state: string } +/** Standalone: a mail server's own OAuth. Instance: the instance's own login page. */ +export type DesktopBrowserSignInRequest = { kind: 'oauth'; serverUrl: string } | { kind: 'instance' }; + +export type DesktopBrowserSignInBegin = + | { ok: true; flowId: string; redirectUri: string; state: string } | { ok: false; error: string }; +export type DesktopBrowserSignInResult = + | { ok: true; code: string; state: string; iss?: string } + | { ok: false; error: string }; + +export type DesktopPasswordSignInStart = { ok: true; host: string } | { ok: false; error: string }; + +export type DesktopPasswordSignInAttempt = + | { ok: true; username: string; password: string; totp?: string } + | { ok: false; error: string }; + +export type DesktopPasswordSignInAnswer = + | { ok: true } + | { ok: false; error: 'invalid_credentials' | 'totp_required' | 'other' }; + +/** Sign-in through the system browser. See lib/desktop/browser-sign-in.ts. */ +export interface DesktopBrowserSignInControls { + /** A short-lived loopback listener for one sign-in. Only from a click. */ + begin: (request: DesktopBrowserSignInRequest) => Promise; + /** Opens the system browser on `url` and waits for the redirect. */ + complete: (flowId: string, url: string) => Promise; + /** The server refused loopback and took the `bulwark:` scheme. */ + useScheme: (flowId: string) => Promise; + cancel: (flowId: string) => void; + /** The server has no OAuth: a page main serves on a stable loopback port. */ + beginPassword: (flowId: string) => Promise; + nextPassword: (flowId: string) => Promise; + answerPassword: (flowId: string, answer: DesktopPasswordSignInAnswer) => void; + outcome: (flowId: string) => Promise; +} + export interface DesktopAuthBridge { - /** Starts a short-lived loopback listener for one sign-in. */ - beginBrowserSignIn: () => Promise<{ flowId: string; redirectUri: string }>; - /** Opens the system browser on `authorizeUrl` and waits for the redirect. */ - completeBrowserSignIn: (flowId: string, authorizeUrl: string) => Promise; - cancelBrowserSignIn: (flowId: string) => void; + /** Once per document, in the first render: a same-origin frame can reach this bridge. */ + claim: () => DesktopBrowserSignInControls | null; } export type DesktopPluginInstallResult = diff --git a/lib/oauth/discovery.ts b/lib/oauth/discovery.ts index e4964d459..838ed69f9 100644 --- a/lib/oauth/discovery.ts +++ b/lib/oauth/discovery.ts @@ -5,6 +5,7 @@ export interface OAuthMetadata { revocation_endpoint?: string; end_session_endpoint?: string; scopes_supported?: string[]; + registration_endpoint?: string; } // Validates that a discovered endpoint URL is safe to follow. Server-side diff --git a/locales/ar/common.json b/locales/ar/common.json index c759d9601..7056ea342 100644 --- a/locales/ar/common.json +++ b/locales/ar/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "محاولات كثيرة جدًا. حاول بعد {count, plural, zero {# دقيقة} one {دقيقة واحدة} two {دقيقتين} few {# دقائق} many {# دقيقة} other {# دقيقة}}." }, "desktop_sign_in": { - "browser_button": "سجّل الدخول باستخدام المتصفح", - "browser_waiting": "أكمل تسجيل الدخول في المتصفح", - "browser_unavailable": "لا يتيح هذا الخادم تسجيل الدخول عبر المتصفح. استخدم كلمة المرور بدلًا من ذلك.", - "browser_failed": "لم ينجح تسجيل الدخول عبر المتصفح. حاول مرة أخرى.", "server_needed": "أدخل عنوان الخادم أولًا.", "server_declined": "لم تسمح بهذا الخادم، لذا لم يُرسل إليه أي شيء.", "server_invalid": "عنوان الخادم هذا غير صالح." }, + "desktop_browser_sign_in": { + "button": "تسجيل الدخول عبر المتصفح…", + "waiting": "في انتظار المتصفح…", + "waiting_hint": "أكمل تسجيل الدخول هناك. يعمل مدير كلمات المرور لديك في المتصفح.", + "cancel": "إلغاء", + "or_here": "أو سجّل الدخول هنا", + "timed_out": "استغرق تسجيل الدخول في المتصفح وقتًا طويلًا. حاول مرة أخرى.", + "no_browser": "تعذر على Bulwark فتح المتصفح. حاول مرة أخرى أو سجّل الدخول هنا.", + "failed": "تعذر تسجيل الدخول عبر المتصفح. حاول مرة أخرى.", + "handoff_banner": "أنت تسجّل الدخول إلى تطبيق Bulwark على هذا الكمبيوتر. يبقى هذا المتصفح خارج Bulwark.", + "consent_title": "هل تريد تسجيل الدخول إلى تطبيق Bulwark؟", + "consent_description": "سيذهب تسجيل دخول {username} إلى تطبيق Bulwark على هذا الكمبيوتر. تابع فقط إذا بدأت ذلك من التطبيق.", + "consent_confirm": "تسجيل الدخول إلى التطبيق", + "consent_cancel": "ليس الآن", + "page_done": "يمكنك إغلاق علامة التبويب هذه والعودة إلى Bulwark.", + "page_failed": "تعذر تسجيل الدخول. عد إلى Bulwark وحاول مرة أخرى.", + "page_link_used": "يعمل هذا الرابط مرة واحدة فقط. عد إلى Bulwark وابدأ من جديد.", + "page_title": "تسجيل الدخول إلى {server}", + "page_intro": "هذه الصفحة من تطبيق Bulwark على هذا الكمبيوتر. تذهب كلمة مرورك إلى {server} فقط.", + "page_username": "عنوان البريد الإلكتروني أو اسم المستخدم", + "page_password": "كلمة المرور", + "page_code": "رمز المصادقة الثنائية", + "page_submit": "تسجيل الدخول", + "page_wrong_password": "لم يقبل الخادم اسم المستخدم وكلمة المرور هذين.", + "page_code_needed": "يحتاج هذا الحساب أيضًا إلى رمز المصادقة الثنائية. أدخل كلمة المرور مرة أخرى والرمز.", + "page_no_answer": "تعذر على Bulwark تسجيل الدخول. تحقق من إمكانية الوصول إلى الخادم وحاول مرة أخرى." + }, "desktop_updates": { "title": "التحديثات", "version_label": "Bulwark {version}", diff --git a/locales/ca/common.json b/locales/ca/common.json index 9ca9c8032..1233b4210 100644 --- a/locales/ca/common.json +++ b/locales/ca/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Massa intents. Torneu-ho a provar d'aquí a {count, plural, one {# minut} other {# minuts}}." }, "desktop_sign_in": { - "browser_button": "Inicia la sessió amb el navegador", - "browser_waiting": "Acaba d'iniciar la sessió al navegador", - "browser_unavailable": "Aquest servidor no permet iniciar la sessió amb el navegador. Fes servir la contrasenya.", - "browser_failed": "No s'ha pogut iniciar la sessió amb el navegador. Torna-ho a provar.", "server_needed": "Primer escriu l'adreça del servidor.", "server_declined": "No has permès aquest servidor, així que no s'hi ha enviat res.", "server_invalid": "Aquesta adreça de servidor no és vàlida." }, + "desktop_browser_sign_in": { + "button": "Inicia la sessió amb el navegador…", + "waiting": "S’està esperant el navegador…", + "waiting_hint": "Acaba d’iniciar la sessió allà. El teu gestor de contrasenyes funciona al navegador.", + "cancel": "Cancel·la", + "or_here": "o inicia la sessió aquí", + "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.", + "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_confirm": "Inicia la sessió a l’aplicació", + "consent_cancel": "Ara no", + "page_done": "Pots tancar aquesta pestanya i tornar a Bulwark.", + "page_failed": "No s’ha pogut iniciar la sessió. Torna a Bulwark i torna-ho a provar.", + "page_link_used": "Aquest enllaç només funciona una vegada. Torna a Bulwark i comença de nou.", + "page_title": "Inicia la sessió a {server}", + "page_intro": "Aquesta pàgina ve de l’aplicació Bulwark d’aquest ordinador. La teva contrasenya va a {server} i enlloc més.", + "page_username": "Adreça electrònica o nom d’usuari", + "page_password": "Contrasenya", + "page_code": "Codi de dos factors", + "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." + }, "desktop_updates": { "title": "Actualitzacions", "version_label": "Bulwark {version}", diff --git a/locales/cs/common.json b/locales/cs/common.json index 5585c00c0..1500c1ee9 100644 --- a/locales/cs/common.json +++ b/locales/cs/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Příliš mnoho pokusů. Zkuste to za {count, plural, one {# minutu} few {# minuty} many {# minuty} other {# minut}}." }, "desktop_sign_in": { - "browser_button": "Přihlásit se v prohlížeči", - "browser_waiting": "Dokončete přihlášení v prohlížeči", - "browser_unavailable": "Tento server přihlášení přes prohlížeč nenabízí. Použijte heslo.", - "browser_failed": "Přihlášení přes prohlížeč se nezdařilo. Zkuste to znovu.", "server_needed": "Nejdřív zadejte adresu serveru.", "server_declined": "Tento server jste nepovolili, proto se na něj nic neodeslalo.", "server_invalid": "Tato adresa serveru není platná." }, + "desktop_browser_sign_in": { + "button": "Přihlásit se v prohlížeči…", + "waiting": "Čekání na prohlížeč…", + "waiting_hint": "Dokončete přihlášení tam. Váš správce hesel funguje v prohlížeči.", + "cancel": "Zrušit", + "or_here": "nebo se přihlaste zde", + "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ý.", + "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_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.", + "page_failed": "Přihlášení se nezdařilo. Vraťte se do Bulwarku a zkuste to znovu.", + "page_link_used": "Tento odkaz funguje jen jednou. Vraťte se do Bulwarku a začněte znovu.", + "page_title": "Přihlásit se k {server}", + "page_intro": "Tato stránka pochází z aplikace Bulwark v tomto počítači. Vaše heslo jde na {server} a nikam jinam.", + "page_username": "E-mailová adresa nebo uživatelské jméno", + "page_password": "Heslo", + "page_code": "Dvoufázový kód", + "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." + }, "desktop_updates": { "title": "Aktualizace", "version_label": "Bulwark {version}", diff --git a/locales/da/common.json b/locales/da/common.json index 9fa9629c6..3ad6140e1 100644 --- a/locales/da/common.json +++ b/locales/da/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "For mange forsøg. Prøv igen om {count, plural, one {# minut} other {# minutter}}." }, "desktop_sign_in": { - "browser_button": "Log ind med din browser", - "browser_waiting": "Gør login færdigt i din browser", - "browser_unavailable": "Denne server tilbyder ikke login via browser. Brug din adgangskode i stedet.", - "browser_failed": "Login via browseren lykkedes ikke. Prøv igen.", "server_needed": "Angiv først serverens adresse.", "server_declined": "Du tillod ikke denne server, så der blev ikke sendt noget til den.", "server_invalid": "Denne serveradresse er ikke gyldig." }, + "desktop_browser_sign_in": { + "button": "Log ind med din browser…", + "waiting": "Venter på din browser…", + "waiting_hint": "Afslut login der. Din adgangskodeadministrator virker i din browser.", + "cancel": "Annuller", + "or_here": "eller log ind her", + "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.", + "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_confirm": "Log ind i appen", + "consent_cancel": "Ikke nu", + "page_done": "Du kan lukke denne fane og gå tilbage til Bulwark.", + "page_failed": "Login lykkedes ikke. Gå tilbage til Bulwark, og prøv igen.", + "page_link_used": "Dette link virker kun én gang. Gå tilbage til Bulwark, og start forfra.", + "page_title": "Log ind på {server}", + "page_intro": "Denne side kommer fra Bulwark-appen på denne computer. Din adgangskode går til {server} og ingen andre steder.", + "page_username": "E-mailadresse eller brugernavn", + "page_password": "Adgangskode", + "page_code": "Tofaktorkode", + "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." + }, "desktop_updates": { "title": "Opdateringer", "version_label": "Bulwark {version}", diff --git a/locales/de/common.json b/locales/de/common.json index d1bc0fa61..bea4623ee 100644 --- a/locales/de/common.json +++ b/locales/de/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Zu viele Versuche. Versuchen Sie es in {count, plural, one {# Minute} other {# Minuten}} noch einmal." }, "desktop_sign_in": { - "browser_button": "Mit dem Browser anmelden", - "browser_waiting": "Schließen Sie die Anmeldung im Browser ab", - "browser_unavailable": "Dieser Server bietet keine Anmeldung über den Browser an. Verwenden Sie stattdessen Ihr Passwort.", - "browser_failed": "Die Anmeldung über den Browser hat nicht geklappt. Versuchen Sie es noch einmal.", "server_needed": "Geben Sie zuerst die Adresse Ihres Servers ein.", "server_declined": "Sie haben diesen Server nicht zugelassen, daher wurde nichts an ihn gesendet.", "server_invalid": "Diese Serveradresse ist ungültig." }, + "desktop_browser_sign_in": { + "button": "Mit Ihrem Browser anmelden…", + "waiting": "Warten auf Ihren Browser…", + "waiting_hint": "Schließen Sie die Anmeldung dort ab. Ihr Passwort-Manager funktioniert in Ihrem Browser.", + "cancel": "Abbrechen", + "or_here": "oder hier anmelden", + "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.", + "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_confirm": "Bei der App anmelden", + "consent_cancel": "Jetzt nicht", + "page_done": "Sie können diesen Tab schließen und zu Bulwark zurückkehren.", + "page_failed": "Die Anmeldung hat nicht geklappt. Gehen Sie zurück zu Bulwark und versuchen Sie es noch einmal.", + "page_link_used": "Dieser Link funktioniert nur einmal. Gehen Sie zurück zu Bulwark und beginnen Sie neu.", + "page_title": "Bei {server} anmelden", + "page_intro": "Diese Seite kommt von der Bulwark-App auf diesem Computer. Ihr Passwort geht an {server} und sonst nirgendwohin.", + "page_username": "E-Mail-Adresse oder Benutzername", + "page_password": "Passwort", + "page_code": "Zwei-Faktor-Code", + "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." + }, "desktop_updates": { "title": "Updates", "version_label": "Bulwark {version}", diff --git a/locales/en/common.json b/locales/en/common.json index b7b372d47..7b3845242 100644 --- a/locales/en/common.json +++ b/locales/en/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Too many tries. Try again in {count, plural, one {# minute} other {# minutes}}." }, "desktop_sign_in": { - "browser_button": "Sign in with your browser", - "browser_waiting": "Finish signing in in your browser", - "browser_unavailable": "This server doesn't offer sign-in through a browser. Use your password instead.", - "browser_failed": "Signing in through your browser didn't work. Try again.", "server_needed": "Enter your server's address first.", "server_declined": "You didn't allow this server, so nothing was sent to it.", "server_invalid": "This server address isn't valid." }, + "desktop_browser_sign_in": { + "button": "Sign in with your browser…", + "waiting": "Waiting for your browser…", + "waiting_hint": "Finish signing in there. Your password manager works in your browser.", + "cancel": "Cancel", + "or_here": "or sign in here", + "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.", + "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_confirm": "Sign in to the app", + "consent_cancel": "Not now", + "page_done": "You can close this tab and go back to Bulwark.", + "page_failed": "Signing in did not work. Go back to Bulwark and try again.", + "page_link_used": "This link only works once. Go back to Bulwark and start again.", + "page_title": "Sign in to {server}", + "page_intro": "This page comes from the Bulwark app on this computer. Your password goes to {server} and nowhere else.", + "page_username": "Email address or username", + "page_password": "Password", + "page_code": "Two-factor code", + "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." + }, "desktop_updates": { "title": "Updates", "version_label": "Bulwark {version}", diff --git a/locales/es/common.json b/locales/es/common.json index a6af887c6..a2689936d 100644 --- a/locales/es/common.json +++ b/locales/es/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Demasiados intentos. Inténtelo de nuevo en {count, plural, one {# minuto} other {# minutos}}." }, "desktop_sign_in": { - "browser_button": "Iniciar sesión con el navegador", - "browser_waiting": "Termina de iniciar sesión en el navegador", - "browser_unavailable": "Este servidor no permite iniciar sesión con el navegador. Usa tu contraseña.", - "browser_failed": "No se pudo iniciar sesión con el navegador. Inténtalo de nuevo.", "server_needed": "Primero escribe la dirección del servidor.", "server_declined": "No permitiste este servidor, así que no se le envió nada.", "server_invalid": "Esta dirección de servidor no es válida." }, + "desktop_browser_sign_in": { + "button": "Iniciar sesión con tu navegador…", + "waiting": "Esperando a tu navegador…", + "waiting_hint": "Termina de iniciar sesión allí. Tu gestor de contraseñas funciona en tu navegador.", + "cancel": "Cancelar", + "or_here": "o inicia sesión aquí", + "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.", + "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_confirm": "Iniciar sesión en la aplicación", + "consent_cancel": "Ahora no", + "page_done": "Puedes cerrar esta pestaña y volver a Bulwark.", + "page_failed": "No se pudo iniciar sesión. Vuelve a Bulwark e inténtalo de nuevo.", + "page_link_used": "Este enlace solo funciona una vez. Vuelve a Bulwark y empieza de nuevo.", + "page_title": "Iniciar sesión en {server}", + "page_intro": "Esta página viene de la aplicación Bulwark de este ordenador. Tu contraseña va a {server} y a ningún otro sitio.", + "page_username": "Correo electrónico o nombre de usuario", + "page_password": "Contraseña", + "page_code": "Código de dos factores", + "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." + }, "desktop_updates": { "title": "Actualizaciones", "version_label": "Bulwark {version}", diff --git a/locales/et/common.json b/locales/et/common.json index 303262a33..df399900f 100644 --- a/locales/et/common.json +++ b/locales/et/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Liiga palju katseid. Proovige uuesti {count, plural, one {# minuti} other {# minuti}} pärast." }, "desktop_sign_in": { - "browser_button": "Logi sisse brauseriga", - "browser_waiting": "Lõpeta sisselogimine brauseris", - "browser_unavailable": "See server ei paku brauseri kaudu sisselogimist. Kasuta parooli.", - "browser_failed": "Brauseri kaudu sisselogimine ei õnnestunud. Proovi uuesti.", "server_needed": "Sisesta kõigepealt serveri aadress.", "server_declined": "Sa ei lubanud seda serverit, nii et sellele ei saadetud midagi.", "server_invalid": "See serveri aadress ei kehti." }, + "desktop_browser_sign_in": { + "button": "Logi sisse brauseriga…", + "waiting": "Ootan brauserit…", + "waiting_hint": "Lõpeta sisselogimine seal. Sinu paroolihaldur töötab brauseris.", + "cancel": "Tühista", + "or_here": "või logi sisse siin", + "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.", + "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_confirm": "Logi rakendusse sisse", + "consent_cancel": "Mitte praegu", + "page_done": "Võid selle vahelehe sulgeda ja Bulwarki naasta.", + "page_failed": "Sisselogimine ei õnnestunud. Mine tagasi Bulwarki ja proovi uuesti.", + "page_link_used": "See link töötab ainult üks kord. Mine tagasi Bulwarki ja alusta uuesti.", + "page_title": "Logi sisse serverisse {server}", + "page_intro": "See leht tuleb selle arvuti Bulwarki rakendusest. Sinu parool läheb serverisse {server} ja mitte kuhugi mujale.", + "page_username": "E-posti aadress või kasutajanimi", + "page_password": "Parool", + "page_code": "Kaheastmelise kinnituse kood", + "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." + }, "desktop_updates": { "title": "Uuendused", "version_label": "Bulwark {version}", diff --git a/locales/fa/common.json b/locales/fa/common.json index 9a1f39794..87630c870 100644 --- a/locales/fa/common.json +++ b/locales/fa/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "تلاش‌های زیاد. {count, plural, one {# دقیقه} other {# دقیقه}} دیگر دوباره تلاش کنید." }, "desktop_sign_in": { - "browser_button": "ورود با مرورگر", - "browser_waiting": "ورود را در مرورگر کامل کنید", - "browser_unavailable": "این سرور ورود از طریق مرورگر را ارائه نمی‌دهد. از گذرواژه خود استفاده کنید.", - "browser_failed": "ورود از طریق مرورگر انجام نشد. دوباره تلاش کنید.", "server_needed": "ابتدا نشانی سرور را وارد کنید.", "server_declined": "شما این سرور را مجاز نکردید، پس چیزی به آن فرستاده نشد.", "server_invalid": "این نشانی سرور معتبر نیست." }, + "desktop_browser_sign_in": { + "button": "ورود با مرورگر…", + "waiting": "در انتظار مرورگر…", + "waiting_hint": "ورود را همان‌جا کامل کنید. مدیر گذرواژه شما در مرورگر کار می‌کند.", + "cancel": "لغو", + "or_here": "یا اینجا وارد شوید", + "timed_out": "ورود در مرورگر بیش از حد طول کشید. دوباره تلاش کنید.", + "no_browser": "Bulwark نتوانست مرورگر را باز کند. دوباره تلاش کنید یا اینجا وارد شوید.", + "failed": "ورود از طریق مرورگر انجام نشد. دوباره تلاش کنید.", + "handoff_banner": "شما در حال ورود به برنامه Bulwark روی این رایانه هستید. این مرورگر همچنان از Bulwark خارج می‌ماند.", + "consent_title": "به برنامه Bulwark وارد می‌شوید؟", + "consent_description": "ورود {username} به برنامه Bulwark روی این رایانه می‌رود. فقط اگر این کار را از برنامه شروع کرده‌اید ادامه دهید.", + "consent_confirm": "ورود به برنامه", + "consent_cancel": "اکنون نه", + "page_done": "می‌توانید این زبانه را ببندید و به Bulwark برگردید.", + "page_failed": "ورود انجام نشد. به Bulwark برگردید و دوباره تلاش کنید.", + "page_link_used": "این پیوند فقط یک بار کار می‌کند. به Bulwark برگردید و از نو شروع کنید.", + "page_title": "ورود به {server}", + "page_intro": "این صفحه از برنامه Bulwark روی این رایانه می‌آید. گذرواژه شما فقط به {server} می‌رود.", + "page_username": "نشانی ایمیل یا نام کاربری", + "page_password": "گذرواژه", + "page_code": "کد دومرحله‌ای", + "page_submit": "ورود", + "page_wrong_password": "سرور این نام کاربری و گذرواژه را نپذیرفت.", + "page_code_needed": "این حساب به کد دومرحله‌ای هم نیاز دارد. گذرواژه و کد را دوباره وارد کنید.", + "page_no_answer": "Bulwark نتوانست وارد شود. بررسی کنید که سرور در دسترس باشد و دوباره تلاش کنید." + }, "desktop_updates": { "title": "به‌روزرسانی‌ها", "version_label": "Bulwark {version}", diff --git a/locales/fr/common.json b/locales/fr/common.json index fd43c5da3..98eca729d 100644 --- a/locales/fr/common.json +++ b/locales/fr/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Trop d'essais. Réessayez dans {count, plural, one {# minute} other {# minutes}}." }, "desktop_sign_in": { - "browser_button": "Se connecter avec le navigateur", - "browser_waiting": "Terminez la connexion dans votre navigateur", - "browser_unavailable": "Ce serveur ne propose pas la connexion par navigateur. Utilisez votre mot de passe.", - "browser_failed": "La connexion par navigateur a échoué. Réessayez.", "server_needed": "Saisissez d'abord l'adresse du serveur.", "server_declined": "Vous n'avez pas autorisé ce serveur, donc rien ne lui a été envoyé.", "server_invalid": "Cette adresse de serveur n'est pas valide." }, + "desktop_browser_sign_in": { + "button": "Se connecter avec votre navigateur…", + "waiting": "En attente de votre navigateur…", + "waiting_hint": "Terminez la connexion là-bas. Votre gestionnaire de mots de passe fonctionne dans votre navigateur.", + "cancel": "Annuler", + "or_here": "ou se connecter ici", + "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.", + "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_confirm": "Se connecter à l’application", + "consent_cancel": "Pas maintenant", + "page_done": "Vous pouvez fermer cet onglet et revenir à Bulwark.", + "page_failed": "La connexion n’a pas fonctionné. Revenez à Bulwark et réessayez.", + "page_link_used": "Ce lien ne fonctionne qu’une fois. Revenez à Bulwark et recommencez.", + "page_title": "Se connecter à {server}", + "page_intro": "Cette page vient de l’application Bulwark sur cet ordinateur. Votre mot de passe va à {server} et nulle part ailleurs.", + "page_username": "Adresse e-mail ou nom d’utilisateur", + "page_password": "Mot de passe", + "page_code": "Code à deux facteurs", + "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." + }, "desktop_updates": { "title": "Mises à jour", "version_label": "Bulwark {version}", diff --git a/locales/he/common.json b/locales/he/common.json index 10bb0aacf..1b4c23a1d 100644 --- a/locales/he/common.json +++ b/locales/he/common.json @@ -6874,14 +6874,37 @@ "blocked_minutes": "יותר מדי ניסיונות. נסו שוב בעוד {count, plural, one {דקה אחת} two {שתי דקות} other {# דקות}}." }, "desktop_sign_in": { - "browser_button": "כניסה באמצעות הדפדפן", - "browser_waiting": "יש להשלים את הכניסה בדפדפן", - "browser_unavailable": "השרת הזה לא מאפשר כניסה דרך דפדפן. יש להשתמש בסיסמה.", - "browser_failed": "הכניסה דרך הדפדפן לא הצליחה. כדאי לנסות שוב.", "server_needed": "קודם צריך להזין את כתובת השרת.", "server_declined": "לא אישרת את השרת הזה, לכן לא נשלח אליו דבר.", "server_invalid": "כתובת השרת הזו לא תקינה." }, + "desktop_browser_sign_in": { + "button": "התחברות דרך הדפדפן…", + "waiting": "ממתין לדפדפן…", + "waiting_hint": "סיימו את ההתחברות שם. מנהל הסיסמאות שלכם פועל בדפדפן.", + "cancel": "ביטול", + "or_here": "או התחברו כאן", + "timed_out": "ההתחברות בדפדפן נמשכה זמן רב מדי. נסו שוב.", + "no_browser": "Bulwark לא הצליח לפתוח את הדפדפן. נסו שוב או התחברו כאן.", + "failed": "ההתחברות דרך הדפדפן לא הצליחה. נסו שוב.", + "handoff_banner": "אתם מתחברים לאפליקציית Bulwark במחשב זה. הדפדפן הזה נשאר מנותק מ-Bulwark.", + "consent_title": "להתחבר לאפליקציית Bulwark?", + "consent_description": "ההתחברות של {username} תועבר לאפליקציית Bulwark במחשב זה. המשיכו רק אם התחלתם זאת מהאפליקציה.", + "consent_confirm": "התחברות לאפליקציה", + "consent_cancel": "לא עכשיו", + "page_done": "אפשר לסגור את הכרטיסייה הזו ולחזור ל-Bulwark.", + "page_failed": "ההתחברות לא הצליחה. חזרו ל-Bulwark ונסו שוב.", + "page_link_used": "הקישור הזה עובד פעם אחת בלבד. חזרו ל-Bulwark והתחילו מחדש.", + "page_title": "התחברות אל {server}", + "page_intro": "הדף הזה מגיע מאפליקציית Bulwark במחשב זה. הסיסמה שלכם נשלחת אל {server} בלבד.", + "page_username": "כתובת דוא״ל או שם משתמש", + "page_password": "סיסמה", + "page_code": "קוד אימות דו-שלבי", + "page_submit": "התחברות", + "page_wrong_password": "השרת לא קיבל את שם המשתמש והסיסמה האלה.", + "page_code_needed": "החשבון הזה צריך גם קוד אימות דו-שלבי. הזינו שוב את הסיסמה ואת הקוד.", + "page_no_answer": "Bulwark לא הצליח להתחבר. בדקו שהשרת זמין ונסו שוב." + }, "desktop_updates": { "title": "עדכונים", "version_label": "Bulwark {version}", diff --git a/locales/hu/common.json b/locales/hu/common.json index 50702f8fb..6b705a398 100644 --- a/locales/hu/common.json +++ b/locales/hu/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Túl sok próbálkozás. Próbálja újra {count, plural, one {# perc} other {# perc}} múlva." }, "desktop_sign_in": { - "browser_button": "Bejelentkezés böngészővel", - "browser_waiting": "Fejezze be a bejelentkezést a böngészőben", - "browser_unavailable": "Ez a szerver nem kínál böngészős bejelentkezést. Használja a jelszavát.", - "browser_failed": "A böngészős bejelentkezés nem sikerült. Próbálja újra.", "server_needed": "Először adja meg a szerver címét.", "server_declined": "Nem engedélyezte ezt a szervert, ezért semmit sem küldtünk neki.", "server_invalid": "Ez a szervercím nem érvényes." }, + "desktop_browser_sign_in": { + "button": "Bejelentkezés a böngészővel…", + "waiting": "Várakozás a böngészőre…", + "waiting_hint": "Fejezze be ott a bejelentkezést. A jelszókezelője a böngészőben működik.", + "cancel": "Mégse", + "or_here": "vagy jelentkezzen be itt", + "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.", + "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_confirm": "Bejelentkezés az alkalmazásba", + "consent_cancel": "Most nem", + "page_done": "Bezárhatja ezt a lapot, és visszatérhet a Bulwarkhoz.", + "page_failed": "A bejelentkezés nem sikerült. Térjen vissza a Bulwarkhoz, és próbálja újra.", + "page_link_used": "Ez a hivatkozás csak egyszer működik. Térjen vissza a Bulwarkhoz, és kezdje újra.", + "page_title": "Bejelentkezés ide: {server}", + "page_intro": "Ez az oldal a számítógépen lévő Bulwark alkalmazástól származik. A jelszava a(z) {server} szerverre kerül, és sehova máshova.", + "page_username": "E-mail-cím vagy felhasználónév", + "page_password": "Jelszó", + "page_code": "Kétfaktoros kód", + "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." + }, "desktop_updates": { "title": "Frissítések", "version_label": "Bulwark {version}", diff --git a/locales/it/common.json b/locales/it/common.json index 7ff4479d1..f5ef49881 100644 --- a/locales/it/common.json +++ b/locales/it/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Troppi tentativi. Riprova tra {count, plural, one {# minuto} other {# minuti}}." }, "desktop_sign_in": { - "browser_button": "Accedi con il browser", - "browser_waiting": "Completa l'accesso nel browser", - "browser_unavailable": "Questo server non offre l'accesso tramite browser. Usa la password.", - "browser_failed": "L'accesso tramite browser non è riuscito. Riprova.", "server_needed": "Inserisci prima l'indirizzo del server.", "server_declined": "Non hai autorizzato questo server, quindi non gli è stato inviato nulla.", "server_invalid": "Questo indirizzo del server non è valido." }, + "desktop_browser_sign_in": { + "button": "Accedi con il browser…", + "waiting": "In attesa del browser…", + "waiting_hint": "Completa l’accesso lì. Il tuo gestore di password funziona nel browser.", + "cancel": "Annulla", + "or_here": "oppure accedi qui", + "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.", + "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_confirm": "Accedi all’app", + "consent_cancel": "Non ora", + "page_done": "Puoi chiudere questa scheda e tornare a Bulwark.", + "page_failed": "L’accesso non è riuscito. Torna a Bulwark e riprova.", + "page_link_used": "Questo link funziona una sola volta. Torna a Bulwark e ricomincia.", + "page_title": "Accedi a {server}", + "page_intro": "Questa pagina viene dall’app Bulwark su questo computer. La tua password va a {server} e da nessun’altra parte.", + "page_username": "Indirizzo e-mail o nome utente", + "page_password": "Password", + "page_code": "Codice a due fattori", + "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." + }, "desktop_updates": { "title": "Aggiornamenti", "version_label": "Bulwark {version}", diff --git a/locales/ja/common.json b/locales/ja/common.json index 3eda5c005..43ad0ed7d 100644 --- a/locales/ja/common.json +++ b/locales/ja/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "試行回数が多すぎます。{count, plural, other {# 分}}後にもう一度お試しください。" }, "desktop_sign_in": { - "browser_button": "ブラウザでサインイン", - "browser_waiting": "ブラウザでサインインを完了してください", - "browser_unavailable": "このサーバーはブラウザでのサインインに対応していません。パスワードを使用してください。", - "browser_failed": "ブラウザでのサインインに失敗しました。もう一度お試しください。", "server_needed": "先にサーバーのアドレスを入力してください。", "server_declined": "このサーバーを許可しなかったため、何も送信していません。", "server_invalid": "このサーバーアドレスは正しくありません。" }, + "desktop_browser_sign_in": { + "button": "ブラウザーでサインイン…", + "waiting": "ブラウザーを待っています…", + "waiting_hint": "ブラウザーでサインインを完了してください。パスワードマネージャーはブラウザーで使えます。", + "cancel": "キャンセル", + "or_here": "またはここでサインイン", + "timed_out": "ブラウザーでのサインインに時間がかかりすぎました。もう一度お試しください。", + "no_browser": "Bulwark はブラウザーを開けませんでした。もう一度試すか、ここでサインインしてください。", + "failed": "ブラウザー経由でサインインできませんでした。もう一度お試しください。", + "handoff_banner": "このコンピューターの Bulwark アプリにサインインしています。このブラウザーは Bulwark にサインインしません。", + "consent_title": "Bulwark アプリにサインインしますか?", + "consent_description": "{username} のサインインは、このコンピューターの Bulwark アプリに渡されます。アプリから始めた場合のみ続行してください。", + "consent_confirm": "アプリにサインイン", + "consent_cancel": "今はしない", + "page_done": "このタブを閉じて Bulwark に戻れます。", + "page_failed": "サインインできませんでした。Bulwark に戻ってもう一度お試しください。", + "page_link_used": "このリンクは 1 回しか使えません。Bulwark に戻ってやり直してください。", + "page_title": "{server} にサインイン", + "page_intro": "このページは、このコンピューターの Bulwark アプリが表示しています。パスワードは {server} にだけ送られます。", + "page_username": "メールアドレスまたはユーザー名", + "page_password": "パスワード", + "page_code": "2 要素認証コード", + "page_submit": "サインイン", + "page_wrong_password": "サーバーはこのユーザー名とパスワードを受け付けませんでした。", + "page_code_needed": "このアカウントには 2 要素認証コードも必要です。パスワードをもう一度入力し、コードも入力してください。", + "page_no_answer": "Bulwark はサインインできませんでした。サーバーに接続できるか確認して、もう一度お試しください。" + }, "desktop_updates": { "title": "アップデート", "version_label": "Bulwark {version}", diff --git a/locales/ko/common.json b/locales/ko/common.json index 355bdbb3f..581f9040f 100644 --- a/locales/ko/common.json +++ b/locales/ko/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "시도 횟수가 너무 많습니다. {count, plural, other {#분}} 후에 다시 시도하세요." }, "desktop_sign_in": { - "browser_button": "브라우저로 로그인", - "browser_waiting": "브라우저에서 로그인을 마치세요", - "browser_unavailable": "이 서버는 브라우저 로그인을 지원하지 않습니다. 비밀번호를 사용하세요.", - "browser_failed": "브라우저 로그인에 실패했습니다. 다시 시도하세요.", "server_needed": "먼저 서버 주소를 입력하세요.", "server_declined": "이 서버를 허용하지 않아 아무것도 보내지 않았습니다.", "server_invalid": "이 서버 주소는 올바르지 않습니다." }, + "desktop_browser_sign_in": { + "button": "브라우저로 로그인…", + "waiting": "브라우저를 기다리는 중…", + "waiting_hint": "브라우저에서 로그인을 마치세요. 비밀번호 관리자는 브라우저에서 사용할 수 있습니다.", + "cancel": "취소", + "or_here": "또는 여기에서 로그인", + "timed_out": "브라우저 로그인이 너무 오래 걸렸습니다. 다시 시도하세요.", + "no_browser": "Bulwark에서 브라우저를 열 수 없습니다. 다시 시도하거나 여기에서 로그인하세요.", + "failed": "브라우저를 통한 로그인에 실패했습니다. 다시 시도하세요.", + "handoff_banner": "이 컴퓨터의 Bulwark 앱에 로그인하고 있습니다. 이 브라우저는 Bulwark에 로그인되지 않습니다.", + "consent_title": "Bulwark 앱에 로그인할까요?", + "consent_description": "{username}의 로그인 정보가 이 컴퓨터의 Bulwark 앱으로 전달됩니다. 앱에서 시작한 경우에만 계속하세요.", + "consent_confirm": "앱에 로그인", + "consent_cancel": "나중에", + "page_done": "이 탭을 닫고 Bulwark로 돌아가도 됩니다.", + "page_failed": "로그인에 실패했습니다. Bulwark로 돌아가서 다시 시도하세요.", + "page_link_used": "이 링크는 한 번만 작동합니다. Bulwark로 돌아가서 다시 시작하세요.", + "page_title": "{server}에 로그인", + "page_intro": "이 페이지는 이 컴퓨터의 Bulwark 앱에서 제공합니다. 비밀번호는 {server}로만 전송됩니다.", + "page_username": "이메일 주소 또는 사용자 이름", + "page_password": "비밀번호", + "page_code": "2단계 인증 코드", + "page_submit": "로그인", + "page_wrong_password": "서버가 이 사용자 이름과 비밀번호를 받아들이지 않았습니다.", + "page_code_needed": "이 계정에는 2단계 인증 코드도 필요합니다. 비밀번호와 코드를 다시 입력하세요.", + "page_no_answer": "Bulwark에서 로그인할 수 없습니다. 서버에 연결할 수 있는지 확인하고 다시 시도하세요." + }, "desktop_updates": { "title": "업데이트", "version_label": "Bulwark {version}", diff --git a/locales/lv/common.json b/locales/lv/common.json index 2f5d9e297..af602f92b 100644 --- a/locales/lv/common.json +++ b/locales/lv/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Pārāk daudz mēģinājumu. Mēģiniet vēlreiz pēc {count, plural, zero {# minūtēm} one {# minūtes} other {# minūtēm}}." }, "desktop_sign_in": { - "browser_button": "Pierakstīties ar pārlūku", - "browser_waiting": "Pabeidziet pierakstīšanos pārlūkā", - "browser_unavailable": "Šis serveris nepiedāvā pierakstīšanos ar pārlūku. Izmantojiet paroli.", - "browser_failed": "Pierakstīšanās ar pārlūku neizdevās. Mēģiniet vēlreiz.", "server_needed": "Vispirms ievadiet servera adresi.", "server_declined": "Jūs neatļāvāt šo serveri, tāpēc tam nekas netika nosūtīts.", "server_invalid": "Šī servera adrese nav derīga." }, + "desktop_browser_sign_in": { + "button": "Pieteikties ar pārlūku…", + "waiting": "Gaida pārlūku…", + "waiting_hint": "Pabeidziet pieteikšanos tur. Jūsu paroļu pārvaldnieks darbojas pārlūkā.", + "cancel": "Atcelt", + "or_here": "vai piesakieties šeit", + "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.", + "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_confirm": "Pieteikties lietotnē", + "consent_cancel": "Ne tagad", + "page_done": "Varat aizvērt šo cilni un atgriezties Bulwark.", + "page_failed": "Pieteikšanās neizdevās. Atgriezieties Bulwark un mēģiniet vēlreiz.", + "page_link_used": "Šī saite darbojas tikai vienreiz. Atgriezieties Bulwark un sāciet no jauna.", + "page_title": "Pieteikties serverī {server}", + "page_intro": "Šī lapa nāk no Bulwark lietotnes šajā datorā. Jūsu parole nonāk serverī {server} un nekur citur.", + "page_username": "E-pasta adrese vai lietotājvārds", + "page_password": "Parole", + "page_code": "Divu faktoru kods", + "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." + }, "desktop_updates": { "title": "Atjauninājumi", "version_label": "Bulwark {version}", diff --git a/locales/mn/common.json b/locales/mn/common.json index cf0de6ec1..33e883235 100644 --- a/locales/mn/common.json +++ b/locales/mn/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Хэт олон оролдлого. {count, plural, one {# минутын} other {# минутын}} дараа дахин оролдоно уу." }, "desktop_sign_in": { - "browser_button": "Хөтчөөр нэвтрэх", - "browser_waiting": "Нэвтрэлтээ хөтөч дээр дуусгана уу", - "browser_unavailable": "Энэ сервер хөтчөөр нэвтрэх боломжгүй. Нууц үгээ ашиглана уу.", - "browser_failed": "Хөтчөөр нэвтэрч чадсангүй. Дахин оролдоно уу.", "server_needed": "Эхлээд серверийн хаягаа оруулна уу.", "server_declined": "Та энэ серверийг зөвшөөрөөгүй тул юу ч илгээгээгүй.", "server_invalid": "Энэ серверийн хаяг буруу байна." }, + "desktop_browser_sign_in": { + "button": "Хөтчөөрөө нэвтрэх…", + "waiting": "Хөтчийг хүлээж байна…", + "waiting_hint": "Тэнд нэвтрэлтээ дуусгана уу. Таны нууц үгийн менежер хөтөч дээр ажиллана.", + "cancel": "Цуцлах", + "or_here": "эсвэл энд нэвтэрнэ үү", + "timed_out": "Хөтчөөр нэвтрэх хэт удаан үргэлжилсэн. Дахин оролдоно уу.", + "no_browser": "Bulwark хөтчийг нээж чадсангүй. Дахин оролдох эсвэл энд нэвтэрнэ үү.", + "failed": "Хөтчөөр нэвтэрч чадсангүй. Дахин оролдоно уу.", + "handoff_banner": "Та энэ компьютер дээрх Bulwark апп руу нэвтэрч байна. Энэ хөтөч Bulwark-д нэвтрэхгүй хэвээр үлдэнэ.", + "consent_title": "Bulwark апп руу нэвтрэх үү?", + "consent_description": "{username}-ийн нэвтрэлт энэ компьютер дээрх Bulwark апп руу очно. Зөвхөн аппаас эхлүүлсэн бол үргэлжлүүлнэ үү.", + "consent_confirm": "Апп руу нэвтрэх", + "consent_cancel": "Одоо биш", + "page_done": "Энэ табыг хааж Bulwark руу буцаж болно.", + "page_failed": "Нэвтэрч чадсангүй. Bulwark руу буцаж дахин оролдоно уу.", + "page_link_used": "Энэ холбоос зөвхөн нэг удаа ажиллана. Bulwark руу буцаж дахин эхэлнэ үү.", + "page_title": "{server} руу нэвтрэх", + "page_intro": "Энэ хуудас энэ компьютер дээрх Bulwark апп-аас ирсэн. Таны нууц үг зөвхөн {server} руу очно.", + "page_username": "Имэйл хаяг эсвэл хэрэглэгчийн нэр", + "page_password": "Нууц үг", + "page_code": "Хоёр шатлалт код", + "page_submit": "Нэвтрэх", + "page_wrong_password": "Сервер энэ хэрэглэгчийн нэр, нууц үгийг хүлээн авсангүй.", + "page_code_needed": "Энэ бүртгэлд хоёр шатлалт код бас хэрэгтэй. Нууц үг болон кодоо дахин оруулна уу.", + "page_no_answer": "Bulwark нэвтэрч чадсангүй. Сервер холбогдох боломжтой эсэхийг шалгаад дахин оролдоно уу." + }, "desktop_updates": { "title": "Шинэчлэлт", "version_label": "Bulwark {version}", diff --git a/locales/nb/common.json b/locales/nb/common.json index c434676eb..4c1fd096d 100644 --- a/locales/nb/common.json +++ b/locales/nb/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "For mange forsøk. Prøv igjen om {count, plural, one {# minutt} other {# minutter}}." }, "desktop_sign_in": { - "browser_button": "Logg på med nettleseren", - "browser_waiting": "Fullfør påloggingen i nettleseren", - "browser_unavailable": "Denne serveren tilbyr ikke pålogging via nettleser. Bruk passordet ditt.", - "browser_failed": "Pålogging via nettleseren mislyktes. Prøv igjen.", "server_needed": "Skriv inn serveradressen først.", "server_declined": "Du tillot ikke denne serveren, så ingenting ble sendt til den.", "server_invalid": "Denne serveradressen er ikke gyldig." }, + "desktop_browser_sign_in": { + "button": "Logg inn med nettleseren…", + "waiting": "Venter på nettleseren…", + "waiting_hint": "Fullfør innloggingen der. Passordbehandleren din virker i nettleseren.", + "cancel": "Avbryt", + "or_here": "eller logg inn her", + "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.", + "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_confirm": "Logg inn i appen", + "consent_cancel": "Ikke nå", + "page_done": "Du kan lukke denne fanen og gå tilbake til Bulwark.", + "page_failed": "Innloggingen virket ikke. Gå tilbake til Bulwark og prøv igjen.", + "page_link_used": "Denne lenken virker bare én gang. Gå tilbake til Bulwark og start på nytt.", + "page_title": "Logg inn på {server}", + "page_intro": "Denne siden kommer fra Bulwark-appen på denne datamaskinen. Passordet ditt går til {server} og ingen andre steder.", + "page_username": "E-postadresse eller brukernavn", + "page_password": "Passord", + "page_code": "Tofaktorkode", + "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." + }, "desktop_updates": { "title": "Oppdateringer", "version_label": "Bulwark {version}", diff --git a/locales/nl/common.json b/locales/nl/common.json index 3afb0250b..a108542ac 100644 --- a/locales/nl/common.json +++ b/locales/nl/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Te veel pogingen. Probeer het over {count, plural, one {# minuut} other {# minuten}} opnieuw." }, "desktop_sign_in": { - "browser_button": "Inloggen met je browser", - "browser_waiting": "Rond het inloggen af in je browser", - "browser_unavailable": "Deze server biedt geen inloggen via een browser. Gebruik je wachtwoord.", - "browser_failed": "Inloggen via de browser is niet gelukt. Probeer het opnieuw.", "server_needed": "Vul eerst het adres van de server in.", "server_declined": "Je hebt deze server niet toegestaan, dus er is niets naartoe gestuurd.", "server_invalid": "Dit serveradres is niet geldig." }, + "desktop_browser_sign_in": { + "button": "Inloggen met je browser…", + "waiting": "Wachten op je browser…", + "waiting_hint": "Rond het inloggen daar af. Je wachtwoordbeheerder werkt in je browser.", + "cancel": "Annuleren", + "or_here": "of log hier in", + "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.", + "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_confirm": "Inloggen bij de app", + "consent_cancel": "Niet nu", + "page_done": "Je kunt dit tabblad sluiten en teruggaan naar Bulwark.", + "page_failed": "Inloggen is niet gelukt. Ga terug naar Bulwark en probeer het opnieuw.", + "page_link_used": "Deze link werkt maar één keer. Ga terug naar Bulwark en begin opnieuw.", + "page_title": "Inloggen bij {server}", + "page_intro": "Deze pagina komt van de Bulwark-app op deze computer. Je wachtwoord gaat naar {server} en nergens anders heen.", + "page_username": "E-mailadres of gebruikersnaam", + "page_password": "Wachtwoord", + "page_code": "Tweefactorcode", + "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." + }, "desktop_updates": { "title": "Updates", "version_label": "Bulwark {version}", diff --git a/locales/pl/common.json b/locales/pl/common.json index 003c9b529..e828b6557 100644 --- a/locales/pl/common.json +++ b/locales/pl/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Zbyt wiele prób. Spróbuj za {count, plural, one {# minutę} few {# minuty} many {# minut} other {# minuty}}." }, "desktop_sign_in": { - "browser_button": "Zaloguj się w przeglądarce", - "browser_waiting": "Dokończ logowanie w przeglądarce", - "browser_unavailable": "Ten serwer nie oferuje logowania przez przeglądarkę. Użyj hasła.", - "browser_failed": "Logowanie przez przeglądarkę nie powiodło się. Spróbuj ponownie.", "server_needed": "Najpierw wpisz adres serwera.", "server_declined": "Ten serwer nie został dozwolony, więc nic do niego nie wysłano.", "server_invalid": "Ten adres serwera jest nieprawidłowy." }, + "desktop_browser_sign_in": { + "button": "Zaloguj się w przeglądarce…", + "waiting": "Czekanie na przeglądarkę…", + "waiting_hint": "Dokończ logowanie w przeglądarce. Działa tam Twój menedżer haseł.", + "cancel": "Anuluj", + "or_here": "lub zaloguj się tutaj", + "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.", + "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_confirm": "Zaloguj się w aplikacji", + "consent_cancel": "Nie teraz", + "page_done": "Możesz zamknąć tę kartę i wrócić do Bulwark.", + "page_failed": "Logowanie nie powiodło się. Wróć do Bulwark i spróbuj ponownie.", + "page_link_used": "Ten link działa tylko raz. Wróć do Bulwark i zacznij od nowa.", + "page_title": "Zaloguj się na {server}", + "page_intro": "Ta strona pochodzi z aplikacji Bulwark na tym komputerze. Twoje hasło trafia na {server} i nigdzie indziej.", + "page_username": "Adres e-mail lub nazwa użytkownika", + "page_password": "Hasło", + "page_code": "Kod dwuskładnikowy", + "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." + }, "desktop_updates": { "title": "Aktualizacje", "version_label": "Bulwark {version}", diff --git a/locales/pt/common.json b/locales/pt/common.json index 4cfe8b1e4..9d8e4b6bb 100644 --- a/locales/pt/common.json +++ b/locales/pt/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Demasiadas tentativas. Tente novamente daqui a {count, plural, one {# minuto} other {# minutos}}." }, "desktop_sign_in": { - "browser_button": "Entrar com o navegador", - "browser_waiting": "Termine de entrar no navegador", - "browser_unavailable": "Este servidor não oferece entrada pelo navegador. Use sua senha.", - "browser_failed": "Não foi possível entrar pelo navegador. Tente novamente.", "server_needed": "Digite primeiro o endereço do servidor.", "server_declined": "Você não permitiu este servidor, então nada foi enviado a ele.", "server_invalid": "Este endereço de servidor não é válido." }, + "desktop_browser_sign_in": { + "button": "Entrar com o navegador…", + "waiting": "A aguardar o navegador…", + "waiting_hint": "Termine de entrar por lá. O seu gestor de palavras-passe funciona no navegador.", + "cancel": "Cancelar", + "or_here": "ou entre aqui", + "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.", + "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_confirm": "Entrar na aplicação", + "consent_cancel": "Agora não", + "page_done": "Pode fechar este separador e voltar ao Bulwark.", + "page_failed": "Não foi possível entrar. Volte ao Bulwark e tente novamente.", + "page_link_used": "Esta ligação só funciona uma vez. Volte ao Bulwark e comece de novo.", + "page_title": "Entrar em {server}", + "page_intro": "Esta página vem da aplicação Bulwark neste computador. A sua palavra-passe vai para {server} e para mais lado nenhum.", + "page_username": "Endereço de e-mail ou nome de utilizador", + "page_password": "Palavra-passe", + "page_code": "Código de dois fatores", + "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." + }, "desktop_updates": { "title": "Atualizações", "version_label": "Bulwark {version}", diff --git a/locales/ro/common.json b/locales/ro/common.json index 572f9b856..7d0cb7008 100644 --- a/locales/ro/common.json +++ b/locales/ro/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Prea multe încercări. Încercați din nou peste {count, plural, one {# minut} few {# minute} other {# de minute}}." }, "desktop_sign_in": { - "browser_button": "Conectează-te cu browserul", - "browser_waiting": "Finalizează conectarea în browser", - "browser_unavailable": "Acest server nu oferă conectare prin browser. Folosește parola.", - "browser_failed": "Conectarea prin browser nu a reușit. Încearcă din nou.", "server_needed": "Introdu mai întâi adresa serverului.", "server_declined": "Nu ai permis acest server, așa că nu i s-a trimis nimic.", "server_invalid": "Această adresă de server nu este validă." }, + "desktop_browser_sign_in": { + "button": "Conectați-vă cu browserul…", + "waiting": "Se așteaptă browserul…", + "waiting_hint": "Terminați conectarea acolo. Managerul de parole funcționează în browser.", + "cancel": "Anulați", + "or_here": "sau conectați-vă aici", + "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.", + "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_confirm": "Conectați-vă la aplicație", + "consent_cancel": "Nu acum", + "page_done": "Puteți închide această filă și reveni la Bulwark.", + "page_failed": "Conectarea nu a reușit. Reveniți la Bulwark și încercați din nou.", + "page_link_used": "Acest link funcționează o singură dată. Reveniți la Bulwark și începeți din nou.", + "page_title": "Conectați-vă la {server}", + "page_intro": "Această pagină vine de la aplicația Bulwark de pe acest computer. Parola merge la {server} și nicăieri altundeva.", + "page_username": "Adresă de e-mail sau nume de utilizator", + "page_password": "Parolă", + "page_code": "Cod cu doi factori", + "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." + }, "desktop_updates": { "title": "Actualizări", "version_label": "Bulwark {version}", diff --git a/locales/ru/common.json b/locales/ru/common.json index 2fdb08106..97d5c3a69 100644 --- a/locales/ru/common.json +++ b/locales/ru/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Слишком много попыток. Повторите через {count, plural, one {# минуту} few {# минуты} many {# минут} other {# минуты}}." }, "desktop_sign_in": { - "browser_button": "Войти через браузер", - "browser_waiting": "Завершите вход в браузере", - "browser_unavailable": "Этот сервер не поддерживает вход через браузер. Используйте пароль.", - "browser_failed": "Не удалось войти через браузер. Попробуйте ещё раз.", "server_needed": "Сначала введите адрес сервера.", "server_declined": "Вы не разрешили этот сервер, поэтому ему ничего не отправлено.", "server_invalid": "Этот адрес сервера недействителен." }, + "desktop_browser_sign_in": { + "button": "Войти через браузер…", + "waiting": "Ожидание браузера…", + "waiting_hint": "Завершите вход там. Ваш менеджер паролей работает в браузере.", + "cancel": "Отмена", + "or_here": "или войдите здесь", + "timed_out": "Вход через браузер занял слишком много времени. Попробуйте ещё раз.", + "no_browser": "Bulwark не смог открыть браузер. Попробуйте ещё раз или войдите здесь.", + "failed": "Не удалось войти через браузер. Попробуйте ещё раз.", + "handoff_banner": "Вы входите в приложение Bulwark на этом компьютере. В этом браузере вход в Bulwark не выполняется.", + "consent_title": "Войти в приложение Bulwark?", + "consent_description": "Ваш вход для {username} будет передан приложению Bulwark на этом компьютере. Продолжайте, только если начали это из приложения.", + "consent_confirm": "Войти в приложение", + "consent_cancel": "Не сейчас", + "page_done": "Можно закрыть эту вкладку и вернуться в Bulwark.", + "page_failed": "Не удалось войти. Вернитесь в Bulwark и попробуйте ещё раз.", + "page_link_used": "Эта ссылка работает только один раз. Вернитесь в Bulwark и начните заново.", + "page_title": "Вход на {server}", + "page_intro": "Эта страница открыта приложением Bulwark на этом компьютере. Ваш пароль уходит на {server} и больше никуда.", + "page_username": "Адрес эл. почты или имя пользователя", + "page_password": "Пароль", + "page_code": "Двухфакторный код", + "page_submit": "Войти", + "page_wrong_password": "Сервер не принял это имя пользователя и пароль.", + "page_code_needed": "Для этой учётной записи также нужен двухфакторный код. Введите пароль ещё раз и код.", + "page_no_answer": "Bulwark не смог войти. Проверьте, доступен ли сервер, и попробуйте ещё раз." + }, "desktop_updates": { "title": "Обновления", "version_label": "Bulwark {version}", diff --git a/locales/sk/common.json b/locales/sk/common.json index d8a42ccfb..536953dc4 100644 --- a/locales/sk/common.json +++ b/locales/sk/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Príliš veľa pokusov. Skúste to o {count, plural, one {# minútu} few {# minúty} many {# minúty} other {# minút}}." }, "desktop_sign_in": { - "browser_button": "Prihlásiť sa v prehliadači", - "browser_waiting": "Dokončite prihlásenie v prehliadači", - "browser_unavailable": "Tento server neponúka prihlásenie cez prehliadač. Použite heslo.", - "browser_failed": "Prihlásenie cez prehliadač sa nepodarilo. Skúste to znova.", "server_needed": "Najprv zadajte adresu servera.", "server_declined": "Tento server ste nepovolili, preto sa naň nič neodoslalo.", "server_invalid": "Táto adresa servera nie je platná." }, + "desktop_browser_sign_in": { + "button": "Prihlásiť sa v prehliadači…", + "waiting": "Čaká sa na prehliadač…", + "waiting_hint": "Dokončite prihlásenie tam. Váš správca hesiel funguje v prehliadači.", + "cancel": "Zrušiť", + "or_here": "alebo sa prihláste tu", + "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ý.", + "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_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.", + "page_failed": "Prihlásenie sa nepodarilo. Vráťte sa do Bulwarku a skúste to znova.", + "page_link_used": "Tento odkaz funguje len raz. Vráťte sa do Bulwarku a začnite znova.", + "page_title": "Prihlásiť sa na {server}", + "page_intro": "Táto stránka pochádza z aplikácie Bulwark v tomto počítači. Vaše heslo ide na {server} a nikam inam.", + "page_username": "E-mailová adresa alebo používateľské meno", + "page_password": "Heslo", + "page_code": "Dvojfaktorový kód", + "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." + }, "desktop_updates": { "title": "Aktualizácie", "version_label": "Bulwark {version}", diff --git a/locales/th/common.json b/locales/th/common.json index af4128993..5371c016d 100644 --- a/locales/th/common.json +++ b/locales/th/common.json @@ -6881,14 +6881,37 @@ "blocked_minutes": "ลองหลายครั้งเกินไป ลองอีกครั้งใน {count, plural, other {# นาที}}" }, "desktop_sign_in": { - "browser_button": "ลงชื่อเข้าใช้ด้วยเบราว์เซอร์", - "browser_waiting": "ลงชื่อเข้าใช้ให้เสร็จในเบราว์เซอร์", - "browser_unavailable": "เซิร์ฟเวอร์นี้ไม่รองรับการลงชื่อเข้าใช้ผ่านเบราว์เซอร์ โปรดใช้รหัสผ่าน", - "browser_failed": "ลงชื่อเข้าใช้ผ่านเบราว์เซอร์ไม่สำเร็จ โปรดลองอีกครั้ง", "server_needed": "ป้อนที่อยู่เซิร์ฟเวอร์ก่อน", "server_declined": "คุณไม่ได้อนุญาตเซิร์ฟเวอร์นี้ จึงไม่มีการส่งข้อมูลใดไป", "server_invalid": "ที่อยู่เซิร์ฟเวอร์นี้ไม่ถูกต้อง" }, + "desktop_browser_sign_in": { + "button": "ลงชื่อเข้าใช้ด้วยเบราว์เซอร์…", + "waiting": "กำลังรอเบราว์เซอร์…", + "waiting_hint": "ลงชื่อเข้าใช้ให้เสร็จในเบราว์เซอร์ ตัวจัดการรหัสผ่านของคุณใช้งานได้ที่นั่น", + "cancel": "ยกเลิก", + "or_here": "หรือลงชื่อเข้าใช้ที่นี่", + "timed_out": "การลงชื่อเข้าใช้ในเบราว์เซอร์ใช้เวลานานเกินไป ลองอีกครั้ง", + "no_browser": "Bulwark เปิดเบราว์เซอร์ไม่ได้ ลองอีกครั้งหรือลงชื่อเข้าใช้ที่นี่", + "failed": "ลงชื่อเข้าใช้ผ่านเบราว์เซอร์ไม่สำเร็จ ลองอีกครั้ง", + "handoff_banner": "คุณกำลังลงชื่อเข้าใช้แอป Bulwark บนคอมพิวเตอร์เครื่องนี้ เบราว์เซอร์นี้จะยังไม่ได้ลงชื่อเข้าใช้ Bulwark", + "consent_title": "ลงชื่อเข้าใช้แอป Bulwark หรือไม่", + "consent_description": "การลงชื่อเข้าใช้ของ {username} จะส่งไปยังแอป Bulwark บนคอมพิวเตอร์เครื่องนี้ ดำเนินการต่อเฉพาะเมื่อคุณเริ่มจากแอปเท่านั้น", + "consent_confirm": "ลงชื่อเข้าใช้แอป", + "consent_cancel": "ไม่ใช่ตอนนี้", + "page_done": "คุณปิดแท็บนี้และกลับไปที่ Bulwark ได้", + "page_failed": "ลงชื่อเข้าใช้ไม่สำเร็จ กลับไปที่ Bulwark แล้วลองอีกครั้ง", + "page_link_used": "ลิงก์นี้ใช้ได้ครั้งเดียว กลับไปที่ Bulwark แล้วเริ่มใหม่", + "page_title": "ลงชื่อเข้าใช้ {server}", + "page_intro": "หน้านี้มาจากแอป Bulwark บนคอมพิวเตอร์เครื่องนี้ รหัสผ่านของคุณจะส่งไปที่ {server} เท่านั้น", + "page_username": "ที่อยู่อีเมลหรือชื่อผู้ใช้", + "page_password": "รหัสผ่าน", + "page_code": "รหัสสองปัจจัย", + "page_submit": "ลงชื่อเข้าใช้", + "page_wrong_password": "เซิร์ฟเวอร์ไม่ยอมรับชื่อผู้ใช้และรหัสผ่านนี้", + "page_code_needed": "บัญชีนี้ต้องใช้รหัสสองปัจจัยด้วย ป้อนรหัสผ่านอีกครั้งพร้อมรหัส", + "page_no_answer": "Bulwark ลงชื่อเข้าใช้ไม่ได้ ตรวจสอบว่าเข้าถึงเซิร์ฟเวอร์ได้แล้วลองอีกครั้ง" + }, "desktop_updates": { "title": "การอัปเดต", "version_label": "Bulwark {version}", diff --git a/locales/tr/common.json b/locales/tr/common.json index c74a4ae59..5c7586188 100644 --- a/locales/tr/common.json +++ b/locales/tr/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Çok fazla deneme. {count, plural, one {# dakika} other {# dakika}} sonra yeniden deneyin." }, "desktop_sign_in": { - "browser_button": "Tarayıcıyla oturum aç", - "browser_waiting": "Oturum açmayı tarayıcınızda tamamlayın", - "browser_unavailable": "Bu sunucu tarayıcıyla oturum açmayı desteklemiyor. Parolanızı kullanın.", - "browser_failed": "Tarayıcıyla oturum açılamadı. Yeniden deneyin.", "server_needed": "Önce sunucu adresini girin.", "server_declined": "Bu sunucuya izin vermediniz, bu yüzden ona hiçbir şey gönderilmedi.", "server_invalid": "Bu sunucu adresi geçerli değil." }, + "desktop_browser_sign_in": { + "button": "Tarayıcınızla oturum açın…", + "waiting": "Tarayıcınız bekleniyor…", + "waiting_hint": "Oturum açmayı orada tamamlayın. Parola yöneticiniz tarayıcınızda çalışır.", + "cancel": "İptal", + "or_here": "veya burada oturum açın", + "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.", + "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_confirm": "Uygulamada oturum aç", + "consent_cancel": "Şimdi değil", + "page_done": "Bu sekmeyi kapatıp Bulwark’a dönebilirsiniz.", + "page_failed": "Oturum açılamadı. Bulwark’a dönün ve yeniden deneyin.", + "page_link_used": "Bu bağlantı yalnızca bir kez çalışır. Bulwark’a dönün ve yeniden başlayın.", + "page_title": "{server} için oturum açın", + "page_intro": "Bu sayfa bu bilgisayardaki Bulwark uygulamasından geliyor. Parolanız {server} sunucusuna gider, başka hiçbir yere gitmez.", + "page_username": "E-posta adresi veya kullanıcı adı", + "page_password": "Parola", + "page_code": "İki aşamalı kod", + "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." + }, "desktop_updates": { "title": "Güncellemeler", "version_label": "Bulwark {version}", diff --git a/locales/uk/common.json b/locales/uk/common.json index 43227c05e..4b0e0d018 100644 --- a/locales/uk/common.json +++ b/locales/uk/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "Забагато спроб. Повторіть через {count, plural, one {# хвилину} few {# хвилини} many {# хвилин} other {# хвилини}}." }, "desktop_sign_in": { - "browser_button": "Увійти через браузер", - "browser_waiting": "Завершіть вхід у браузері", - "browser_unavailable": "Цей сервер не підтримує вхід через браузер. Використайте пароль.", - "browser_failed": "Не вдалося увійти через браузер. Спробуйте ще раз.", "server_needed": "Спочатку введіть адресу сервера.", "server_declined": "Ви не дозволили цей сервер, тому йому нічого не надіслано.", "server_invalid": "Ця адреса сервера недійсна." }, + "desktop_browser_sign_in": { + "button": "Увійти через браузер…", + "waiting": "Очікування браузера…", + "waiting_hint": "Завершіть вхід там. Ваш менеджер паролів працює в браузері.", + "cancel": "Скасувати", + "or_here": "або увійдіть тут", + "timed_out": "Вхід через браузер тривав надто довго. Спробуйте ще раз.", + "no_browser": "Bulwark не зміг відкрити браузер. Спробуйте ще раз або увійдіть тут.", + "failed": "Не вдалося увійти через браузер. Спробуйте ще раз.", + "handoff_banner": "Ви входите в застосунок Bulwark на цьому комп’ютері. У цьому браузері вхід у Bulwark не виконується.", + "consent_title": "Увійти в застосунок Bulwark?", + "consent_description": "Ваш вхід для {username} буде передано застосунку Bulwark на цьому комп’ютері. Продовжуйте, лише якщо почали це із застосунку.", + "consent_confirm": "Увійти в застосунок", + "consent_cancel": "Не зараз", + "page_done": "Можна закрити цю вкладку й повернутися до Bulwark.", + "page_failed": "Не вдалося увійти. Поверніться до Bulwark і спробуйте ще раз.", + "page_link_used": "Це посилання працює лише один раз. Поверніться до Bulwark і почніть знову.", + "page_title": "Вхід на {server}", + "page_intro": "Цю сторінку відкрив застосунок Bulwark на цьому комп’ютері. Ваш пароль іде на {server} і більше нікуди.", + "page_username": "Адреса ел. пошти або ім’я користувача", + "page_password": "Пароль", + "page_code": "Двофакторний код", + "page_submit": "Увійти", + "page_wrong_password": "Сервер не прийняв це ім’я користувача й пароль.", + "page_code_needed": "Для цього облікового запису також потрібен двофакторний код. Введіть пароль ще раз і код.", + "page_no_answer": "Bulwark не зміг увійти. Перевірте, чи доступний сервер, і спробуйте ще раз." + }, "desktop_updates": { "title": "Оновлення", "version_label": "Bulwark {version}", diff --git a/locales/vi/common.json b/locales/vi/common.json index 8c6ef8e6f..6e370f97a 100644 --- a/locales/vi/common.json +++ b/locales/vi/common.json @@ -6885,14 +6885,37 @@ "blocked_minutes": "Quá nhiều lần thử. Hãy thử lại sau {count, plural, other {# phút}}." }, "desktop_sign_in": { - "browser_button": "Đăng nhập bằng trình duyệt", - "browser_waiting": "Hoàn tất đăng nhập trong trình duyệt", - "browser_unavailable": "Máy chủ này không hỗ trợ đăng nhập qua trình duyệt. Hãy dùng mật khẩu.", - "browser_failed": "Không thể đăng nhập qua trình duyệt. Hãy thử lại.", "server_needed": "Trước tiên hãy nhập địa chỉ máy chủ.", "server_declined": "Bạn không cho phép máy chủ này nên không có gì được gửi đến đó.", "server_invalid": "Địa chỉ máy chủ này không hợp lệ." }, + "desktop_browser_sign_in": { + "button": "Đăng nhập bằng trình duyệt…", + "waiting": "Đang chờ trình duyệt…", + "waiting_hint": "Hãy hoàn tất đăng nhập ở đó. Trình quản lý mật khẩu của bạn hoạt động trong trình duyệt.", + "cancel": "Hủy", + "or_here": "hoặc đăng nhập tại đây", + "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.", + "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_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.", + "page_failed": "Không đăng nhập được. Hãy quay lại Bulwark và thử lại.", + "page_link_used": "Liên kết này chỉ dùng được một lần. Hãy quay lại Bulwark và bắt đầu lại.", + "page_title": "Đăng nhập vào {server}", + "page_intro": "Trang này đến từ ứng dụng Bulwark trên máy tính này. Mật khẩu của bạn chỉ được gửi đến {server}.", + "page_username": "Địa chỉ email hoặc tên người dùng", + "page_password": "Mật khẩu", + "page_code": "Mã hai yếu tố", + "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." + }, "desktop_updates": { "title": "Cập nhật", "version_label": "Bulwark {version}", diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json index 1028578b1..cb8013156 100644 --- a/locales/zh-TW/common.json +++ b/locales/zh-TW/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "嘗試次數過多。請在 {count, plural, other {# 分鐘}}後再試。" }, "desktop_sign_in": { - "browser_button": "使用瀏覽器登入", - "browser_waiting": "請在瀏覽器中完成登入", - "browser_unavailable": "此伺服器不支援透過瀏覽器登入。請使用密碼。", - "browser_failed": "無法透過瀏覽器登入。請再試一次。", "server_needed": "請先輸入伺服器位址。", "server_declined": "你沒有允許此伺服器,因此沒有傳送任何內容給它。", "server_invalid": "此伺服器位址無效。" }, + "desktop_browser_sign_in": { + "button": "使用瀏覽器登入…", + "waiting": "正在等候瀏覽器…", + "waiting_hint": "請在瀏覽器中完成登入。你的密碼管理工具可以在瀏覽器中使用。", + "cancel": "取消", + "or_here": "或在此登入", + "timed_out": "瀏覽器登入耗時過長。請再試一次。", + "no_browser": "Bulwark 無法開啟瀏覽器。請再試一次,或在此登入。", + "failed": "透過瀏覽器登入失敗。請再試一次。", + "handoff_banner": "你正在登入這台電腦上的 Bulwark 應用程式。此瀏覽器不會登入 Bulwark。", + "consent_title": "要登入 Bulwark 應用程式嗎?", + "consent_description": "{username} 的登入資訊將交給這台電腦上的 Bulwark 應用程式。只有從應用程式發起時才繼續。", + "consent_confirm": "登入應用程式", + "consent_cancel": "暫不", + "page_done": "你可以關閉此分頁並返回 Bulwark。", + "page_failed": "登入失敗。請返回 Bulwark 並再試一次。", + "page_link_used": "此連結只能使用一次。請返回 Bulwark 重新開始。", + "page_title": "登入 {server}", + "page_intro": "此頁面來自這台電腦上的 Bulwark 應用程式。你的密碼只會傳送到 {server}。", + "page_username": "電子郵件地址或使用者名稱", + "page_password": "密碼", + "page_code": "雙重驗證碼", + "page_submit": "登入", + "page_wrong_password": "伺服器不接受此使用者名稱和密碼。", + "page_code_needed": "此帳戶還需要雙重驗證碼。請重新輸入密碼和驗證碼。", + "page_no_answer": "Bulwark 無法登入。請檢查伺服器是否可連線,然後再試一次。" + }, "desktop_updates": { "title": "更新", "version_label": "Bulwark {version}", diff --git a/locales/zh/common.json b/locales/zh/common.json index 641f7a2cf..97a8fb1e7 100644 --- a/locales/zh/common.json +++ b/locales/zh/common.json @@ -6873,14 +6873,37 @@ "blocked_minutes": "尝试次数过多。请在 {count, plural, other {# 分钟}}后重试。" }, "desktop_sign_in": { - "browser_button": "使用浏览器登录", - "browser_waiting": "请在浏览器中完成登录", - "browser_unavailable": "此服务器不支持通过浏览器登录。请使用密码。", - "browser_failed": "无法通过浏览器登录。请重试。", "server_needed": "请先输入服务器地址。", "server_declined": "你没有允许此服务器,因此没有向它发送任何内容。", "server_invalid": "此服务器地址无效。" }, + "desktop_browser_sign_in": { + "button": "使用浏览器登录…", + "waiting": "正在等待浏览器…", + "waiting_hint": "请在浏览器中完成登录。你的密码管理器可以在浏览器中使用。", + "cancel": "取消", + "or_here": "或在此登录", + "timed_out": "浏览器登录用时过长。请重试。", + "no_browser": "Bulwark 无法打开浏览器。请重试,或在此登录。", + "failed": "通过浏览器登录失败。请重试。", + "handoff_banner": "你正在登录这台电脑上的 Bulwark 应用。此浏览器不会登录 Bulwark。", + "consent_title": "要登录 Bulwark 应用吗?", + "consent_description": "{username} 的登录信息将交给这台电脑上的 Bulwark 应用。只有从应用中发起时才继续。", + "consent_confirm": "登录应用", + "consent_cancel": "暂不", + "page_done": "你可以关闭此标签页并返回 Bulwark。", + "page_failed": "登录失败。请返回 Bulwark 并重试。", + "page_link_used": "此链接只能使用一次。请返回 Bulwark 重新开始。", + "page_title": "登录 {server}", + "page_intro": "此页面来自这台电脑上的 Bulwark 应用。你的密码只会发送到 {server}。", + "page_username": "电子邮件地址或用户名", + "page_password": "密码", + "page_code": "双重验证代码", + "page_submit": "登录", + "page_wrong_password": "服务器不接受此用户名和密码。", + "page_code_needed": "此账户还需要双重验证代码。请重新输入密码和代码。", + "page_no_answer": "Bulwark 无法登录。请检查服务器是否可访问,然后重试。" + }, "desktop_updates": { "title": "更新", "version_label": "Bulwark {version}", diff --git a/scripts/lite/lib.mjs b/scripts/lite/lib.mjs index 088f3533a..2c124ddbb 100644 --- a/scripts/lite/lib.mjs +++ b/scripts/lite/lib.mjs @@ -118,6 +118,9 @@ export const LITE_API_STRING_ALLOWLIST = [ // the fragment. "/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/park", + "/api/auth/desktop-handoff/redeem", "/api/auth/totp-token-exchange", "/api/auth/session", "/api/auth/verify", diff --git a/stores/auth-store.ts b/stores/auth-store.ts index 2250c9ec9..fd0df6cae 100644 --- a/stores/auth-store.ts +++ b/stores/auth-store.ts @@ -109,6 +109,11 @@ interface AuthState { loginWithToken: (serverUrl: string, token: string, rememberMe?: boolean) => Promise; loginWithOAuth: (serverUrl: string, code: string, codeVerifier: string, redirectUri: string, serverId?: string) => Promise; loginWithServerSso: (code: string, state: string) => Promise; + /** + * 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'>; loginDemo: () => Promise; /** * Obtain a usable access token for `accountId`, or the active account. @@ -1602,6 +1607,101 @@ function notifySignedIn(state: { activeAccountId: string | null; username: strin void authHooks.onLogin.emit({ accountId: state.activeAccountId, username: state.username ?? '' }); } +/** + * A provider's tokens are in, with the refresh token already in the slot's cookie: the + * rest of a sign-in. Server-side SSO, and the desktop app's sign-in on an instance. + */ +async function adoptProviderSession( + set: (state: Partial) => void, + get: () => AuthState, + session: { serverUrl: string; accessToken: string; expiresIn: number; remember: boolean | undefined; slot: number }, +): Promise { + const { serverUrl: ssoServerUrl, accessToken: access_token, expiresIn: expires_in, remember, slot } = session; + const accountStore = useAccountStore.getState(); + let boundAccountId: string | undefined; + const client = JMAPClient.withBearer(ssoServerUrl, access_token, '', () => get().refreshAccessToken({ accountId: boundAccountId })); + await client.connect(); + + const jmapUsername = client.getUsername(); + const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), 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; + initializeFeatureStores(client); + + const accountId = generateAccountId(username, ssoServerUrl); + boundAccountId = accountId; + + const prevAccountId = get().activeAccountId; + if (prevAccountId && prevAccountId !== accountId) { + snapshotAccount(prevAccountId); + clearAllStores(); + } + + holdClient(accountId, client); + bindClientStatusHandlers(client, set, get, accountId); + + accountStore.addAccount({ + label: primaryIdentity?.name || username, + serverUrl: ssoServerUrl, + username, + authMode: 'oauth', + rememberMe: remember !== false, + displayName: primaryIdentity?.name || username, + email: primaryIdentity?.email || username, + lastLoginAt: Date.now(), + isConnected: true, + hasError: false, + isDefault: accountStore.accounts.length === 0, + }); + // 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.setActiveAccount(accountId); + + await syncStalwartAuthContext(ssoServerUrl, username, client.getAuthHeader(), slot); + void syncAccountDisplayName(accountId, client, primaryIdentity?.name); + + set({ + isAuthenticated: true, + isLoading: false, + serverUrl: ssoServerUrl, + username, + client, + ...getClientRateLimitState(client), + identities, + primaryIdentity, + authMode: 'oauth', + accessToken: access_token, + tokenExpiresAt: Date.now() + expires_in * 1000, + connectionLost: false, + error: null, + activeAccountId: accountId, + }); + + import('@/stores/email-store').then(({ useEmailStore }) => { + useEmailStore.getState().prefetchInitialData(client).catch((err) => { + debug.error('Initial data prefetch failed:', err); + }); + }).catch(() => {}); + + scheduleRefresh(expires_in, () => get().refreshAccessToken({ accountId }), accountId); + + notifyParent('sso:auth-success', { username }); + + fetchConfig().then(cfg => { + if (!cfg.settingsSyncEnabled) return; + useSettingsStore.getState().loadFromServer(username, ssoServerUrl).finally(() => { + useSettingsStore.getState().enableSync(username, ssoServerUrl); + applyPreferredIdentity(accountId); + }); + }).catch(() => {}); + + notifySignedIn(get()); +} + function beforeLogoutHooks(accountId: string, options: SignOutCleanupOptions = {}): Promise { return Promise.race([ Promise.all([authHooks.onBeforeLogout.emit({ accountId }), runBeforeSignOut(accountId, options)]).then(() => {}), @@ -2268,88 +2368,7 @@ export const useAuthStore = create()( throw new Error('Server URL not configured'); } - let boundAccountId: string | undefined; - const client = JMAPClient.withBearer(ssoServerUrl, access_token, '', () => get().refreshAccessToken({ accountId: boundAccountId })); - await client.connect(); - - const jmapUsername = client.getUsername(); - const { identities, primaryIdentity } = loadIdentities(await client.getIdentities(), 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; - initializeFeatureStores(client); - - const accountId = generateAccountId(username, ssoServerUrl); - boundAccountId = accountId; - - const prevAccountId = get().activeAccountId; - if (prevAccountId && prevAccountId !== accountId) { - snapshotAccount(prevAccountId); - clearAllStores(); - } - - holdClient(accountId, client); - bindClientStatusHandlers(client, set, get, accountId); - - accountStore.addAccount({ - label: primaryIdentity?.name || username, - serverUrl: ssoServerUrl, - username, - authMode: 'oauth', - rememberMe: remember !== false, - displayName: primaryIdentity?.name || username, - email: primaryIdentity?.email || username, - lastLoginAt: Date.now(), - isConnected: true, - hasError: false, - isDefault: accountStore.accounts.length === 0, - }); - // 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.setActiveAccount(accountId); - - await syncStalwartAuthContext(ssoServerUrl, username, client.getAuthHeader(), slot); - void syncAccountDisplayName(accountId, client, primaryIdentity?.name); - - set({ - isAuthenticated: true, - isLoading: false, - serverUrl: ssoServerUrl, - username, - client, - ...getClientRateLimitState(client), - identities, - primaryIdentity, - authMode: 'oauth', - accessToken: access_token, - tokenExpiresAt: Date.now() + expires_in * 1000, - connectionLost: false, - error: null, - activeAccountId: accountId, - }); - - import('@/stores/email-store').then(({ useEmailStore }) => { - useEmailStore.getState().prefetchInitialData(client).catch((err) => { - debug.error('Initial data prefetch failed:', err); - }); - }).catch(() => {}); - - scheduleRefresh(expires_in, () => get().refreshAccessToken({ accountId }), accountId); - - notifyParent('sso:auth-success', { username }); - - fetchConfig().then(cfg => { - if (!cfg.settingsSyncEnabled) return; - useSettingsStore.getState().loadFromServer(username, ssoServerUrl).finally(() => { - useSettingsStore.getState().enableSync(username, ssoServerUrl); - applyPreferredIdentity(accountId); - }); - }).catch(() => {}); - - notifySignedIn(get()); + await adoptProviderSession(set, get, { serverUrl: ssoServerUrl, accessToken: access_token, expiresIn: expires_in, remember, slot }); return true; } catch (error) { debug.error('Server SSO login error:', error); @@ -2367,6 +2386,42 @@ export const useAuthStore = create()( } }, + loginWithDesktopHandoff: async (code, verifier, { remember, rememberPassword, allowedServers }) => { + if (IS_LITE) return 'failed'; + set({ isLoading: true, error: null, isRateLimited: false, rateLimitUntil: null }); + try { + const slot = useAccountStore.getState().getNextCookieSlot(); + 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 }), + }).then((answer) => noteSessionAnswer(answer, slot)); + if (!res.ok) { + const refusal = (await res.json().catch(() => null)) as { error?: string } | null; + set({ isLoading: false, error: null }); + return refusal?.error === 'blocked_by_policy' ? 'blocked' : 'failed'; + } + const parked = await res.json(); + if (parked.flow === 'password') { + // 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 }); + return 'ok'; + } catch (error) { + debug.error('Desktop hand-off login error:', error); + set({ + isLoading: false, + error: error instanceof Error ? error.message : 'generic', + isAuthenticated: false, + isRateLimited: false, + rateLimitUntil: null, + client: null, + }); + return 'failed'; + } + }, + refreshAccessToken: async (options) => { // Every multi-account client and timer passes its own account: renewing // the active slot on a background account's behalf would hand that From 37844ce3e5d1392eec2f39af3b7c6acaf991ae8b Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:25:39 +0100 Subject: [PATCH 10/59] fix: use the registration endpoint a mail server names when the desktop app signs in through the browser --- lib/__tests__/oauth-discovery.test.ts | 8 ++++++++ lib/oauth/discovery.ts | 2 ++ 2 files changed, 10 insertions(+) diff --git a/lib/__tests__/oauth-discovery.test.ts b/lib/__tests__/oauth-discovery.test.ts index 8697c7779..694b4e0e1 100644 --- a/lib/__tests__/oauth-discovery.test.ts +++ b/lib/__tests__/oauth-discovery.test.ts @@ -47,6 +47,14 @@ describe('oauth/discovery', () => { } }); + it('keeps a registration endpoint the server names, for the desktop app, and only a string', async () => { + const answer = (extra: Record) => ({ status: 200, ok: true, headers: new Headers(), json: async () => ({ ...VALID_METADATA, ...extra }) }); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(answer({ registration_endpoint: 'https://auth.example.com/register' }))); + expect((await discoverOAuth('https://a.example.com', { validateEndpoint }))?.registration_endpoint).toBe('https://auth.example.com/register'); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(answer({ registration_endpoint: 7 }))); + expect((await discoverOAuth('https://b.example.com', { validateEndpoint }))?.registration_endpoint).toBeUndefined(); + }); + it('follows one redirect that stays on the same host', async () => { const redirect = { status: 301, ok: false, headers: new Headers({ location: '/auth/.well-known/openid-configuration' }), json: async () => ({}) }; const document = { status: 200, ok: true, headers: new Headers(), json: async () => VALID_METADATA }; diff --git a/lib/oauth/discovery.ts b/lib/oauth/discovery.ts index 838ed69f9..6c52e7126 100644 --- a/lib/oauth/discovery.ts +++ b/lib/oauth/discovery.ts @@ -149,6 +149,8 @@ async function attemptDiscovery( token_endpoint: data.token_endpoint, revocation_endpoint: data.revocation_endpoint, end_session_endpoint: data.end_session_endpoint, + // Not followed from here: the one caller checks it itself (app/api/auth/desktop-oauth). + ...(typeof data.registration_endpoint === 'string' ? { registration_endpoint: data.registration_endpoint } : {}), ...(Array.isArray(data.scopes_supported) ? { scopes_supported: data.scopes_supported.filter((s: unknown): s is string => typeof s === 'string') } : {}), From d31d0af5607e06adc284d0d26915347b4182dce5 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:36:48 +0100 Subject: [PATCH 11/59] fix: say what an open program still holds, keep forwarded parts under their rules, and let main decide what a sent draft leaves --- .../__tests__/edited-files-host.test.tsx | 162 +++++++-- components/desktop/edited-files-host.tsx | 108 +++--- .../composer-edit-attachments.test.tsx | 316 ++++++++++++++++++ .../__tests__/edit-attachment-gates.test.tsx | 141 ++++++++ components/email/email-composer.tsx | 33 +- components/mail/mail-app.tsx | 3 + components/pro/pro-email-tab-body.tsx | 2 + hooks/__tests__/use-composer-edits.test.tsx | 81 +++-- hooks/use-composer-edits.ts | 37 +- hooks/use-edit-attachment.ts | 3 +- hooks/use-phishing-report.ts | 5 + .../__tests__/edit-attachments.test.ts | 27 +- lib/desktop/edit-attachments.ts | 13 +- lib/desktop/languages.ts | 11 + lib/desktop/types.ts | 34 +- lib/offline/device-wipe.ts | 12 +- lib/offline/wipe-registry.ts | 15 +- locales/ar/common.json | 16 +- locales/ca/common.json | 16 +- locales/cs/common.json | 16 +- locales/da/common.json | 16 +- locales/de/common.json | 16 +- locales/en/common.json | 16 +- locales/es/common.json | 16 +- locales/et/common.json | 16 +- locales/fa/common.json | 16 +- locales/fr/common.json | 16 +- locales/he/common.json | 16 +- locales/hu/common.json | 16 +- locales/it/common.json | 16 +- locales/ja/common.json | 16 +- locales/ko/common.json | 16 +- locales/lv/common.json | 16 +- locales/mn/common.json | 16 +- locales/nb/common.json | 16 +- locales/nl/common.json | 16 +- locales/pl/common.json | 16 +- locales/pt/common.json | 16 +- locales/ro/common.json | 16 +- locales/ru/common.json | 16 +- locales/sk/common.json | 16 +- locales/th/common.json | 16 +- locales/tr/common.json | 16 +- locales/uk/common.json | 16 +- locales/vi/common.json | 16 +- locales/zh-TW/common.json | 16 +- locales/zh/common.json | 16 +- stores/pro-tab-store.ts | 2 + 48 files changed, 1261 insertions(+), 224 deletions(-) create mode 100644 components/email/__tests__/composer-edit-attachments.test.tsx create mode 100644 components/email/__tests__/edit-attachment-gates.test.tsx diff --git a/components/desktop/__tests__/edited-files-host.test.tsx b/components/desktop/__tests__/edited-files-host.test.tsx index 19e0fd228..30338054d 100644 --- a/components/desktop/__tests__/edited-files-host.test.tsx +++ b/components/desktop/__tests__/edited-files-host.test.tsx @@ -8,7 +8,9 @@ const handOffDraft = vi.hoisted(() => vi.fn()); const openDraftWindow = vi.hoisted(() => vi.fn()); const saveBlobAs = vi.hoisted(() => vi.fn(() => true)); const signOutGates = vi.hoisted(() => [] as ((account: string) => Promise)[]); -const accounts = vi.hoisted(() => ({ list: [{ id: 'acct', cookieSlot: 2 }] as { id: string; cookieSlot: number }[], active: 'acct' as string | null })); +const accounts = vi.hoisted(() => ({ list: [{ id: 'acct', cookieSlot: 2 }] as { id: string; cookieSlot: number; label?: string }[], active: 'acct' as string | null })); +const contentHidden = vi.hoisted(() => ({ value: false })); +const switchAccount = vi.hoisted(() => vi.fn(async () => {})); vi.mock('next-intl', () => ({ useTranslations: () => (key: string) => key })); vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) })); @@ -16,6 +18,7 @@ vi.mock('@/stores/toast-store', () => ({ toast })); vi.mock('@/lib/device-policy', () => ({ canDownload: () => policy.allowed, canExport: () => true })); vi.mock('@/lib/offline/offline-mode', () => ({ scopeDecided: () => policy.decided })); vi.mock('@/lib/desktop/mail-links', () => ({ openMailLink })); +vi.mock('@/lib/desktop/mail-notifications', () => ({ contentHiddenFor: () => contentHidden.value })); vi.mock('@/lib/launch-handoff', () => ({ handOffDraft })); vi.mock('@/lib/popout/open', () => ({ openDraftWindow })); vi.mock('@/lib/download-guard', () => ({ saveBlobAs })); @@ -36,6 +39,7 @@ vi.mock('@/stores/account-store', () => { }); vi.mock('@/stores/auth-store', () => { const useAuthStore = (select: (s: { activeAccountId: string | null }) => unknown) => select({ activeAccountId: accounts.active }); + useAuthStore.getState = () => ({ activeAccountId: accounts.active, switchAccount }); return { useAuthStore }; }); @@ -43,7 +47,7 @@ import { EditedFilesHost } from '../edited-files-host'; import { resetEditSessions, takeFilesForReply, useEditSessions } from '@/lib/desktop/edit-attachments'; const session = (over: Record = {}) => ({ - id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"mail","emailId":"e1","ownerAccountId":"owner"}', changed: true, version: 1, hash: 'h', claimed: false, ...over, + id: 's1', name: 'a.docx', type: 'x/y', account: 'acct', source: '{"kind":"mail","emailId":"e1","ownerAccountId":"owner"}', changed: true, version: 1, hash: 'h', claimed: false, held: false, savedAs: false, lastChance: false, ...over, }); let bridge: { edit: Record>; dialogs: { confirm: ReturnType }; os: { notify: ReturnType } }; @@ -57,6 +61,7 @@ function show(...sessions: ReturnType[]) { beforeEach(() => { policy.decided = true; policy.allowed = true; + contentHidden.value = false; accounts.list = [{ id: 'acct', cookieSlot: 2 }]; accounts.active = 'acct'; signOutGates.length = 0; @@ -72,8 +77,13 @@ beforeEach(() => { settle: vi.fn(async () => []), read: vi.fn(async () => ({ ok: true, name: 'a.docx', type: 'x/y', data: new Uint8Array([1]), hash: 'h' })), taken: vi.fn(async () => {}), - discard: vi.fn(async () => {}), - clear: vi.fn(async () => {}), + release: vi.fn(async () => {}), + discard: vi.fn(async () => ({ held: [] })), + forceDiscard: vi.fn(async () => ({ held: [] })), + askClear: vi.fn(async () => true), + clear: vi.fn(async () => ({ held: [] })), + wipe: vi.fn(async () => ({ held: [] })), + shown: vi.fn(), setSource: vi.fn(), claim: vi.fn(), onChange: vi.fn(() => () => {}), @@ -174,27 +184,43 @@ describe('other sources', () => { }); describe('discarding', () => { - it('asks first, with keeping as the default', async () => { - bridge.dialogs.confirm.mockResolvedValueOnce(1); + it('goes to main, which asks natively about edits', async () => { show(session()); fireEvent.click(screen.getByRole('button', { name: 'discard a.docx' })); - await waitFor(() => expect(bridge.dialogs.confirm).toHaveBeenCalled()); - expect(bridge.dialogs.confirm.mock.calls[0][0]).toMatchObject({ defaultId: 1 }); - await new Promise((resolve) => setTimeout(resolve, 10)); - expect(bridge.edit.discard).not.toHaveBeenCalled(); - - bridge.dialogs.confirm.mockResolvedValueOnce(0); - fireEvent.click(screen.getByRole('button', { name: 'discard a.docx' })); await waitFor(() => expect(bridge.edit.discard).toHaveBeenCalledWith('s1')); + expect(bridge.dialogs.confirm).not.toHaveBeenCalled(); }); }); describe('the organisation', () => { - it('saying no ends a session and its copy, and says so', async () => { + it('saying no ends a session with no question, says so on the OS, and stays until read', async () => { policy.allowed = false; show(session()); - await waitFor(() => expect(bridge.edit.discard).toHaveBeenCalledWith('s1')); - expect(toast.error).toHaveBeenCalledWith('removed_policy'); + await waitFor(() => expect(bridge.edit.forceDiscard).toHaveBeenCalledWith('s1')); + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('removed_policy', { duration: 0 })); + expect(bridge.edit.discard).not.toHaveBeenCalled(); + await waitFor(() => expect(bridge.os.notify).toHaveBeenCalledWith(expect.objectContaining({ id: 'edit-policy-s1', title: 'removed_policy', body: 'outside_note' }))); + }); + + it('says when a program still has the file', async () => { + policy.allowed = false; + bridge.edit.forceDiscard.mockResolvedValue({ held: ['a.docx'] }); + show(session()); + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('removed_policy_held', { duration: 0 })); + }); + + it('names no file on the OS where that account hides content', async () => { + policy.allowed = false; + contentHidden.value = true; + show(session()); + await waitFor(() => expect(bridge.os.notify).toHaveBeenCalledWith(expect.objectContaining({ title: 'removed_policy_hidden' }))); + }); + + it('does not end a session twice while a program holds it', async () => { + policy.allowed = false; + show(session({ held: true })); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(bridge.edit.forceDiscard).not.toHaveBeenCalled(); }); it('not having said yet deletes nothing, and reads nothing either', async () => { @@ -202,21 +228,107 @@ describe('the organisation', () => { show(session()); fireEvent.click(screen.getByText('save_copy')); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('blocked_policy')); - expect(bridge.edit.discard).not.toHaveBeenCalled(); + expect(bridge.edit.forceDiscard).not.toHaveBeenCalled(); expect(bridge.edit.read).not.toHaveBeenCalled(); }); }); describe('signing out', () => { - it('asks only with edits nobody took, in the account going', async () => { - show(session({ account: 'acct' }), session({ id: 's2', account: 'other', changed: false })); + it('leaves the question to main, whose yes covers the deleting', async () => { + show(session()); expect(signOutGates).toHaveLength(1); - bridge.dialogs.confirm.mockResolvedValueOnce(1); + bridge.edit.askClear.mockResolvedValueOnce(false); await expect(signOutGates[0]('acct')).resolves.toBe(false); - bridge.dialogs.confirm.mockResolvedValueOnce(0); - await expect(signOutGates[0]('acct')).resolves.toBe(true); - bridge.dialogs.confirm.mockClear(); - await expect(signOutGates[0]('other')).resolves.toBe(true); - expect(bridge.dialogs.confirm).not.toHaveBeenCalled(); + expect(bridge.edit.askClear).toHaveBeenCalledWith('acct'); + }); +}); + +describe('what a program still holds', () => { + it('names the file, for an account signed in here, and what the app can\'t reach', () => { + show(session({ held: true, changed: false })); + expect(screen.getByTestId('edited-file-held').textContent).toContain('held_named'); + expect(screen.getByTestId('edited-file-held').textContent).toContain('outside_note'); + expect(screen.queryByTestId('edited-file')).toBeNull(); + }); + + it('names nothing for anyone else, and still says it', () => { + show(session({ held: true, changed: false, account: 'someone-else' })); + const notice = screen.getByTestId('edited-file-held').textContent ?? ''; + expect(notice).toContain('held_unnamed'); + expect(notice).not.toContain('held_named'); + }); + + it('a held file with edits nobody wanted is not offered', () => { + show(session({ held: true, changed: true })); + expect(screen.queryByTestId('edited-file')).toBeNull(); + }); +}); + +describe('the name on the OS', () => { + it('stays off where that account hides content', async () => { + contentHidden.value = true; + show(session()); + await waitFor(() => expect(bridge.os.notify).toHaveBeenCalledWith(expect.objectContaining({ title: 'changed_title_hidden' }))); + }); + + it('shows where it does not', async () => { + show(session()); + await waitFor(() => expect(bridge.os.notify).toHaveBeenCalledWith(expect.objectContaining({ title: 'changed_title' }))); + }); +}); + +describe('more than one account', () => { + it('says which one a file belongs to', () => { + accounts.list = [{ id: 'acct', cookieSlot: 2, label: 'work@example.org' }, { id: 'home', cookieSlot: 3, label: 'home@example.org' }]; + show(session()); + expect(screen.getByTestId('edited-file-account').textContent).toBe('work@example.org'); + }); + + it('with one, there is nothing to say', () => { + show(session()); + expect(screen.queryByTestId('edited-file-account')).toBeNull(); + }); + + it('a new message starts from the file\'s own account', async () => { + accounts.list = [{ id: 'acct', cookieSlot: 2 }, { id: 'home', cookieSlot: 3 }]; + accounts.active = 'home'; + const order: string[] = []; + switchAccount.mockImplementationOnce(async () => { order.push('switch'); }); + handOffDraft.mockImplementationOnce(() => { order.push('handoff'); }); + show(session({ source: '{"kind":"file"}' })); + fireEvent.click(screen.getByText('new_message')); + await waitFor(() => expect(handOffDraft).toHaveBeenCalled()); + expect(switchAccount).toHaveBeenCalledWith('acct'); + expect(order).toEqual(['switch', 'handoff']); + }); + + it('already on it, nothing switches', async () => { + show(session({ source: '{"kind":"file"}' })); + fireEvent.click(screen.getByText('new_message')); + await waitFor(() => expect(handOffDraft).toHaveBeenCalled()); + expect(switchAccount).not.toHaveBeenCalled(); + }); +}); + +describe('the last offer', () => { + it('says so, and tells main it was seen', async () => { + show(session({ lastChance: true })); + expect(screen.getByTestId('edited-file-last-chance')).toBeTruthy(); + await waitFor(() => expect(bridge.edit.shown).toHaveBeenCalledWith('s1')); + }); + + it('an ordinary offer says nothing of it', async () => { + show(session()); + expect(screen.queryByTestId('edited-file-last-chance')).toBeNull(); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(bridge.edit.shown).not.toHaveBeenCalled(); + }); +}); + +describe('a file saved under a new name from a draft', () => { + it('has no draft to open: its own message is what it can go on', () => { + show(session({ source: '{"kind":"draft","draftId":"d1"}', savedAs: true })); + expect(screen.queryByText('open_draft')).toBeNull(); + expect(screen.getByText('new_message')).toBeTruthy(); }); }); diff --git a/components/desktop/edited-files-host.tsx b/components/desktop/edited-files-host.tsx index 4cc594eb0..5eaf7906f 100644 --- a/components/desktop/edited-files-host.tsx +++ b/components/desktop/edited-files-host.tsx @@ -8,6 +8,7 @@ import { useRouter } from "@/i18n/navigation"; import { getDesktopBridge } from "@/lib/desktop/bridge"; import { editForbidden, followEditSessions, getEditBridge, parkFilesForReply, parseEditSource, readEditedFile, useEditSessions } from "@/lib/desktop/edit-attachments"; import { openMailLink } from "@/lib/desktop/mail-links"; +import { contentHiddenFor } from "@/lib/desktop/mail-notifications"; import type { DesktopEditSession } from "@/lib/desktop/types"; import { saveBlobAs } from "@/lib/download-guard"; import { handOffDraft } from "@/lib/launch-handoff"; @@ -29,8 +30,8 @@ function useSignedInAccounts(): Set { * Attachments opened with Edit and saved in their program, with what can be done with them. * A composer offers its own files on the chip, so this has what no composer holds. It stays * until the user has decided: a save may come at any time, also while the app was closed. - * Only for accounts signed in here: someone else signing in doesn't see these. - * Main window only, and nothing at all in a browser. + * Names only for accounts signed in here: someone else signing in doesn't see these, and + * hears only that a copy is still held somewhere. Main window only, nothing in a browser. */ export function EditedFilesHost() { const t = useTranslations("desktopEdit"); @@ -39,6 +40,7 @@ export function EditedFilesHost() { tRef.current = t; const sessions = useEditSessions((s) => s.sessions); const accounts = useSignedInAccounts(); + const accountList = useAccountStore((s) => s.accounts); const [busy, setBusy] = useState(null); const available = !!getEditBridge(); @@ -46,9 +48,13 @@ export function EditedFilesHost() { if (available) followEditSessions(); }, [available]); - const offers = useMemo(() => sessions.filter((s) => s.changed && !s.claimed && accounts.has(s.account)), [sessions, accounts]); + const offers = useMemo(() => sessions.filter((s) => s.changed && !s.claimed && !s.held && accounts.has(s.account)), [sessions, accounts]); + const held = useMemo(() => sessions.filter((s) => s.held), [sessions]); + const heldNames = held.filter((s) => accounts.has(s.account)).map((s) => s.name); + const heldOthers = held.length - heldNames.length; - // Whoever is in the other program sees this. Once per file, not at every save. + // Whoever is in the other program sees this. Once per file, not at every save. A file's + // name can say as much as a subject, so the same rule as for new mail. const toldRef = useRef(new Set()); useEffect(() => { const os = getDesktopBridge()?.os; @@ -57,22 +63,37 @@ export function EditedFilesHost() { toldRef.current.add(session.id); void os?.notify({ id: `edit-${session.id}`, - title: tRef.current("changed_title", { name: session.name }), + title: contentHiddenFor(session.account) ? tRef.current("changed_title_hidden") : tRef.current("changed_title", { name: session.name }), body: tRef.current("changed_body"), context: JSON.stringify({ editedFile: true }), }).catch(() => {}); } }, [offers]); - // The organisation's no ends a session, also one with a file open and edits in it. + // Seen once, so a copy past its 30 days can go a day later. + useEffect(() => { + for (const session of offers) if (session.lastChance) getEditBridge()?.shown(session.id); + }, [offers]); + + // The organisation's no ends a session, also one with a file open and edits in it. Someone + // may be in the other program, so the OS says it as well, and the toast stays until read. useEffect(() => { const bridge = getEditBridge(); if (!bridge) return; const enforce = () => { for (const session of useEditSessions.getState().sessions) { - if (!editForbidden(session.account)) continue; - void bridge.discard(session.id); - toast.error(tRef.current("removed_policy", { name: session.name })); + if (session.held || !editForbidden(session.account)) continue; + void bridge.forceDiscard(session.id).then((result) => { + if (result.refused) return; + const message = tRef.current(result.held.length > 0 ? "removed_policy_held" : "removed_policy", { name: session.name }); + toast.error(message, { duration: 0 }); + void getDesktopBridge()?.os?.notify({ + id: `edit-policy-${session.id}`, + title: contentHiddenFor(session.account) ? tRef.current("removed_policy_hidden") : message, + body: tRef.current("outside_note"), + context: JSON.stringify({ editedFile: true }), + }).catch(() => {}); + }); } }; enforce(); @@ -80,32 +101,21 @@ export function EditedFilesHost() { return () => stops.forEach((stop) => stop()); }, []); - // Edits nobody took: asks before a sign-out the user started. A wipe doesn't. + // Before a sign-out the user started. Main asks, as it's what would delete, and names what a + // program still has open. A wipe doesn't ask. useEffect(() => { - if (!getEditBridge()) return; - return addSignOutGate(async (accountId) => { - const waiting = useEditSessions.getState().sessions.filter((s) => s.account === accountId && s.changed); - const dialogs = getDesktopBridge()?.dialogs; - if (waiting.length === 0 || !dialogs) return true; - const buttons = [tRef.current("signout_confirm"), tRef.current("cancel")]; - const choice = await dialogs.confirm({ - type: "warning", - message: tRef.current("signout_title"), - detail: tRef.current("signout_detail"), - buttons, - defaultId: 1, - }); - return choice === 0; - }); + const bridge = getEditBridge(); + if (!bridge) return; + return addSignOutGate((accountId) => bridge.askClear(accountId)); }, []); - if (!available || offers.length === 0) return null; + if (!available || (offers.length === 0 && held.length === 0)) return null; - const withFile = async (session: DesktopEditSession, then: (file: File, hash: string) => void) => { + const withFile = async (session: DesktopEditSession, then: (file: File, hash: string) => void | Promise) => { setBusy(session.id); try { const outcome = await readEditedFile(session); - if (outcome.ok) then(outcome.file, outcome.hash); + if (outcome.ok) await then(outcome.file, outcome.hash); else if (outcome.reason === "policy") toast.error(t("blocked_policy")); else if (outcome.reason === "busy") toast.error(t("read_busy", { name: session.name })); else if (outcome.reason !== "locked") toast.error(t("read_failed", { name: session.name })); @@ -127,20 +137,21 @@ export function EditedFilesHost() { ); }); + /** From the account the file belongs to, whichever one is on screen. */ + const attachToNew = (session: DesktopEditSession) => withFile(session, async (file) => { + const auth = useAuthStore.getState(); + if (auth.activeAccountId !== session.account) await auth.switchAccount(session.account); + handOffDraft({ files: [file] }); + }); + const saveCopy = (session: DesktopEditSession) => withFile(session, (file, hash) => { if (saveBlobAs(file, file.name, { kind: "attachment", subject: session.account })) void getEditBridge()?.taken(session.id, hash); }); - const discard = async (session: DesktopEditSession) => { - const bridge = getDesktopBridge(); - const choice = await bridge?.dialogs?.confirm({ - type: "warning", - message: t("discard_title", { name: session.name }), - detail: t("discard_detail"), - buttons: [t("discard_confirm"), t("cancel")], - defaultId: 1, - }); - if (choice === 0) await getEditBridge()?.discard(session.id); + const accountLabel = (session: DesktopEditSession) => { + if (accountList.length < 2) return null; + const entry = accountList.find((a) => a.id === session.account); + return entry?.label || entry?.username || null; }; return ( @@ -150,19 +161,30 @@ export function EditedFilesHost() { // Toasts have one corner and the account menu the other, and both have to stay reachable: over the mail columns, under any menu or dialog. className="fixed inset-x-0 bottom-4 z-40 mx-auto flex max-h-[60vh] w-[22rem] max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto" > + {held.length > 0 && ( +
+ {heldNames.length > 0 &&

{t("held_named", { names: heldNames.join(", ") })}

} + {heldOthers > 0 &&

{t("held_unnamed")}

} +

{t("outside_note")}

+
+ )} {offers.map((session) => { const source = parseEditSource(session.source); + const draftId = source.kind === "draft" && !session.savedAs ? source.draftId : null; + const account = accountLabel(session); return (
diff --git a/components/email/__tests__/composer-edit-attachments.test.tsx b/components/email/__tests__/composer-edit-attachments.test.tsx new file mode 100644 index 000000000..a71161ac5 --- /dev/null +++ b/components/email/__tests__/composer-edit-attachments.test.tsx @@ -0,0 +1,316 @@ +// The composer's end of the desktop app's Edit, on the real composer. +import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest'; +import React from 'react'; +import { EmailComposer } from '../email-composer'; +import { resetEditSessions, useEditSessions } from '@/lib/desktop/edit-attachments'; +import { useAuthStore } from '@/stores/auth-store'; + +// ─── Heavy component mocks (mirrors reply-addressing.test.tsx) ──────────────── + +const editorKeyDown = vi.hoisted(() => vi.fn()); +const toastError = vi.hoisted(() => vi.fn()); + +vi.mock('@/lib/offline/offline-mode', async (original) => ({ + ...(await original()), + scopeDecided: () => true, +})); + +vi.mock('@/components/email/rich-text-editor', () => ({ + RichTextEditor: () => React.createElement('div', { + 'data-testid': 'rich-text-editor', + onKeyDown: (event: React.KeyboardEvent) => { + if (!event.defaultPrevented) editorKeyDown(); + }, + }), +})); + +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/components/ui/avatar', () => ({ Avatar: () => null })); +vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null })); +vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null })); +vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null })); +vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null })); +vi.mock('@/hooks/use-focus-trap', () => ({ + useFocusTrap: () => ({ current: null }), +})); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ + useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }), + stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }), +})); + +// ─── Store mocks ────────────────────────────────────────────────────────────── + +vi.mock('@/stores/auth-store', () => { + const state = { + client: null, + identities: [], + primaryIdentity: null, + isAuthenticated: false, + isDemoMode: false, + activeAccountId: null, + connectionLost: false, + getClientForAccount: () => undefined, + getAllConnectedClients: () => new Map(), + syncIdentities: () => {}, + refreshIdentities: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAuthStore: hook }; +}); + +vi.mock('@/stores/identity-store', () => { + const state = { + identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }], + defaultIdentityId: 'id-me', + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useIdentityStore: hook }; +}); + +vi.mock('@/stores/account-store', () => { + const state = { accounts: [], getAccountById: () => undefined }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAccountStore: hook }; +}); + +vi.mock('@/stores/email-store', () => { + const state = { + draftSaveEnabled: false, + sendRawEmail: async () => ({ sent: true }), + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useEmailStore: hook }; +}); + +const updateSetting = vi.fn(); + +vi.mock('@/stores/settings-store', () => { + const state = { + timeFormat: '24h', + plainTextMode: false, + subAddressDelimiter: '+', + autoSelectReplyIdentity: true, + attachmentReminderEnabled: false, + attachmentReminderKeywords: [], + emptySubjectWarningEnabled: true, + sendDelaySeconds: 0, + signaturePosition: 'above_quote', + signatureSeparatorEnabled: false, + requestReadReceiptDefault: false, + addTrustedSender: () => {}, + trustedSendersAddressBook: null, + updateSetting: (...args: unknown[]) => updateSetting(...args), + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useSettingsStore: hook }; +}); + +vi.mock('@/stores/contact-store', () => { + const state = { + contacts: [], + getAutocomplete: async () => [], + addToTrustedSendersBook: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useContactStore: hook }; +}); + +vi.mock('@/stores/template-store', () => { + const state = { templates: [], addTemplate: async () => {} }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useTemplateStore: hook }; +}); + +// ─── Misc dependency mocks ──────────────────────────────────────────────────── + +vi.mock('@/stores/toast-store', () => ({ + toast: { info: () => {}, error: toastError, success: () => {} }, +})); + +vi.mock('@/lib/plugin-hooks', () => ({ + identityHooks: { + onSignatureRender: { size: 0, transform: async (value: unknown) => value }, + onIdentitySelect: { size: 0, emit: async () => {} }, + }, + templateHooks: { + onTemplateRender: { size: 0, transform: async (value: unknown) => value }, + onTemplateApply: { size: 0, emit: async () => {} }, + }, + emailHooks: { + onComposerOpen: { call: async () => [] }, + onRecipientChange: { call: async () => [] }, + getRecipientSuggestions: { call: async () => [] }, + onRecipientChipsChange: { transform: async (chips: unknown) => chips }, + onDraftChange: { emit: () => {} }, + onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft }, + onBeforeEmailSend: { intercept: async () => true, interceptOutcome: async () => 'allowed' }, + onComposeSend: { takeOver: async () => 'default' }, + onTransformOutgoingEmail: { transform: async (email: unknown) => email }, + }, + contactHooks: { + search: { call: async () => [] }, + onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial }, + }, +})); + +vi.mock('@/lib/email-sanitization', () => ({ + sanitizeSignatureHtml: (v: string) => v, + sanitizeEmailHtml: (v: string) => v, + parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'), +})); + +vi.mock('@/lib/email-threading', () => ({ + computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }), +})); +vi.mock('@/lib/signature-utils', () => ({ + appendPlainTextSignature: (body: string) => body, + getPlainTextSignature: () => '', +})); +vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' })); +vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } })); +vi.mock('@/components/email/quoted-html', () => ({ + buildQuotedHtmlBlock: () => '', + serializeEditorContent: () => '', +})); +vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s })); + +// ─── Tests ──────────────────────────────────────────────────────────────────── + +// Discard used to share the X button's path: without unsaved changes it just +// closed, so a draft reopened via "Cancel and edit" stayed in Drafts. + +const REOPENED_DRAFT = { + to: 'bob@example.com', + cc: '', + bcc: '', + subject: 'Lunch', + body: '

Hello there

', + showCc: false, + showBcc: false, + selectedIdentityId: 'id-me', + subAddressTag: '', + mode: 'compose' as const, + draftId: 'draft-1', +}; + +const session = (over: Record = {}) => ({ + id: 's1', name: 'a.txt', type: 'text/plain', account: 'acct', source: '{"kind":"draft","draftId":"draft-1"}', + changed: false, version: 0, hash: 'h', claimed: false, held: false, savedAs: false, lastChance: false, ...over, +}); + +function fakeEdit() { + return { + canEdit: () => true, + begin: vi.fn(), + open: vi.fn(), + reopen: vi.fn(), + list: vi.fn(async () => useEditSessions.getState().sessions), + settle: vi.fn(async () => useEditSessions.getState().sessions), + read: vi.fn(), + taken: vi.fn(async () => {}), + release: vi.fn(async () => {}), + discard: vi.fn(async () => ({ held: [] })), + forceDiscard: vi.fn(async () => ({ held: [] })), + askClear: vi.fn(async () => true), + clear: vi.fn(async () => ({ held: [] })), + wipe: vi.fn(async () => ({ held: [] })), + shown: vi.fn(), + setSource: vi.fn(), + claim: vi.fn(), + onChange: vi.fn(() => () => {}), + }; +} + +const DRAFT_WITH_FILE = { ...REOPENED_DRAFT, attachments: [{ blobId: 'b1', name: 'a.txt', type: 'text/plain', size: 3 }] }; + +describe('the composer with a file open for editing', () => { + let edit: ReturnType; + + beforeEach(() => { + edit = fakeEdit(); + window.bulwarkDesktop = { version: 1, platform: 'win32', edit, dialogs: { confirm: vi.fn(async () => 0) } } as never; + resetEditSessions(); + useAuthStore.setState({ activeAccountId: 'acct' } as never); + }); + + afterEach(() => { + window.bulwarkDesktop = undefined; + useAuthStore.setState({ activeAccountId: null } as never); + }); + + it('a double click on Send, while it looks at the file, sends once', async () => { + useEditSessions.setState({ sessions: [session({ changed: true })] }); + // Both clicks wait on the same answer, so both would go on. + let answer: (value: unknown) => void = () => {}; + const looking = new Promise((resolve) => { answer = resolve; }); + edit.settle.mockImplementation(() => looking as never); + const onSend = vi.fn(async () => {}); + render(); + await screen.findAllByTestId('composer-edit-update'); + + const send = screen.getAllByTestId('composer-send')[0]; + fireEvent.click(send); + fireEvent.click(send); + await act(async () => { answer([session({ changed: true })]); }); + await waitFor(() => expect(onSend).toHaveBeenCalled()); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); }); + expect(onSend).toHaveBeenCalledTimes(1); + // One question, too: each click would otherwise put up its own. + expect((window.bulwarkDesktop as unknown as { dialogs: { confirm: ReturnType } }).dialogs.confirm).toHaveBeenCalledTimes(1); + }); + + it('with nothing open for editing, Send looks at nothing', async () => { + const onSend = vi.fn(async () => {}); + render(); + fireEvent.click(screen.getAllByTestId('composer-send')[0]); + await waitFor(() => expect(onSend).toHaveBeenCalled()); + expect(edit.settle).not.toHaveBeenCalled(); + }); + + const forward = (phishingMarked: boolean) => ( + + ); + + it('a part forwarded from an ordinary message has Edit', async () => { + render(forward(false)); + expect(await screen.findByTestId('composer-edit')).toBeTruthy(); + }); + + it('a part forwarded from a message marked as phishing has none', async () => { + render(forward(true)); + await screen.findByText('a.txt'); + expect(screen.queryByTestId('composer-edit')).toBeNull(); + }); + + it('the mark stays on the part through a hand-over to another window', async () => { + render(); + await screen.findByText('a.txt'); + expect(screen.queryByTestId('composer-edit')).toBeNull(); + }); +}); diff --git a/components/email/__tests__/edit-attachment-gates.test.tsx b/components/email/__tests__/edit-attachment-gates.test.tsx new file mode 100644 index 000000000..de7c3b84d --- /dev/null +++ b/components/email/__tests__/edit-attachment-gates.test.tsx @@ -0,0 +1,141 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Email, Mailbox } from '@/lib/jmap/types'; +import { PHISHING_KEYWORD } from '@/lib/phishing-report'; + +// Where a message's attachment gets Edit, on the real components with the real check. Only +// the organisation's answer is stood in for: whether it has spoken, which needs a server. + +vi.mock('@/lib/offline/offline-mode', async (original) => ({ + ...(await original()), + scopeDecided: () => true, +})); +vi.mock('@/hooks/use-media-query', () => ({ + useDeviceDetection: () => ({ isMobile: false, isTablet: false, isDesktop: true }), + useMediaQuery: () => false, +})); +vi.mock('@/components/tour/tour-provider', () => ({ + useTour: () => ({ activeTour: null, startTour: vi.fn(), endTour: vi.fn(), registerStep: vi.fn() }), +})); +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/hooks/use-plugin-slot-offers', () => ({ usePluginSlotOffers: () => [] })); +vi.mock('@/hooks/use-wopi-status', () => ({ useWopiStatus: () => ({ enabled: false }), canWopiOpen: () => false })); +vi.mock('@/hooks/use-own-domain-address', () => ({ useOwnDomainAddress: () => () => false })); + +class NoopResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +} +vi.stubGlobal('ResizeObserver', NoopResizeObserver); + +const { EmailViewer } = await import('../email-viewer'); +const { ThreadConversationView } = await import('../thread-conversation-view'); +const { useAuthStore } = await import('@/stores/auth-store'); + +const mailboxes = [{ id: 'inbox', name: 'Inbox', role: 'inbox', parentId: null, myRights: { mayAddItems: true } }] as unknown as Mailbox[]; + +const part = (over: Record = {}) => ({ partId: '2', blobId: 'blob-1', name: 'report.docx', type: 'application/octet-stream', size: 10, disposition: 'attachment', ...over }); + +function makeEmail(attachment: Record, keywords: Record = { $seen: true }): Email { + return { + id: 'e1', blobId: 'b1', threadId: 't1', mailboxIds: { inbox: true }, keywords, + from: [{ name: 'Alice', email: 'alice@example.com' }], to: [{ name: 'Bob', email: 'bob@example.com' }], + subject: 'Hello', receivedAt: '2026-01-01T00:00:00Z', preview: 'Hello', hasAttachment: true, size: 100, + textBody: [{ partId: '1', type: 'text/plain' }], htmlBody: [{ partId: '1', type: 'text/plain' }], + attachments: [attachment], bodyValues: { 1: { value: 'Hello' } }, + } as unknown as Email; +} + +/** Answers anything the views ask of a client with nothing. */ +const fakeClient = new Proxy({}, { get: (_target, name) => (name === 'then' ? undefined : () => undefined) }); + +let popup: ReturnType; + +beforeEach(() => { + popup = vi.fn(async () => null); + window.bulwarkDesktop = { + version: 1, + platform: 'win32', + menu: { setState: () => {}, popup }, + // The shell's list, for the ones used here. + edit: { canEdit: (name: string) => /\.(docx|txt)$/.test(name), list: async () => [], onChange: () => () => {} }, + } as never; + useAuthStore.setState({ activeAccountId: 'acct', client: fakeClient } as never); +}); + +afterEach(() => { + cleanup(); + window.bulwarkDesktop = undefined; + useAuthStore.setState({ activeAccountId: null, client: null } as never); +}); + +async function viewerMenu(email: Email): Promise<(string | undefined)[]> { + render(); + const tile = await screen.findByTestId('attachment'); + fireEvent.contextMenu(tile.parentElement ?? tile, { clientX: 5, clientY: 5 }); + await waitFor(() => expect(popup).toHaveBeenCalled()); + return (popup.mock.calls[0][0] as { label?: string }[]).map((item) => item.label); +} + +describe('the reader', () => { + it('offers Edit on a part with a blob', async () => { + expect(await viewerMenu(makeEmail(part()))).toContain('edit'); + }); + + it('has none on a message marked as phishing', async () => { + expect(await viewerMenu(makeEmail(part(), { $seen: true, [PHISHING_KEYWORD]: true }))).not.toContain('edit'); + }); + + it('has none on a part with no blob, which is how a decrypted part reaches it', async () => { + expect(await viewerMenu(makeEmail(part({ blobId: '', tnefData: new Uint8Array([1]) })))).not.toContain('edit'); + }); + + it('has none for a file the shell keeps out', async () => { + expect(await viewerMenu(makeEmail(part({ name: 'run.bat' })))).not.toContain('edit'); + }); +}); + +function conversation(email: Email) { + render( + {}} + />, + ); +} + +describe('the conversation view', () => { + const edit = () => screen.queryByRole('button', { name: 'desktopEdit.edit_named' }); + + it('offers Edit on a part with a blob', async () => { + conversation(makeEmail(part())); + await waitFor(() => expect(edit()).not.toBeNull()); + }); + + it('has none on a message marked as phishing', async () => { + conversation(makeEmail(part(), { $seen: true, [PHISHING_KEYWORD]: true })); + await screen.findByText(/report\.docx/); + expect(edit()).toBeNull(); + }); + + it('has none on a part with no blob', async () => { + conversation(makeEmail(part({ blobId: '' }))); + await screen.findByText(/report\.docx/); + expect(edit()).toBeNull(); + }); + + it('has none for a file the shell keeps out', async () => { + conversation(makeEmail(part({ name: 'run.bat' }))); + await screen.findByText(/run\.bat/); + expect(edit()).toBeNull(); + }); + + it('has none in a browser', async () => { + window.bulwarkDesktop = undefined; + conversation(makeEmail(part())); + await screen.findByText(/report\.docx/); + expect(edit()).toBeNull(); + }); +}); diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx index beb816e70..61f0724f6 100644 --- a/components/email/email-composer.tsx +++ b/components/email/email-composer.tsx @@ -278,7 +278,7 @@ export interface ComposerDraftData { * File). Without these the composer starts with zero attachments and the * next save/send rebuilds the draft without them - silent data loss (#849). */ - attachments?: Array<{ blobId: string; name?: string; type?: string; size: number; cid?: string; disposition?: string; sourceAccountId?: string }>; + attachments?: Array<{ blobId: string; name?: string; type?: string; size: number; cid?: string; disposition?: string; sourceAccountId?: string; editBlocked?: boolean }>; /** The send options picked so far; absent, the defaults. Carried to another window. */ requestReadReceipt?: boolean; requestDsn?: boolean; @@ -475,6 +475,8 @@ interface EmailComposerProps { quoteWrapInBlockquote?: boolean; /** The original's headers: a reply or forward starts with its classification label. */ headers?: Record; + /** The original carries the phishing mark: its forwarded parts stay out of the desktop app's Edit. */ + phishingMarked?: boolean; /** The original's From, when `from` is left out (a forward as attachment): whether its label counts. */ originalFrom?: { email?: string; name?: string }[]; }; @@ -488,6 +490,8 @@ type ComposerAttachment = { // on a forward - the message may go out through another account, which // cannot resolve them. See rehomeForeignBlobs. sourceAccountId?: string; + // From a message marked as phishing: stays out of the desktop app's Edit. + editBlocked?: boolean; name: string; type: string; size: number; @@ -1118,6 +1122,7 @@ export function EmailComposer({ // A forward stashed before its first save still holds the original // account's blobs: keep the tag so they are copied before saving. ...(att.sourceAccountId ? { sourceAccountId: att.sourceAccountId } : {}), + ...(att.editBlocked ? { editBlocked: true } : {}), fromDraftPart: true, })); } @@ -1146,6 +1151,7 @@ export function EmailComposer({ size: att.size, blobId: att.blobId, sourceAccountId: att.sourceAccountId ?? sourceAccountId ?? undefined, + ...(replyTo.phishingMarked ? { editBlocked: true } : {}), })); } return []; @@ -2752,9 +2758,13 @@ export function EmailComposer({ // The desktop app: files dropped or pasted anywhere on the window come here, if this one's on screen. const loadAttachmentForEdit = useCallback(async (att: ComposerAttachment): Promise => { if (att.file) return att.file; - if (!composerClient || !att.blobId) throw new Error('No content for this attachment'); - return composerClient.fetchBlob(att.blobId, att.name, att.type); - }, [composerClient]); + // A forwarded part lives in its own login until the draft is saved through another. + const owner = att.sourceAccountId && att.sourceAccountId !== composerAccountId + ? useAuthStore.getState().getClientForAccount(att.sourceAccountId) + : composerClient; + if (!owner || !att.blobId) throw new Error('No content for this attachment'); + return owner.fetchBlob(att.blobId, att.name, att.type); + }, [composerClient, composerAccountId]); const composerEdits = useComposerEdits({ attachments, setAttachments, @@ -3675,6 +3685,7 @@ export function EmailComposer({ }, [attachments]); const [isWaitingForUploads, setIsWaitingForUploads] = useState(false); const sendCancelledRef = useRef(false); + const confirmingSendRef = useRef(false); // The user confirmed sending without a subject for this message. const emptySubjectConfirmedRef = useRef(false); // Placeholders the user chose to send as they are. The warning comes back @@ -3729,7 +3740,17 @@ export function EmailComposer({ if (isSendingRef.current) return; // Saved in another program and not on this message yet: not silently the older one. - if (!(await composerEdits.confirmSend())) return; + // The wait lets a second click in, so that one goes no further. + if (composerEdits.holdsEdits()) { + if (confirmingSendRef.current) return; + confirmingSendRef.current = true; + try { + if (!(await composerEdits.confirmSend())) return; + } finally { + confirmingSendRef.current = false; + } + if (isSendingRef.current) return; + } if (attachmentsRef.current.some(att => att.uploading)) { isSendingRef.current = true; @@ -5427,7 +5448,7 @@ export function EmailComposer({ {tEdit('update')} )} - {!att.uploading && !att.error && composerEdits.canEdit(att.name) && ( + {!att.uploading && !att.error && composerEdits.canEditChip(att) && (