Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/web-errors-focus-downloads.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions packages/core/src/i18n/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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',
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/i18n/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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',
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/i18n/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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',
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/i18n/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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',
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/i18n/locales/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ export const zh: TranslationKeys = {
fileSizeExceeded: '文件过大。最大大小为 {{max}}。',
fileReadError: '读取文件失败',
fileReadAborted: '文件读取已中止',
tooLarge: '此密文过大,服务器无法接收。请尝试更小的文件或更少的文本。',
rateLimited: '请求过多。请稍后再试。',
},
},
view: {
Expand Down Expand Up @@ -283,6 +285,7 @@ export const zh: TranslationKeys = {
content: {
fileShared: '有人与您分享了一个文件',
downloadFile: '下载文件',
downloadFailed: '无法下载此文件,因为其内容未包含在密文中。',
hideContent: '隐藏内容',
showContent: '显示内容',
copyToClipboard: '复制到剪贴板',
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/i18n/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ export interface TranslationKeys {
fileSizeExceeded: string;
fileReadError: string;
fileReadAborted: string;
tooLarge: string;
rateLimited: string;
};
};
view: {
Expand Down Expand Up @@ -269,6 +271,7 @@ export interface TranslationKeys {
content: {
fileShared: string;
downloadFile: string;
downloadFailed: string;
hideContent: string;
showContent: string;
copyToClipboard: string;
Expand Down
35 changes: 35 additions & 0 deletions packages/web/e2e/focus.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
22 changes: 20 additions & 2 deletions packages/web/src/components/StatusCard.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
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. */
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 (
<div className="mx-auto w-full max-w-xl pt-4 sm:pt-12">
<Card className="flex flex-col items-start gap-4 p-6 sm:p-8">
<div className="space-y-2">
<h1 className="font-display text-2xl font-semibold tracking-tight sm:text-3xl">
<h1
ref={titleRef}
tabIndex={-1}
className="font-display text-2xl font-semibold tracking-tight outline-none sm:text-3xl"
>
{title}
</h1>
{description && <div className="text-muted-foreground">{description}</div>}
Expand Down
26 changes: 26 additions & 0 deletions packages/web/src/lib/createError.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
16 changes: 16 additions & 0 deletions packages/web/src/lib/createError.ts
Original file line number Diff line number Diff line change
@@ -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;
}
31 changes: 30 additions & 1 deletion packages/web/src/lib/secretUrl.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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();
});
});
20 changes: 20 additions & 0 deletions packages/web/src/lib/secretUrl.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { parseKey } from '@crypt.fyi/core';

interface SecretLinksInput {
origin: string;
id: string;
Expand Down Expand Up @@ -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;
}
15 changes: 12 additions & 3 deletions packages/web/src/pages/Create.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -461,13 +462,17 @@ export function CreatePage() {
};
},
onError(error) {
toast.error(error.message);
toast.error(describeCreateError(error, t));
},
gcTime: 0,
});

const [selectedFile, setSelectedFile] = useState<File | null>(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];
Expand Down Expand Up @@ -1130,7 +1135,11 @@ export function CreatePage() {
className="mx-auto max-w-2xl space-y-5"
>
<div className="space-y-1.5">
<h2 className="flex items-center gap-2.5 font-display text-2xl font-semibold tracking-tight sm:text-3xl">
<h2
ref={focusOnMount}
tabIndex={-1}
className="flex items-center gap-2.5 font-display text-2xl font-semibold tracking-tight outline-none sm:text-3xl"
>
<IconLock className="size-6 shrink-0 text-sealed" aria-hidden />
{t('create.success.title')}
</h2>
Expand Down
Loading
Loading