diff --git a/.changeset/web-errors-focus-downloads.md b/.changeset/web-errors-focus-downloads.md new file mode 100644 index 0000000..3e0044c --- /dev/null +++ b/.changeset/web-errors-focus-downloads.md @@ -0,0 +1,6 @@ +--- +'@crypt.fyi/core': patch +'@crypt.fyi/web': patch +--- + +Explain why creating a secret failed when it is too large for the server or the request was rate limited, instead of showing "unexpected status code 413/429". After creating a secret, and on each recipient screen, focus moves to the new heading. Links whose `?p=true` was stripped still ask for the password, and shared files only download from data embedded in the secret. Core adds the matching translations. diff --git a/packages/core/src/i18n/locales/de.ts b/packages/core/src/i18n/locales/de.ts index 9d53729..bfbecb7 100644 --- a/packages/core/src/i18n/locales/de.ts +++ b/packages/core/src/i18n/locales/de.ts @@ -231,6 +231,9 @@ export const de: TranslationKeys = { fileSizeExceeded: 'Datei ist zu groß. Maximale Größe ist {{max}}.', fileReadError: 'Fehler beim Lesen der Datei', fileReadAborted: 'Dateilesen wurde abgebrochen', + tooLarge: + 'Dieses Geheimnis ist zu groß für den Server. Versuche es mit einer kleineren Datei oder weniger Text.', + rateLimited: 'Zu viele Anfragen. Warte einen Moment und versuche es erneut.', }, }, view: { @@ -299,6 +302,8 @@ export const de: TranslationKeys = { content: { fileShared: 'Eine Datei wurde mit Ihnen geteilt', downloadFile: 'Datei herunterladen', + downloadFailed: + 'Diese Datei kann nicht heruntergeladen werden, weil ihr Inhalt nicht im Geheimnis enthalten ist.', hideContent: 'Inhalt verbergen', showContent: 'Inhalt anzeigen', copyToClipboard: 'In die Zwischenablage kopieren', diff --git a/packages/core/src/i18n/locales/en.ts b/packages/core/src/i18n/locales/en.ts index fda2306..3692865 100644 --- a/packages/core/src/i18n/locales/en.ts +++ b/packages/core/src/i18n/locales/en.ts @@ -228,6 +228,8 @@ export const en: TranslationKeys = { fileSizeExceeded: 'File is too large. Maximum size is {{max}}.', fileReadError: 'Failed to read file', fileReadAborted: 'File reading was aborted', + tooLarge: 'This secret is too large for the server. Try a smaller file or less text.', + rateLimited: 'Too many requests. Wait a moment and try again.', }, }, view: { @@ -293,6 +295,8 @@ export const en: TranslationKeys = { content: { fileShared: 'A file has been shared with you', downloadFile: 'Download File', + downloadFailed: + "This file can't be downloaded because its contents are not embedded in the secret.", hideContent: 'Hide content', showContent: 'Show content', copyToClipboard: 'Copy to clipboard', diff --git a/packages/core/src/i18n/locales/es.ts b/packages/core/src/i18n/locales/es.ts index abd5140..00e3a02 100644 --- a/packages/core/src/i18n/locales/es.ts +++ b/packages/core/src/i18n/locales/es.ts @@ -232,6 +232,9 @@ export const es: TranslationKeys = { fileSizeExceeded: 'El archivo es demasiado grande. El tamaño máximo es {{max}}.', fileReadError: 'Error al leer el archivo', fileReadAborted: 'La lectura del archivo fue interrumpida', + tooLarge: + 'Este secreto es demasiado grande para el servidor. Prueba con un archivo más pequeño o menos texto.', + rateLimited: 'Demasiadas solicitudes. Espera un momento y vuelve a intentarlo.', }, }, view: { @@ -298,6 +301,8 @@ export const es: TranslationKeys = { content: { fileShared: 'Se ha compartido un archivo contigo', downloadFile: 'Descargar Archivo', + downloadFailed: + 'Este archivo no se puede descargar porque su contenido no está incluido en el secreto.', hideContent: 'Ocultar contenido', showContent: 'Mostrar contenido', copyToClipboard: 'Copiar al portapapeles', diff --git a/packages/core/src/i18n/locales/fr.ts b/packages/core/src/i18n/locales/fr.ts index bff3ba2..8cfa43a 100644 --- a/packages/core/src/i18n/locales/fr.ts +++ b/packages/core/src/i18n/locales/fr.ts @@ -232,6 +232,9 @@ export const fr: TranslationKeys = { fileSizeExceeded: 'Le fichier est trop volumineux. La taille maximale est {{max}}.', fileReadError: 'Échec de la lecture du fichier', fileReadAborted: 'La lecture du fichier a été interrompue', + tooLarge: + 'Ce secret est trop volumineux pour le serveur. Essayez un fichier plus petit ou moins de texte.', + rateLimited: 'Trop de requêtes. Patientez un instant puis réessayez.', }, }, view: { @@ -298,6 +301,8 @@ export const fr: TranslationKeys = { content: { fileShared: 'Un fichier a été partagé avec vous', downloadFile: 'Télécharger le Fichier', + downloadFailed: + "Ce fichier ne peut pas être téléchargé, car son contenu n'est pas inclus dans le secret.", hideContent: 'Masquer le contenu', showContent: 'Afficher le contenu', copyToClipboard: 'Copier dans le presse-papiers', diff --git a/packages/core/src/i18n/locales/zh.ts b/packages/core/src/i18n/locales/zh.ts index a5fd1ec..7929a7a 100644 --- a/packages/core/src/i18n/locales/zh.ts +++ b/packages/core/src/i18n/locales/zh.ts @@ -222,6 +222,8 @@ export const zh: TranslationKeys = { fileSizeExceeded: '文件过大。最大大小为 {{max}}。', fileReadError: '读取文件失败', fileReadAborted: '文件读取已中止', + tooLarge: '此密文过大,服务器无法接收。请尝试更小的文件或更少的文本。', + rateLimited: '请求过多。请稍后再试。', }, }, view: { @@ -283,6 +285,7 @@ export const zh: TranslationKeys = { content: { fileShared: '有人与您分享了一个文件', downloadFile: '下载文件', + downloadFailed: '无法下载此文件,因为其内容未包含在密文中。', hideContent: '隐藏内容', showContent: '显示内容', copyToClipboard: '复制到剪贴板', diff --git a/packages/core/src/i18n/types.ts b/packages/core/src/i18n/types.ts index 50a8913..c30cb4e 100644 --- a/packages/core/src/i18n/types.ts +++ b/packages/core/src/i18n/types.ts @@ -212,6 +212,8 @@ export interface TranslationKeys { fileSizeExceeded: string; fileReadError: string; fileReadAborted: string; + tooLarge: string; + rateLimited: string; }; }; view: { @@ -269,6 +271,7 @@ export interface TranslationKeys { content: { fileShared: string; downloadFile: string; + downloadFailed: string; hideContent: string; showContent: string; copyToClipboard: string; diff --git a/packages/web/e2e/focus.spec.ts b/packages/web/e2e/focus.spec.ts new file mode 100644 index 0000000..726654f --- /dev/null +++ b/packages/web/e2e/focus.spec.ts @@ -0,0 +1,35 @@ +import { test, expect } from './fixtures'; +import { createTextSecret } from './helpers'; + +test.describe('focus and link handling', () => { + test('moves focus to the result after creating and opening a secret', async ({ page }) => { + await page.goto('/new'); + await page.getByLabel('Secret content').fill(`playwright-focus-${Date.now()}`); + await page.getByRole('button', { name: 'Create' }).click(); + await expect(page.getByRole('heading', { name: 'Secret Created!' })).toBeFocused(); + + await page.getByRole('button', { name: 'Show secret URL' }).first().click(); + const combinedUrl = await page.locator('#combined-url').inputValue(); + + await page.goto(combinedUrl); + await expect( + page.getByRole('heading', { name: 'Someone shared a secret with you' }), + ).toBeFocused(); + }); + + test('asks for the password when ?p=true was stripped from the link', async ({ page }) => { + const secret = `playwright-stripped-${Date.now()}`; + const password = `pw-${Date.now()}`; + const combinedUrl = await createTextSecret(page, secret, { password }); + + const stripped = new URL(combinedUrl); + stripped.search = ''; + await page.goto('/new'); + await page.goto(stripped.toString()); + await expect(page.getByRole('heading', { name: 'Enter Password' })).toBeVisible(); + + await page.locator('#secret-password').fill(password); + await page.getByRole('button', { name: 'Unlock secret' }).click(); + await expect(page.getByLabel('Secret content')).toHaveText(secret); + }); +}); diff --git a/packages/web/src/components/StatusCard.tsx b/packages/web/src/components/StatusCard.tsx index acbb16e..3ec22b3 100644 --- a/packages/web/src/components/StatusCard.tsx +++ b/packages/web/src/components/StatusCard.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { useCallback, type ReactNode } from 'react'; import { Card } from '@/components/ui/card'; /** Shared shell for every "here is what happened, here is what to do" recipient state. */ @@ -6,16 +6,34 @@ export function StatusCard({ title, description, children, + focusTitle = true, }: { title: string; description?: ReactNode; children?: ReactNode; + /** + * Move focus to the title when the card appears, so keyboard and screen + * reader users land on the new state instead of the page body. Turn off when + * the card's content focuses a field itself. + */ + focusTitle?: boolean; }) { + const titleRef = useCallback( + (node: HTMLHeadingElement | null) => { + if (focusTitle) node?.focus(); + }, + [focusTitle], + ); + return (
-

+

{title}

{description &&
{description}
} diff --git a/packages/web/src/lib/createError.test.ts b/packages/web/src/lib/createError.test.ts new file mode 100644 index 0000000..cd0ebc0 --- /dev/null +++ b/packages/web/src/lib/createError.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; +import { ErrorUnexpectedStatus } from '@crypt.fyi/core'; +import { describeCreateError } from './createError'; + +const t = (key: string) => `translated:${key}`; + +describe('describeCreateError', () => { + it('explains a rejected oversized secret', () => { + expect(describeCreateError(new ErrorUnexpectedStatus(413), t)).toBe( + 'translated:create.errors.tooLarge', + ); + }); + + it('explains rate limiting', () => { + expect(describeCreateError(new ErrorUnexpectedStatus(429), t)).toBe( + 'translated:create.errors.rateLimited', + ); + }); + + it('keeps other messages', () => { + expect(describeCreateError(new ErrorUnexpectedStatus(500), t)).toBe( + 'unexpected status code 500', + ); + expect(describeCreateError(new Error('boom'), t)).toBe('boom'); + }); +}); diff --git a/packages/web/src/lib/createError.ts b/packages/web/src/lib/createError.ts new file mode 100644 index 0000000..00c8222 --- /dev/null +++ b/packages/web/src/lib/createError.ts @@ -0,0 +1,16 @@ +import { ErrorUnexpectedStatus } from '@crypt.fyi/core'; + +type Translate = (key: 'create.errors.tooLarge' | 'create.errors.rateLimited') => string; + +/** + * User-facing message for a failed create. The server's body limit can be well + * below the file size the form accepts once the content is encoded and + * encrypted, so a 413 needs to say what went wrong rather than show the status. + */ +export function describeCreateError(error: Error, t: Translate): string { + if (error instanceof ErrorUnexpectedStatus) { + if (error.status === 413) return t('create.errors.tooLarge'); + if (error.status === 429) return t('create.errors.rateLimited'); + } + return error.message; +} diff --git a/packages/web/src/lib/secretUrl.test.ts b/packages/web/src/lib/secretUrl.test.ts index 35f43d9..c7f7495 100644 --- a/packages/web/src/lib/secretUrl.test.ts +++ b/packages/web/src/lib/secretUrl.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { buildSecretLinks, migrateLegacyQueryKey } from './secretUrl'; +import { + buildSecretLinks, + isPasswordProtectedLink, + migrateLegacyQueryKey, + safeFileDownloadUrl, +} from './secretUrl'; describe('buildSecretLinks', () => { it('returns both URL forms and keeps the combined QR behavior', () => { @@ -62,3 +67,27 @@ describe('migrateLegacyQueryKey', () => { expect(url.toString()).toBe('https://crypt.example/vault-id?keep=true#fragment-key'); }); }); + +describe('isPasswordProtectedLink', () => { + it('uses the p query parameter', () => { + expect(isPasswordProtectedLink(true, 'legacy-key')).toBe(true); + expect(isPasswordProtectedLink(undefined, '')).toBe(false); + }); + + it('recognises a password-protected key when the query was stripped', () => { + expect(isPasswordProtectedLink(undefined, '2.decryption-key')).toBe(true); + expect(isPasswordProtectedLink(undefined, 'decryption-key')).toBe(false); + }); +}); + +describe('safeFileDownloadUrl', () => { + it('allows inline data URLs', () => { + expect(safeFileDownloadUrl('data:text/plain;base64,aGk=')).toBe('data:text/plain;base64,aGk='); + }); + + it('rejects links to other locations', () => { + expect(safeFileDownloadUrl('https://example.com/file.pdf')).toBeUndefined(); + expect(safeFileDownloadUrl('javascript:alert(1)')).toBeUndefined(); + expect(safeFileDownloadUrl(undefined)).toBeUndefined(); + }); +}); diff --git a/packages/web/src/lib/secretUrl.ts b/packages/web/src/lib/secretUrl.ts index 00764b5..e4ad18a 100644 --- a/packages/web/src/lib/secretUrl.ts +++ b/packages/web/src/lib/secretUrl.ts @@ -1,3 +1,5 @@ +import { parseKey } from '@crypt.fyi/core'; + interface SecretLinksInput { origin: string; id: string; @@ -52,3 +54,21 @@ export function migrateLegacyQueryKey(url: URL): boolean { return true; } + +/** + * Whether a link is password protected. Some apps strip the `?p=true` query, + * but a key with the v2 prefix is only issued for password-protected secrets, + * so the fragment alone is enough to ask for the password. + */ +export function isPasswordProtectedLink(passwordParam: unknown, fragmentKey: string): boolean { + return Boolean(passwordParam) || (fragmentKey !== '' && parseKey(fragmentKey).scheme === 'v2'); +} + +/** + * The URL of a file the sender shared, or undefined when it is not an inline + * data URL. The sender controls this value, so anything else (for example an + * https link to another site) must not be opened as a download. + */ +export function safeFileDownloadUrl(content: unknown): string | undefined { + return typeof content === 'string' && content.startsWith('data:') ? content : undefined; +} diff --git a/packages/web/src/pages/Create.tsx b/packages/web/src/pages/Create.tsx index 76cea05..65641ae 100644 --- a/packages/web/src/pages/Create.tsx +++ b/packages/web/src/pages/Create.tsx @@ -3,7 +3,7 @@ import { Resolver, useForm } from 'react-hook-form'; import { z } from 'zod'; import { sha256, ErrorNotFound, sleep } from '@crypt.fyi/core'; import { motion, AnimatePresence } from 'framer-motion'; -import { useEffect, useMemo, DragEvent } from 'react'; +import { useCallback, useEffect, useMemo, DragEvent } from 'react'; import { Form, FormControl, @@ -68,6 +68,7 @@ import { Pill } from '@/components/ui/pill'; import { Switch } from '@/components/ui/switch'; import { buildSecretLinks } from '@/lib/secretUrl'; import type { SecretLinks } from '@/lib/secretUrl'; +import { describeCreateError } from '@/lib/createError'; const VALID_FILE_TYPES = ['Files', 'text/plain', 'text/uri-list', 'text/html']; const MAX_FILE_SIZE = 1 * 1024 * 1024; @@ -461,13 +462,17 @@ export function CreatePage() { }; }, onError(error) { - toast.error(error.message); + toast.error(describeCreateError(error, t)); }, gcTime: 0, }); const [selectedFile, setSelectedFile] = useState(null); + // The form, including the focused submit button, unmounts when the secret is + // created; move focus to the result so it isn't dropped on the page body. + const focusOnMount = useCallback((node: HTMLElement | null) => node?.focus(), []); + const handleFiles = async (files: File[]) => { if (files.length > 0) { const file = files[0]; @@ -1130,7 +1135,11 @@ export function CreatePage() { className="mx-auto max-w-2xl space-y-5" >
-

+

{t('create.success.title')}

diff --git a/packages/web/src/pages/View.tsx b/packages/web/src/pages/View.tsx index 8c3f5ed..8e17727 100644 --- a/packages/web/src/pages/View.tsx +++ b/packages/web/src/pages/View.tsx @@ -22,6 +22,7 @@ import { } from '@crypt.fyi/core'; import { useTranslation } from 'react-i18next'; import { useClient } from '@/context/client'; +import { isPasswordProtectedLink, safeFileDownloadUrl } from '@/lib/secretUrl'; export function ViewPage() { const { id } = useParams({ from: '/$id' }); @@ -29,7 +30,13 @@ export function ViewPage() { // TanStack reuses this file-route component across vault IDs. Bound all // key-bearing local state to the public vault ID without keying on the hash. - return ; + return ( + + ); } interface VaultViewProps { @@ -308,8 +315,13 @@ function VaultView({ id, isPasswordSet }: VaultViewProps) { title={t('view.content.fileShared')} label={t('view.content.downloadFile')} onDownload={() => { + const href = safeFileDownloadUrl(fileData.content); + if (!href) { + toast.error(t('view.content.downloadFailed')); + return; + } const link = document.createElement('a'); - link.href = fileData.content; + link.href = href; link.download = fileData.name; link.click(); }} @@ -425,7 +437,11 @@ function CredentialsForm({ }; return ( - {description}

}> + {description}

} + focusTitle={false} + >
{showKeyField && (