Skip to content

Build your personal knowledge base with Trilium Notes

perf(sync): platform-native base64 via crypto provider

Elian Doran2beeed20a0fe
diff --git a/apps/server/src/crypto_provider.spec.ts b/apps/server/src/crypto_provider.spec.ts
new file mode 100644
index 0000000000..3b32daa72f
--- /dev/null
+++ b/apps/server/src/crypto_provider.spec.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import NodejsCryptoProvider from "./crypto_provider.js";
+
+const provider = new NodejsCryptoProvider();
+
+describe("NodejsCryptoProvider base64", () => {
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder();
+ // RFC 4648 §10 test vectors
+ const vectors: [string, string][] = [
+ ["", ""],
+ ["f", "Zg=="],
+ ["fo", "Zm8="],
+ ["foo", "Zm9v"],
+ ["foob", "Zm9vYg=="],
+ ["fooba", "Zm9vYmE="],
+ ["foobar", "Zm9vYmFy"]
+ ];
+
+ it("encodes the RFC 4648 test vectors", () => {
+ for (const [input, expected] of vectors) {
+ expect(provider.base64Encode(encoder.encode(input))).toBe(expected);
+ }
+ });
+
+ it("decodes the RFC 4648 test vectors", () => {
+ for (const [input, expected] of vectors) {
+ expect(decoder.decode(provider.base64Decode(expected))).toBe(input);
+ }
+ });
+
+ it("round-trips every byte value 0..255", () => {
+ const bytes = new Uint8Array(256);
+ for (let i = 0; i < 256; i++) bytes[i] = i;
+ expect(Array.from(provider.base64Decode(provider.base64Encode(bytes)))).toEqual(Array.from(bytes));
+ });
+
+ it("round-trips a large buffer", () => {
+ const bytes = new Uint8Array(100_000);
+ for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 31 + 7) & 0xff;
+ expect(Array.from(provider.base64Decode(provider.base64Encode(bytes)))).toEqual(Array.from(bytes));
+ });
+
+ it("encodes a Uint8Array view with a non-zero byteOffset (zero-copy path stays correct)", () => {
+ // The native implementation views the backing ArrayBuffer via byteOffset/byteLength;
+ // a subarray must encode only its own window, not the whole backing buffer.
+ const backing = new Uint8Array([0xff, 0xff, 0x66, 0x6f, 0x6f, 0xff]); // "foo" in the middle
+ expect(provider.base64Encode(backing.subarray(2, 5))).toBe("Zm9v");
+ });
+
+ it("returns empty for empty input", () => {
+ expect(provider.base64Encode(new Uint8Array(0))).toBe("");
+ expect(provider.base64Decode("")).toHaveLength(0);
+ });
+});
diff --git a/apps/server/src/crypto_provider.ts b/apps/server/src/crypto_provider.ts
index b2030babc9..35c39db4bc 100644
--- a/apps/server/src/crypto_provider.ts
+++ b/apps/server/src/crypto_provider.ts
@@ -57,4 +57,14 @@ export default class NodejsCryptoProvider implements CryptoProvider {
return crypto.timingSafeEqual(bufA, bufB);
}
+
+ base64Encode(bytes: Uint8Array): string {
+ // View the existing memory (zero-copy) rather than reallocating, then let Node's native
+ // (C++) encoder do the work — orders of magnitude faster than a per-byte JS loop.
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
+ }
+
+ base64Decode(base64: string): Uint8Array {
+ return Buffer.from(base64, "base64");
+ }
}
diff --git a/apps/standalone/src/lightweight/crypto_provider.spec.ts b/apps/standalone/src/lightweight/crypto_provider.spec.ts
index dfbf65e1d6..a21e754b3d 100644
--- a/apps/standalone/src/lightweight/crypto_provider.spec.ts
+++ b/apps/standalone/src/lightweight/crypto_provider.spec.ts
@@ -111,3 +111,48 @@ describe("AesJsCipher (via createCipheriv/createDecipheriv)", () => {
expect(out[15]).toBe(0);
});
});
+
+describe("BrowserCryptoProvider base64", () => {
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder();
+ // RFC 4648 §10 test vectors
+ const vectors: [string, string][] = [
+ ["", ""],
+ ["f", "Zg=="],
+ ["fo", "Zm8="],
+ ["foo", "Zm9v"],
+ ["foob", "Zm9vYg=="],
+ ["fooba", "Zm9vYmE="],
+ ["foobar", "Zm9vYmFy"]
+ ];
+
+ it("encodes the RFC 4648 test vectors", () => {
+ for (const [input, expected] of vectors) {
+ expect(provider.base64Encode(encoder.encode(input))).toBe(expected);
+ }
+ });
+
+ it("decodes the RFC 4648 test vectors", () => {
+ for (const [input, expected] of vectors) {
+ expect(decoder.decode(provider.base64Decode(expected))).toBe(input);
+ }
+ });
+
+ it("round-trips every byte value 0..255", () => {
+ const bytes = new Uint8Array(256);
+ for (let i = 0; i < 256; i++) bytes[i] = i;
+ expect(Array.from(provider.base64Decode(provider.base64Encode(bytes)))).toEqual(Array.from(bytes));
+ });
+
+ it("round-trips a large buffer spanning multiple 32K chunks", () => {
+ const bytes = new Uint8Array(100_000); // > CHUNK (0x8000), forces the multi-chunk path
+ for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 31 + 7) & 0xff;
+ const round = provider.base64Decode(provider.base64Encode(bytes));
+ expect(Array.from(round)).toEqual(Array.from(bytes));
+ });
+
+ it("encodes a Uint8Array view (subarray with a non-zero offset)", () => {
+ const backing = new Uint8Array([0xff, 0xff, 0x66, 0x6f, 0x6f, 0xff]); // "foo" in the middle
+ expect(provider.base64Encode(backing.subarray(2, 5))).toBe("Zm9v");
+ });
+});
diff --git a/apps/standalone/src/lightweight/crypto_provider.ts b/apps/standalone/src/lightweight/crypto_provider.ts
index 128031bba2..3712d4adfc 100644
--- a/apps/standalone/src/lightweight/crypto_provider.ts
+++ b/apps/standalone/src/lightweight/crypto_provider.ts
@@ -94,6 +94,28 @@ export default class BrowserCryptoProvider implements CryptoProvider {
}
return result === 0;
}
+
+ base64Encode(bytes: Uint8Array): string {
+ // Build the binary string in 32K chunks via fromCharCode.apply. This avoids both the
+ // pathological per-byte string concatenation of a naive loop and the call-stack limit
+ // of applying fromCharCode to the whole array at once.
+ const CHUNK = 0x8000; // 32768
+ let binary = "";
+ for (let i = 0; i < bytes.length; i += CHUNK) {
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK) as unknown as number[]);
+ }
+ return btoa(binary);
+ }
+
+ base64Decode(base64: string): Uint8Array {
+ const binary = atob(base64);
+ const len = binary.length;
+ const bytes = new Uint8Array(len);
+ for (let i = 0; i < len; i++) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return bytes;
+ }
}
/**
diff --git a/packages/trilium-core/src/services/encryption/crypto.ts b/packages/trilium-core/src/services/encryption/crypto.ts
index 809c131acf..3b6d561266 100644
--- a/packages/trilium-core/src/services/encryption/crypto.ts
+++ b/packages/trilium-core/src/services/encryption/crypto.ts
@@ -39,6 +39,15 @@ export interface CryptoProvider {
* @returns true if arrays are equal, false otherwise
*/
constantTimeCompare(a: Uint8Array, b: Uint8Array): boolean;
+
+ /**
+ * Encodes raw bytes to a standard (RFC 4648) base64 string. Platform-optimized: server and
+ * desktop use Node's native `Buffer`; standalone uses a chunked browser implementation.
+ */
+ base64Encode(bytes: Uint8Array): string;
+
+ /** Decodes a standard (RFC 4648) base64 string back into raw bytes. */
+ base64Decode(base64: string): Uint8Array;
}
let crypto: CryptoProvider | null = null;
diff --git a/packages/trilium-core/src/services/utils/binary.spec.ts b/packages/trilium-core/src/services/utils/binary.spec.ts
index 7ef6b82c72..f6e6af63ea 100644
Binary files a/packages/trilium-core/src/services/utils/binary.spec.ts and b/packages/trilium-core/src/services/utils/binary.spec.ts differ
diff --git a/packages/trilium-core/src/services/utils/binary.ts b/packages/trilium-core/src/services/utils/binary.ts
index a2dac2f365..7e5cfa932c 100644
--- a/packages/trilium-core/src/services/utils/binary.ts
+++ b/packages/trilium-core/src/services/utils/binary.ts
@@ -1,6 +1,8 @@
import chardet from "chardet";
import stripBom from "strip-bom";
+import { getCrypto } from "../encryption/crypto.js";
+
const utf8Decoder = new TextDecoder("utf-8");
const utf8Encoder = new TextEncoder();
@@ -11,28 +13,18 @@ export function concat2(a: Uint8Array, b: Uint8Array): Uint8Array {
return out;
}
+/**
+ * Encodes a string (UTF-8) or raw bytes to a standard base64 string. The heavy lifting is
+ * delegated to the active crypto provider so each platform uses its fastest implementation
+ * (native `Buffer` on server/desktop, a chunked encoder in the browser).
+ */
export function encodeBase64(stringOrBuffer: string | Uint8Array): string {
- const bytes = wrapStringOrBuffer(stringOrBuffer);
- let binary = "";
- const len = bytes.length;
-
- for (let i = 0; i < len; i++) {
- binary += String.fromCharCode(bytes[i]);
- }
-
- return btoa(binary);
+ return getCrypto().base64Encode(wrapStringOrBuffer(stringOrBuffer));
}
+/** Decodes a standard base64 string into raw bytes via the active crypto provider. */
export function decodeBase64(base64: string): Uint8Array {
- const binary = atob(base64);
- const len = binary.length;
-
- const bytes = new Uint8Array(len);
- for (let i = 0; i < len; i++) {
- bytes[i] = binary.charCodeAt(i);
- }
-
- return bytes;
+ return getCrypto().base64Decode(base64);
}
export function decodeUtf8(stringOrBuffer: string | Uint8Array) {