codec.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { AUTH_LEASE_MAX_FRAME_BYTES, AuthLeaseProtocolError } from './contracts.js';
  2. const FRAME_PREFIX_BYTES = 4;
  3. export function encodeAuthLeaseFrame(value: unknown): Buffer {
  4. let payload: Buffer;
  5. try {
  6. payload = Buffer.from(JSON.stringify(value), 'utf8');
  7. } catch {
  8. throw new AuthLeaseProtocolError('INVALID_REQUEST');
  9. }
  10. if (payload.length === 0 || payload.length > AUTH_LEASE_MAX_FRAME_BYTES) {
  11. throw new AuthLeaseProtocolError('INVALID_REQUEST');
  12. }
  13. const prefix = Buffer.allocUnsafe(FRAME_PREFIX_BYTES);
  14. prefix.writeUInt32BE(payload.length, 0);
  15. return Buffer.concat([prefix, payload]);
  16. }
  17. export class AuthLeaseFrameDecoder {
  18. private buffer = Buffer.alloc(0);
  19. get bufferedBytes(): number {
  20. return this.buffer.length;
  21. }
  22. push(chunk: Uint8Array): unknown[] {
  23. if (chunk.byteLength === 0) return [];
  24. this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk)]);
  25. const frames: unknown[] = [];
  26. while (this.buffer.length >= FRAME_PREFIX_BYTES) {
  27. const payloadLength = this.buffer.readUInt32BE(0);
  28. if (payloadLength === 0 || payloadLength > AUTH_LEASE_MAX_FRAME_BYTES) {
  29. this.buffer = Buffer.alloc(0);
  30. throw new AuthLeaseProtocolError('INVALID_REQUEST');
  31. }
  32. const frameLength = FRAME_PREFIX_BYTES + payloadLength;
  33. if (this.buffer.length < frameLength) {
  34. if (this.buffer.length > AUTH_LEASE_MAX_FRAME_BYTES + FRAME_PREFIX_BYTES) {
  35. this.buffer = Buffer.alloc(0);
  36. throw new AuthLeaseProtocolError('INVALID_REQUEST');
  37. }
  38. return frames;
  39. }
  40. const payload = this.buffer.subarray(FRAME_PREFIX_BYTES, frameLength);
  41. this.buffer = this.buffer.subarray(frameLength);
  42. try {
  43. frames.push(JSON.parse(payload.toString('utf8')) as unknown);
  44. } catch {
  45. this.buffer = Buffer.alloc(0);
  46. throw new AuthLeaseProtocolError('INVALID_REQUEST');
  47. }
  48. }
  49. return frames;
  50. }
  51. }