diff --git a/src/adapters/browser-files/download-delivery-adapter.ts b/src/adapters/browser-files/download-delivery-adapter.ts index 7d89cba3..04159ca3 100644 --- a/src/adapters/browser-files/download-delivery-adapter.ts +++ b/src/adapters/browser-files/download-delivery-adapter.ts @@ -324,17 +324,10 @@ export function createDownloadDeliveryAdapter( dependencies.observer, ); } - let suggestedFileName: string; + // Q-6.2-10. Validation already sanitized the name; it is not redone. + const suggestedFileName = validation.value; let transferId: string; try { - suggestedFileName = sanitizeSuggestedFileName( - activeInput.suggestedFileName, - { - safeExtension: activeInput.safeExtension, - maxUtf8Bytes: - dependencies.filenameMaxUtf8Bytes, - } satisfies SuggestedFileNamePolicy, - ); transferId = createTransferId(); } catch { return observeResult( @@ -946,7 +939,7 @@ function validateDownloadInput( input: DeliveryInput, options: DownloadDeliveryAdapterOptions, userActivation: Readonly<{ isActive: boolean }> | undefined, -): BrowserDataResult { +): BrowserDataResult { if ( input.signal.aborted || input.suggestedFileName.length === 0 || @@ -1016,14 +1009,15 @@ function validateDownloadInput( return browserDataFailure("PERMISSION_DENIED", "DOWNLOAD"); } try { - sanitizeSuggestedFileName(input.suggestedFileName, { - safeExtension: input.safeExtension, - maxUtf8Bytes: options.filenameMaxUtf8Bytes, - }); + return browserDataSuccess( + sanitizeSuggestedFileName(input.suggestedFileName, { + safeExtension: input.safeExtension, + maxUtf8Bytes: options.filenameMaxUtf8Bytes, + } satisfies SuggestedFileNamePolicy), + ); } catch { return browserDataFailure("INVALID_INPUT", "DOWNLOAD"); } - return browserDataSuccess(true); } /** diff --git a/src/adapters/browser-files/file-policy.ts b/src/adapters/browser-files/file-policy.ts index 455a4f57..676ec6f2 100644 --- a/src/adapters/browser-files/file-policy.ts +++ b/src/adapters/browser-files/file-policy.ts @@ -354,12 +354,7 @@ export function sanitizeSuggestedFileName( base = fallbackBase.length > 0 ? fallbackBase : "download"; } - while ( - base.length > 0 && - utf8Length(`${base}${safeExtension}`) > maxUtf8Bytes - ) { - base = Array.from(base).slice(0, -1).join("").trimEnd(); - } + base = truncateUtf8(base, maxUtf8Bytes - utf8Length(safeExtension)); if (base.length === 0 || WINDOWS_RESERVED.test(base)) { base = fallbackBase; } @@ -401,21 +396,36 @@ function utf8Length(value: string): number { return new TextEncoder().encode(value).byteLength; } +/** + * Q-6.2-10. The longest code-point prefix within `maxBytes` UTF-8 bytes, with + * trailing whitespace removed once it was cut; `value` itself when it fits. + * One pass: re-encoding the whole name per dropped code point was O(n^2). + */ +function truncateUtf8(value: string, maxBytes: number): string { + let bytes = 0; + let end = 0; + for (const character of value) { + const codePoint = character.codePointAt(0) ?? 0; + // A lone surrogate encodes as U+FFFD, three bytes, like any BMP point. + bytes += + codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + if (bytes > maxBytes) return value.slice(0, end).trimEnd(); + end += character.length; + } + return value; +} + function fitFallbackBaseName( configured: string, extension: string, maxUtf8Bytes: number, ): string { - let fallback = + const fallback = truncateUtf8( configured.length > 0 && !WINDOWS_RESERVED.test(configured) ? configured - : "download"; - while ( - fallback.length > 0 && - utf8Length(`${fallback}${extension}`) > maxUtf8Bytes - ) { - fallback = Array.from(fallback).slice(0, -1).join("").trimEnd(); - } + : "download", + maxUtf8Bytes - utf8Length(extension), + ); return fallback.length > 0 && !WINDOWS_RESERVED.test(fallback) ? fallback : "a"; diff --git a/tests/unit/browser-file-content.test.ts b/tests/unit/browser-file-content.test.ts index 76d78597..3b34ec9c 100644 --- a/tests/unit/browser-file-content.test.ts +++ b/tests/unit/browser-file-content.test.ts @@ -121,6 +121,31 @@ describe("browser file content policy", () => { ).toBe("d.bin"); }); + it("truncates a huge filename in linear time with the same result (Q-6.2-10)", () => { + const policy = { safeExtension: ".pdf", maxUtf8Bytes: 180 } as const; + expect( + sanitizeSuggestedFileName(`${"a".repeat(175)} bbbb.pdf`, policy), + ).toBe(`${"a".repeat(175)}.pdf`); + expect( + sanitizeSuggestedFileName(`${"가".repeat(100)}.pdf`, policy), + ).toBe(`${"가".repeat(58)}.pdf`); + expect( + sanitizeSuggestedFileName(`${"😀".repeat(50)}.pdf`, policy), + ).toBe(`${"😀".repeat(44)}.pdf`); + + // A server-supplied name used to be re-encoded whole once per dropped + // code point: O(n^2), so a 100k-character name froze the tab. + const encode = vi.spyOn(TextEncoder.prototype, "encode"); + try { + expect( + sanitizeSuggestedFileName("x".repeat(5_000), policy), + ).toBe(`${"x".repeat(176)}.pdf`); + expect(encode.mock.calls.length).toBeLessThan(10); + } finally { + encode.mockRestore(); + } + }); + it("keeps native files behind opaque refs and performs bounded reads", async () => { const policies = pngPolicies(); const vault = new BrowserFileVault({