Files
bennc/src/messages/basic.ts
Jack Hadrill 61b7c50868
Some checks failed
CI / build (push) Failing after 12s
CI / publish (push) Has been skipped
refactor: update romulus-js import path to @3t/romulus and adjust tests accordingly
2025-09-06 19:06:08 +01:00

45 lines
1.3 KiB
TypeScript

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");
}