MLS implementation

This commit is contained in:
Danny Morabito 2025-03-11 20:50:33 +01:00
parent fc6e1c59a5
commit a69e78389f
Signed by: dannym
GPG key ID: 7CC8056A5A04557E
5 changed files with 743 additions and 6 deletions

View file

@ -8,6 +8,7 @@ import {
encryptionKey,
encryptUint8Array,
} from "./utils/encryption.ts";
import { NSec } from "@nostr/tools/nip19";
export function isLocalhost(req: Request): boolean {
const url = new URL(req.url);
@ -61,9 +62,52 @@ export async function getCCNPubkey(): Promise<string> {
return ccnPublicKey;
}
export async function getMLSPrivateKey(): Promise<NSec> {
const mlsPrivPath = await getEveFilePath("mls.priv");
const doWeHaveKey = await exists(mlsPrivPath);
if (doWeHaveKey) {
const encryptedPrivateKey = Deno.readTextFileSync(mlsPrivPath);
const decryptedPrivateKey = decryptUint8Array(
decodeBase64(encryptedPrivateKey),
encryptionKey,
);
return nostrTools.nip19.nsecEncode(decryptedPrivateKey);
}
const mlsPrivateKey = nostrTools.generateSecretKey();
const encryptedPrivateKey = encryptUint8Array(mlsPrivateKey, encryptionKey);
Deno.writeTextFileSync(mlsPrivPath, encodeBase64(encryptedPrivateKey));
return nostrTools.nip19.nsecEncode(mlsPrivateKey);
}
export async function getCCNPrivateKey(): Promise<Uint8Array> {
const encryptedPrivateKey = Deno.readTextFileSync(
await getEveFilePath("ccn.priv"),
);
return decryptUint8Array(decodeBase64(encryptedPrivateKey), encryptionKey);
}
/**
* Compares two byte-like objects in a constant-time manner to prevent timing attacks.
*
* @param a - First byte-like object to compare
* @param b - Second byte-like object to compare
* @returns boolean indicating whether the inputs contain identical bytes
*/
export function bytesEqual<
T extends Uint8Array | number[] | string,
>(a: T, b: T): boolean {
const aLength = a.length;
const bLength = b.length;
let result = aLength !== bLength ? 1 : 0;
const maxLength = Math.max(aLength, bLength);
for (let i = 0; i < maxLength; i++) {
const aVal = i < aLength
? (typeof a === "string" ? a.charCodeAt(i) : a[i])
: 0;
const bVal = i < bLength
? (typeof b === "string" ? b.charCodeAt(i) : b[i])
: 0;
result |= aVal ^ bVal;
}
return result === 0;
}