const test = require("node:test"); const assert = require("node:assert"); const { SIGNATURE, isPrefix, parse } = require("./proxy-protocol"); const header = (family, source, destination, command = 0x21) => { const body = Buffer.concat([source, destination, Buffer.alloc(4)]); const buffer = Buffer.alloc(16 + body.length); SIGNATURE.copy(buffer, 0); buffer[12] = command; buffer[13] = family; buffer.writeUInt16BE(body.length, 14); body.copy(buffer, 16); return buffer; }; test("parses an IPv4 source address", () => { const parsed = parse(header(0x11, Buffer.from([203, 0, 113, 7]), Buffer.from([10, 0, 0, 1]))); assert.strictEqual(parsed.ip, "203.0.113.7"); assert.strictEqual(parsed.length, 16 + 12); }); test("parses an IPv6 source address", () => { const source = Buffer.from([0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); const parsed = parse(header(0x21, source, Buffer.alloc(16))); assert.strictEqual(parsed.ip, "2001:db8:0:0:0:0:0:1"); }); test("returns null until the header is complete", () => { const buffer = header(0x11, Buffer.from([1, 2, 3, 4]), Buffer.from([5, 6, 7, 8])); assert.strictEqual(parse(buffer.subarray(0, 10)), null); assert.strictEqual(parse(buffer.subarray(0, 20)), null); }); test("has no address for a LOCAL command", () => { const parsed = parse(header(0x00, Buffer.alloc(0), Buffer.alloc(0), 0x20)); assert.strictEqual(parsed.ip, null); }); test("tells the signature apart from a TLS handshake", () => { assert.strictEqual(isPrefix(SIGNATURE.subarray(0, 5)), true); assert.strictEqual(isPrefix(SIGNATURE), true); assert.strictEqual(isPrefix(Buffer.from([0x16, 0x03, 0x01, 0x00])), false); });