Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(utils): handle non-ASCII text in browser base64 helpers (#16880)

mengnanjiugaipeifense94325a6311c5
diff --git a/packages/utils/src/base64.test.ts b/packages/utils/src/base64.test.ts
index 8869970b9c4..4a9d30b2a5d 100644
--- a/packages/utils/src/base64.test.ts
+++ b/packages/utils/src/base64.test.ts
@@ -114,4 +114,27 @@ describe('base64 utilities', () => {
});
});
});
+
+ describe('non-ASCII in the browser environment (native btoa/atob)', () => {
+ it('should round-trip UTF-8 text that native btoa would reject as raw input', () => {
+ const originalBtoa = global.btoa;
+ const originalAtob = global.atob;
+ // Faithful to real browsers: btoa throws on any code point > U+00FF,
+ // and atob returns a Latin1 binary string (not a UTF-8-decoded string).
+ global.btoa = (s: string) => {
+ if (/[^\u0000-\u00FF]/.test(s)) throw new Error('InvalidCharacterError');
+ return Buffer.from(s, 'latin1').toString('base64');
+ };
+ global.atob = (b: string) => Buffer.from(b, 'base64').toString('latin1');
+
+ try {
+ const input = '中文测试 😀 café';
+ // Before the fix this threw InvalidCharacterError on encode.
+ expect(decodeFromBase64(encodeToBase64(input))).toBe(input);
+ } finally {
+ global.btoa = originalBtoa;
+ global.atob = originalAtob;
+ }
+ });
+ });
});
diff --git a/packages/utils/src/base64.ts b/packages/utils/src/base64.ts
index ac006de1e6a..0448982ec87 100644
--- a/packages/utils/src/base64.ts
+++ b/packages/utils/src/base64.ts
@@ -12,8 +12,11 @@ import { Buffer } from 'buffer.js';
*/
export const encodeToBase64 = (input: string): string => {
if (typeof btoa === 'function') {
- // Browser environment
- return btoa(input);
+ // Browser environment: `btoa` only accepts Latin1 and throws on any code
+ // point > U+00FF, so UTF-8-encode first and map each byte to a Latin1 char.
+ const bytes = new TextEncoder().encode(input);
+ const binary = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join('');
+ return btoa(binary);
} else {
// Node.js environment
return Buffer.from(input, 'utf8').toString('base64');
@@ -27,8 +30,11 @@ export const encodeToBase64 = (input: string): string => {
*/
export const decodeFromBase64 = (input: string): string => {
if (typeof atob === 'function') {
- // Browser environment
- return atob(input);
+ // Browser environment: `atob` yields a Latin1 binary string, so read the
+ // bytes back out and decode them as UTF-8.
+ const binary = atob(input);
+ const bytes = Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);
+ return new TextDecoder().decode(bytes);
} else {
// Node.js environment
return Buffer.from(input, 'base64').toString('utf8');