const ed = require('@noble/ed25519'); /** * Represents an ECC key manager that can generate and sign messages using Ed25519 keys. */ export class ECCManager { /** * Initializes a new ECC key manager with a new random private key and its corresponding public key. * @returns {Promise} A Promise that resolves to the new ECCManager object. */ static async create() { const eccManager = new ECCManager(); eccManager.CSK = ed.utils.randomPrivateKey(); eccManager.CVK = await ed.getPublicKey(eccManager.CSK); return eccManager; } /** * Creates a new ECC key manager instance with the given private and public keys. * @param {Uint8Array} privateKey - The private key for the ECC key manager. * @param {Uint8Array} publicKey - The public key for the ECC key manager. */ constructor(privateKey, publicKey) { this.CSK = privateKey; this.CVK = publicKey; } /** * Creates a digital signature for the specified message using the client's private key. * @param {string} msg - The message to sign. * @returns {Promise} A Promise that resolves to the digital signature as a string. */ async signMsg(msg) { return ed.sign(msg, this.CSK); } /** * Adds a header with the digital signature of a given payload to a set of HTTP headers. * @async * @param {Headers} currentHeaders - The current set of HTTP headers to add the signature header to. * @param {Object} payload - The payload object to sign and add to the headers. * @returns {Promise} A Promise that resolves to the updated set of HTTP headers. */ async addPayloadSignatureHeader(currentHeaders, payload) { // Convert the payload to a Uint8Array using JSON encoding const encoder = new TextEncoder(); const payloadBytes = encoder.encode(JSON.stringify(payload)); // Sign the payload using the ed25519 algorithm and the client's private key const signature = await ed.sign(payloadBytes, this.CSK); //FIXME depricated function | Encode the signature using base64 const base64Signature = btoa(String.fromCharCode.apply(null, signature)); // Append the X-Payload-Signature header to the given set of HTTP headers, with the value set to the base64-encoded signature currentHeaders.append("X-Payload-Signature", base64Signature); // Return the updated set of HTTP headers as a Promise return currentHeaders; } }