Skip to content

Commit 221df51

Browse files
jxomampcode-com
andcommitted
feat(Base64): lenient decoding
Strip non-base64 characters before decoding instead of only stripping trailing padding. Amp-Thread-ID: https://ampcode.com/threads/T-019c079b-e704-766b-95e5-24dbb1dace30 Co-authored-by: Amp <amp@ampcode.com>
1 parent 28d28f6 commit 221df51

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/core/Base64.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ export declare namespace fromString {
238238
* @returns The Base64 decoded {@link ox#Bytes.Bytes}.
239239
*/
240240
export function toBytes(value: string): Bytes.Bytes {
241-
const base64 = value.replace(/=+$/, '')
241+
const base64 = value.replace(/[^A-Za-z0-9+/_-]/g, '')
242242

243243
const size = base64.length
244244

src/core/_test/Base64.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,16 @@ describe('toBytes', () => {
5959
Bytes.fromString('hello wo�d'),
6060
)
6161
})
62+
63+
test('strips invalid characters', () => {
64+
expect(Base64.toBytes('aGVsbG8!')).toStrictEqual(Bytes.fromString('hello'))
65+
expect(Base64.toBytes(' aGVsbG8 ')).toStrictEqual(
66+
Bytes.fromString('hello'),
67+
)
68+
expect(Base64.toBytes('aGVs\nbG8=')).toStrictEqual(
69+
Bytes.fromString('hello'),
70+
)
71+
})
6272
})
6373

6474
describe('toHex', () => {

0 commit comments

Comments
 (0)