import { encrypt, decrypt } from "@3t/romulus"; import { DEFAULT_KEY, MessageTypes } from "../common"; import { numberToUint16BE } from "../utilities/number"; import { packOutgoingPacket } from "./packet"; const MESSAGE_TYPE = numberToUint16BE(MessageTypes.Basic); export interface BasicMessage { data: Uint8Array; } /** * Create an outgoing basic message (0x0001) packet. * @param message The plaintext message to send. * @param key The key to encrypt the data with. * @returns An encrypted outgoing basic message (0x0001) packet. */ export function packBasicMessage( message: Uint8Array, key: Uint8Array = DEFAULT_KEY, ): Uint8Array { const data = encrypt(message, MESSAGE_TYPE, key); return packOutgoingPacket({ messageType: MESSAGE_TYPE, data: data, }); } /** * Unpack the data section of an incoming basic message (0x0001) message. * @param data The encrypted data section of an incoming basic message (0x0001) message. * @param key The key to decrypt the data with. * @returns The decrypted plaintext message. */ export function unpackBasicMessage( data: Uint8Array, key: Uint8Array = DEFAULT_KEY, ): Uint8Array { const result = decrypt(data, MESSAGE_TYPE, key); if (result.success) { return result.plaintext; } throw new Error("Failed to decrypt basic message"); }