feat: implement end-to-end encryption for relay connections

This commit is contained in:
Mohamed Boudra
2026-02-03 13:40:44 +07:00
parent a7a39ffd01
commit 6ed70e24c7
23 changed files with 1004 additions and 115 deletions
+12
View File
@@ -0,0 +1,12 @@
import { fromByteArray, toByteArray } from "base64-js";
export function arrayBufferToBase64(buffer: ArrayBuffer): string {
return fromByteArray(new Uint8Array(buffer));
}
export function base64ToArrayBuffer(base64: string): ArrayBuffer {
const bytes = toByteArray(base64);
const out = new Uint8Array(bytes.byteLength);
out.set(bytes);
return out.buffer;
}
+3 -20
View File
@@ -1,3 +1,4 @@
/// <reference lib="dom" />
/**
* E2EE crypto primitives using WebCrypto API.
*
@@ -6,6 +7,8 @@
* - AES-256-GCM for authenticated encryption
*/
import { arrayBufferToBase64, base64ToArrayBuffer } from "./base64.js";
const ECDH_ALGORITHM = { name: "ECDH", namedCurve: "P-256" };
const AES_ALGORITHM = { name: "AES-GCM", length: 256 };
const IV_LENGTH = 12;
@@ -127,23 +130,3 @@ export async function decrypt(
return plaintext;
}
}
// --- Helpers ---
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
+2 -20
View File
@@ -1,3 +1,4 @@
/// <reference lib="dom" />
/**
* Encrypted channel that wraps a WebSocket-like transport.
*
@@ -13,6 +14,7 @@ import {
encrypt,
decrypt,
} from "./crypto.js";
import { arrayBufferToBase64, base64ToArrayBuffer } from "./base64.js";
export interface Transport {
send(data: string | ArrayBuffer): void;
@@ -193,23 +195,3 @@ export class EncryptedChannel {
return this.state === "open";
}
}
// --- Helpers ---
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}