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
20 changes: 20 additions & 0 deletions components/utils/base-64.utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,26 @@ describe("base-64.utils", () => {
expect(fromBase64("aGVsbG8=")).toBe("hello");
});

test("should decode base64 with line breaks and surrounding whitespace", () => {
expect(fromBase64("aGVs\nbG8=")).toBe("hello");
expect(fromBase64("aGVs\r\nbG8=")).toBe("hello");
expect(fromBase64(" aGVsbG8= ")).toBe("hello");
});

test("should decode multiple base64 strings, one per line", () => {
expect(fromBase64("aGVsbG8=\nd29ybGQ=")).toBe("hello\nworld");
});

test("should decode PEM-style wrapped base64 as a single message", () => {
const message =
"hello world this is a longer message for testing pem wrap";
const wrapped = Buffer.from(message)
.toString("base64")
.match(/.{1,20}/g)!
.join("\n");
expect(fromBase64(wrapped)).toBe(message);
});

test("should throw an error for an invalid Base64 string", () => {
expect(() => fromBase64("invalid_base64")).toThrow(
"Invalid Base64 input"
Expand Down
34 changes: 30 additions & 4 deletions components/utils/base-64.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,39 @@ export function toBase64(value: string) {
}
}

function decodeBase64Chunk(value: string): string {
const decoded = Buffer.from(value, "base64").toString("utf-8");
if (!isPrintableASCII(decoded)) {
throw new Error("Decoded string contains non-printable characters");
}
return decoded;
}

export function fromBase64(value: string): string {
try {
const decoded = Buffer.from(value, "base64").toString("utf-8");
if (!isPrintableASCII(decoded)) {
throw new Error("Decoded string contains non-printable characters");
const trimmed = value.trim();
if (!trimmed) {
return "";
}

const lines = trimmed
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);

if (lines.length > 1) {
const stripped = trimmed.replace(/\s/g, "");
const singleDecoded = decodeBase64Chunk(stripped);
const firstLineDecoded = decodeBase64Chunk(lines[0]);

// Multiple independent base64 strings (one per line) decode to the same
// output as the first line when joined; PEM-style wrapped input does not.
if (singleDecoded === firstLineDecoded) {
return lines.map((line) => decodeBase64Chunk(line)).join("\n");
}
}
return decoded;

return decodeBase64Chunk(trimmed.replace(/\s/g, ""));
} catch {
throw new Error("Invalid Base64 input");
}
Expand Down