import { test } from 'node:test'; import assert from 'node:assert/strict'; import { encode, decode } from '../code.js'; test('decode reads the host-bearing short-key format (h/p/t/n/s/fp)', () => { const code = encode({ v: 1, h: '100.64.0.5', p: 9110, t: 'deadbeefcafe1234', n: 'prod-3', s: 'wss', fp: 'AB:CD:EF:01' }); assert.ok(code.startsWith('mhu1_')); const d = decode(code); assert.equal(d.host, '100.64.0.5'); assert.equal(d.port, 9110); assert.equal(d.token, 'deadbeefcafe1234'); assert.equal(d.label, 'prod-3'); assert.equal(d.scheme, 'wss'); assert.equal(d.fp, 'AB:CD:EF:01'); }); test('decode is tolerant of the legacy long-key format (port/token/label, no host -> ws)', () => { const d = decode(encode({ v: 1, port: 9110, token: 'token-abc', label: 'localhost' })); assert.equal(d.host, undefined); assert.equal(d.port, 9110); assert.equal(d.token, 'token-abc'); assert.equal(d.label, 'localhost'); assert.equal(d.scheme, 'ws'); }); test('decode rejects a string without the mhu1_ prefix', () => { assert.throws(() => decode('hello-world'), /missing "mhu1_" prefix/); }); test('decode rejects a wrong-version payload', () => { const bad = 'mhu1_' + Buffer.from( JSON.stringify({ v: 2, port: 9110, token: 'x', label: 'l' }), 'utf8', ).toString('base64url'); assert.throws(() => decode(bad), /unsupported version/); }); test('decode rejects garbage after the prefix', () => { assert.throws(() => decode('mhu1_!!!not-base64-or-json!!!'), /Invalid code/); }); test('decode rejects an empty payload', () => { assert.throws(() => decode('mhu1_'), /empty payload/); }); test('decode rejects a non-string input', () => { assert.throws(() => decode(null), /expected a string/); }); test('decode rejects a missing token', () => { const bad = 'mhu1_' + Buffer.from( JSON.stringify({ v: 1, port: 9110, label: 'l' }), 'utf8', ).toString('base64url'); assert.throws(() => decode(bad), /token/); }); test('decode rejects a non-number port', () => { const bad = 'mhu1_' + Buffer.from( JSON.stringify({ v: 1, port: 'nope', token: 'x', label: 'l' }), 'utf8', ).toString('base64url'); assert.throws(() => decode(bad), /port/); });